var PersoOption = Class.create();

PersoOption.prototype = {
	initialize: function(fields){
		this.doProcessCheckbox = $('cbo_personalisation-yes');
		this.optionDropdown = $('personalisation_option');
		this.errorColour = '#ff0000';
		this.okColour = '#d7d7d7';
		this.fields = fields;
	},
	getPersoFields: function()
	{
		var persoCode = $F(this.optionDropdown);
		var length = persoCode.length;
		if(persoCode.substr(length-1, length) == 'I')
		{
			return this.fields.initial;
		}
		if( this.lineCount(persoCode, '1') )
		{
			return this.fields.one;
		}
		if( this.lineCount(persoCode, '2') )
		{
			return this.fields.two;
		}
		if( this.lineCount(persoCode, '3') )
		{
			return this.fields.three;
		}
		return false;
	},
	lineCount: function(string, compare)
	{
		var length = string.length;
		if(	
			string.substr(length-2, 1) == compare ||
			string.substr(length-3, 1) == compare
		)
		{
			return true;
		}
		return false;
	},
	validate: function()
	{
		if(this.doProcessCheckbox.checked)
		{
			var fields = this.getPersoFields();
			this.valid = true;
			if(fields !== false)
			{
				fields.each(this.checkField.bind(this));
			}
			else
			{
				this.checkField(this.optionDropdown);
				alert('Please select the personalisation option you wish to use from the dropdown highlighted below.');
				return false;
			}
			if(this.valid == false)
			{
				alert('Please enter your personalisation details in the text box(es) provided.');
			}
			return this.valid;
		}
		return true;
	},
	checkField: function(id)
	{
		var element = $(id);
		if(element == this.optionDropdown)
		{
			var eventHook = 'change';
		}
		else
		{
			var eventHook = 'keyup';
		}
		Event.stopObserving(element, eventHook);
		this.emptyColours(element);
		Event.observe(element, eventHook, this.changeEvent.bind(this));
	},
	changeEvent: function(e)
	{
		this.emptyColours(Event.element(e), 'keyup');
	},
	emptyColours: function(element)
	{
		if(this.doProcessCheckbox.checked)
		{
			if($F(element) == '')
			{
				element.setStyle({borderColor: this.errorColour}).focus();
				this.valid = false;
			}
			else
			{
				element.setStyle({borderColor: this.okColour})
			}
		}
	}
}