palm.forms = {
	init: function(){
		window.addEvent("domready", function(){
			palm.forms.CS.init();
			for(formToCheck in palm.forms.instances){
				if($(formToCheck)){
					palm.forms.instances[formToCheck].init();
				}
			}
		});
	},
	instances: {
		/*
		 * Describes each form and contains validation logic and functions
		*/
		"contactUsForm": {
			btnSend: {},
			error: "",
			error_info: "",
			str: "",
			init: function(){
				this.str = "";
				this.btnSend = $('btnSend');
				this.error = $('error');
				this.error_info = $('error_info');

				//Replace the standard input submit button with styled button in the DOM and update local reference
				this.btnSend = palm.forms.replaceSubmitBtn(this.btnSend);
				
				//Attach onclick event to the JS submit button
				this.btnSend.addEvent("click",function(){
					palm.forms.instances.contactUsForm.str = palm.forms.instances.contactUsForm.validate();
					if(palm.forms.instances.contactUsForm.str.length>0){
						palm.forms.instances.contactUsForm.error.setStyle("display","")
						palm.forms.instances.contactUsForm.error_info.set('html',palm.forms.instances.contactUsForm.str);
					}
					else{
						this.disabled=true;
						$('contactUsForm').submit();
						return false;
					}
					palm.forms.instances.contactUsForm.str = "";
				});
			},
			fields: {
				firstname: "firstname",
				lastname: "lastname",
				email: "email",
				countrySelected: "country",
				contactEnquiry: "messageType"
			},
			validate: function(){
				this.elements = $("form_area").getElements("LABEL");
				this.error.setStyle("display","none")
				this.elements.each(function(el){
					el.className = "";		   
				});
				if(palm.forms.txtValueisNull(this.fields.firstname)){
					$(this.fields.firstname).getParent().getFirst().className = "error_info";
					this.str += "&bull; please check your First name<br/>";	
				}
				if(palm.forms.txtValueisNull(this.fields.lastname)){
					$(this.fields.lastname).getParent().getFirst().className = "error_info";
					this.str += "&bull; please check your Last name<br/>";	
				}
				if(palm.forms.txtValueisNull(this.fields.email) || !palm.forms.verifyAddress(this.fields.email)){
					$(this.fields.email).getParent().getFirst().className = "error_info";
					this.str += "&bull; please check your Email address<br/>";	
				}
				if(palm.forms.selectValueIsNull(this.fields.countrySelected)){
					$(this.fields.countrySelected).getParent().getParent().getFirst().className = "error_info";
					this.str += "&bull; please check your Country<br/>";	
				}		
				if(palm.forms.selectValueIsNull(this.fields.contactEnquiry)){
					$(this.fields.contactEnquiry).getParent().getParent().getFirst().className = "error_info";
					this.str += "&bull; please check your Nature of enquiry<br/>";	
				}
				return this.str;
			}
		},
		"contactSalesForm": {
			btnSend: {},
			error: "",
			error_info: "",
			str: "",
			init: function(){
				this.str = "";
				this.btnSend = $('btnSend');
				this.error = $('error');
				this.error_info = $('error_info');

				this.functions.paginateForm();
				this.functions.showHideRadioText();
				this.functions.showHideSelectText();
			},
			fields: {
				title: "title",
				firstname: "firstname",
				lastname: "lastname",
				email: "email",
				confirmemail: "email_confirm",
				contactType: "contactType",
				contactEnquiry: "messageType",
				/* developmentNameOC: "developmentNameOC",
				developmentNameUC: "developmentNameUC",
				developmentNameTrump: "developmentNameTrump", */
				developmentNameMarina: "developmentNameMarina",
				developmentNamePlots: "developmentNamePlots",
				country: "country",
				nationality: "nationality",
				individualOrganisationInd: "individualOrganisationInd",
				individualOrganisationOrg: "individualOrganisationOrg",
				individualOrganisationOrgName: "individualOrganisationOrgName",
				mobilephoneCode: "mobilephoneCode",
				mobilephoneArea: "mobilephoneArea",
				mobilephoneNumber: "mobilephoneNumber"
			},
			validate: function(){
				this.elements = $("form_area").getElements("LABEL");
				this.error.setStyle("display","none");
				this.elements.each(function(el){
					el.className = "";		   
				});

				if(palm.forms.selectValueIsNull(this.fields.title)){
					$(this.fields.title).getParent().getParent().getFirst().className = "error_info";
					this.str += "&bull; please check your Title<br/>";
				}
				if(palm.forms.txtValueisNull(this.fields.firstname)){
					$(this.fields.firstname).getParent().getFirst().className = "error_info";
					this.str += "&bull; please check your First name<br/>";	
				}
				if(palm.forms.txtValueisNull(this.fields.lastname)){
					$(this.fields.lastname).getParent().getFirst().className = "error_info";
					this.str += "&bull; please check your Last name<br/>";	
				}
				if(palm.forms.txtValueisNull(this.fields.email) || !palm.forms.verifyAddress(this.fields.email)){
					$(this.fields.email).getParent().getFirst().className = "error_info";
					this.str += "&bull; please check your Email address<br/>";	
				}else if(palm.forms.txtValueisNull(this.fields.confirmemail) || $(this.fields.email).value!=$(this.fields.confirmemail).value){
					$(this.fields.email).getParent().getFirst().className = "error_info";
					$(this.fields.confirmemail).getParent().getFirst().className = "error_info";
					this.str += "&bull; your email addresses do not match<br/>";	
				}else if(palm.forms.chkByAjax("email",$(this.fields.email).value) == "0"){
					$(this.fields.email).getParent().getFirst().className = "error_info";
					this.str += "&bull; we have already received a sales enquiry from that email address<br/>";	
				}	
				if(palm.forms.selectValueIsNull(this.fields.contactType)){
					$(this.fields.contactType).getParent().getParent().getFirst().className = "error_info";
					this.str += "&bull; please check your Contact preference<br/>";	
				/* }
				if(palm.forms.chkBoxUnChecked(this.fields.developmentNameOC)&&palm.forms.chkBoxUnChecked(this.fields.developmentNameUC)&&palm.forms.chkBoxUnChecked(this.fields.developmentNameTrump)&&palm.forms.chkBoxUnChecked(this.fields.developmentNameMarina)){
					$(this.fields.developmentNameOC).getParent().getParent().getParent().getFirst().className = "error_info";
					this.str += "&bull; please select one or more Development name<br/>"; */
				}
				if(palm.forms.chkBoxUnChecked(this.fields.developmentNameMarina)&&palm.forms.chkBoxUnChecked(this.fields.developmentNamePlots)){
					$(this.fields.developmentNameOC).getParent().getParent().getParent().getFirst().className = "error_info";
					this.str += "&bull; please select one or more Development name<br/>";	
					
				}
				if(palm.forms.selectValueIsNull(this.fields.country)){
					$(this.fields.country).getParent().getParent().getFirst().className = "error_info";
					this.str += "&bull; please check your Country<br/>";
				}
				if(palm.forms.selectValueIsNull(this.fields.nationality)){
					$(this.fields.nationality).getParent().getParent().getFirst().className = "error_info";
					this.str += "&bull; please check your Nationality<br/>";
				}
				if(palm.forms.chkBoxUnChecked(this.fields.individualOrganisationInd)&&palm.forms.chkBoxUnChecked(this.fields.individualOrganisationOrg)){
					$(this.fields.individualOrganisationInd).getParent().getParent().getParent().getFirst().className = "error_info";
					this.str += "&bull; please state whether you are an Individual or Organisation<br/>";
				}else if(!palm.forms.chkBoxUnChecked(this.fields.individualOrganisationOrg)&&palm.forms.txtValueisNull(this.fields.individualOrganisationOrgName)){
					$(this.fields.individualOrganisationInd).getParent().getParent().getParent().getFirst().className = "error_info";
					this.str += "&bull; please state your Organisation Name<br/>";
				}
				if(palm.forms.selectValueIsNull(this.fields.mobilephoneCode)||palm.forms.txtValueisNull(this.fields.mobilephoneArea)||palm.forms.txtValueisNull(this.fields.mobilephoneNumber)){
					$(this.fields.mobilephoneCode).getParent().getParent().getParent().getParent().getFirst().className = "error_info";
					this.str += "&bull; please check your Mobile Number<br/>";
				}
				
				return this.str;
			},
			functions: {
				doCheck: function(){
					palm.forms.instances.contactSalesForm.str = palm.forms.instances.contactSalesForm.validate();
					if(palm.forms.instances.contactSalesForm.str.length>0){
						palm.forms.instances.contactSalesForm.error.setStyle("display","")
						palm.forms.instances.contactSalesForm.error_info.set('html',palm.forms.instances.contactSalesForm.str);
						palm.forms.instances.contactSalesForm.str = "";
						return false;
					}
					palm.forms.instances.contactSalesForm.str = "";
					return true;
				},
				doShowHide: function(id,item,value){
					var el = $(id);
					if($(el).get(item) == value){
						$(id+'Name').getParent().setStyle('display','block');
					}else{
						$(id+'Name').getParent().setStyle('display','none');
					}
				},
				showHideRadioText: function(){
					$$('input.showtextchecked').each(function(el) {
						var id = $(el).get('id');
						if(!$(el).get('checked')){
							$(id+'Name').getParent().setStyle('display','none');
						}
						
						var groupName = $(el).get('name');
						
						$$('input[name="'+groupName+'"]').addEvent("change", function() {
							palm.forms.instances.contactSalesForm.functions.doShowHide(id,'checked',true);
						});
						
						$$('input[name="'+groupName+'"]').addEvent("click", function() {
							palm.forms.instances.contactSalesForm.functions.doShowHide(id,'checked',true);
						});
					});
				},
				showHideSelectText: function(){
					$$('select.showtextchanged').each(function(el) {
						var id = $(el).get('id');
						if($(el).get('value') != "Other"){
							$(id+'Name').getParent().setStyle('display','none');
						}
							
						$(el).addEvent("change", function() {
							palm.forms.instances.contactSalesForm.functions.doShowHide(id,'value',"Other");
						});
					});
				},
				paginateTo: function(s){
					if(this.doCheck()){
						var thisButtonSet = $$('#form_area fieldset.paginated-form');
						
						thisButtonSet.setStyles(
						{
							'display':'none'
						});
						
						$$(thisButtonSet[s]).setStyle('display','block');			
					}
				},
				paginateForm: function(){
					$$('#form_area fieldset.paginated-form').setStyles(
						{
							'display':'none'
						}	
					);
					
					if($('btnSend')) { $('btnSend').getParent().setStyle('display','none'); }
					
					$$('#form_area fieldset.paginated-form')[0].setStyle('display','block');
					
					var forms = $$('#form_area fieldset.paginated-form');
					
					for(var i=0, thisEl="";i<forms.length;i++){		
						thisEl = $(forms[i]);
						
						var divTopID = 'pagination-top-outer-'+i;
						var divBottomID = 'pagination-bottom-outer-'+i;
						
						var liID = 'pagination-container-'+i;
					
						var divContainerTop = new Element('div',
						{
							'id': divTopID,
							'class': 'pagination-top',
							'styles':
							{
								'width': '100%',
								'float': 'left'
							}
						});
								
						$(thisEl).grab(divContainerTop,'top');
						
						for(var j=0;j<4;j++){
							var liID = 'pagination-container-'+i+'-'+j;
							var pagID = 'pagination-pag-'+i+'-'+j;
					
							newListItem = new Element('li',
							{
								'id': liID,
								'class': 'step_btn step_'+(j+1)
							});

							bottomPagination = new Element('li',
							{
								'id': liID,
								'class': 'btn_font dyna_next',
								'styles':
								{
									'margin-right': '10px'
								}
							});
							
							var nextNav = bottomPagination.clone();
							var prevNav = bottomPagination.clone();
							
							if(forms.length == 1) {
								if(j == 3) { newListItem.addClass('step_selected'); }
							}else{
								if(j == i) { newListItem.addClass('step_selected'); }
								else { newListItem.removeClass('step_selected'); }
							}
						
							var clearer = new Element('li',{
								'styles':
								{
									'margin-top': 0,
									'padding': 0,
									'width': '100%',
									'float': 'left',
									'list-style': 'none'
								}
							});
								
							$(thisEl).grab(clearer);
						
							$(divTopID).grab(newListItem,'bottom');
						}
						
						if(i != 0){
							prevNav.set('html','<a href="#" onclick="palm.forms.instances.contactSalesForm.functions.paginateTo('+(i-1)+')">Previous</a>');
							$(thisEl).grab(prevNav,'bottom');
						}
						
						if(i == forms.length-1 && forms.length != 1){
							nextNav.set('html','<a href="#" onclick="$(\'contactSalesForm\').submit(); return false;">Finish</a>');
							$(thisEl).grab(nextNav,'bottom');
						}else if(i != forms.length-1){
							nextNav.set('html','<a href="#" onclick="palm.forms.instances.contactSalesForm.functions.paginateTo('+(i+1)+')" class="checkPoint">Next</a>');
							$(thisEl).grab(nextNav,'bottom');
						}
					}
				}
			}
		},
		"qe2PromoForm": {
			btnSend: {},
			error: "",
			error_info: "",
			str: "",
			init: function(){
				this.str = "";
				this.btnSend = $('btnSend');
				
                if (!$('error')) {
                
                    var error_div = new Element('div', {
                        'id'        :   'error',
                        'styles'    : {
                            'display' : 'none'
                        }
                    });
                    
                    var error_div_info = new Element('div', {
                        'id'        :   'error_info'
                    });
                    
                    error_div_info.inject(error_div, 'inside');
                    
                    error_div.inject($('qe2PromoForm'), 'before');
                }
                
                this.error = $('error');
				this.error_info = $('error_info');

				//Replace the standard input submit button with styled button in the DOM and update local reference
				this.btnSend = palm.forms.replaceSubmitBtn(this.btnSend);
				
				//Attach onclick event to the JS submit button
				this.btnSend.addEvent("click",function(){
					palm.forms.instances.qe2PromoForm.str = palm.forms.instances.qe2PromoForm.validate();
					if(palm.forms.instances.qe2PromoForm.str.length>0){
						palm.forms.instances.qe2PromoForm.error.setStyle("display","")
						palm.forms.instances.qe2PromoForm.error_info.set('html',palm.forms.instances.qe2PromoForm.str);
					}
					else{
						this.disabled=true;
						$('qe2PromoForm').submit();
						return false;
					}
					palm.forms.instances.qe2PromoForm.str = "";
				});
			},
			fields: {
				title: "title",
				firstname: "firstname",
				lastname: "lastname",
				email: "email",
				boatname: "boatname",
				boatnumber: "boatnumber",
				totalpeople: "totalpeople",
				mobilephoneNumber: "mobilephoneNumber"
			},
			validate: function(){
				this.elements = $("form_area").getElements("LABEL");
				this.error.setStyle("display","none")
				this.elements.each(function(el){
					el.className = "";		   
				});
				if(palm.forms.selectValueIsNull(this.fields.title)){
					$(this.fields.title).getParent().getParent().getFirst().className = "error_info";
					this.str += "&bull; Please state your Title<br/>";	
				}
				if(palm.forms.txtValueisNull(this.fields.firstname)){
					$(this.fields.firstname).getParent().getFirst().className = "error_info";
					this.str += "&bull; Please provide your First name<br/>";	
				}
				if(palm.forms.txtValueisNull(this.fields.lastname)){
					$(this.fields.lastname).getParent().getFirst().className = "error_info";
					this.str += "&bull; Please provide your Last name<br/>";	
				}
				if(palm.forms.txtValueisNull(this.fields.email) || !palm.forms.verifyAddress(this.fields.email)){
					$(this.fields.email).getParent().getFirst().className = "error_info";
					this.str += "&bull; Please check your Email address<br/>";	
				}
				if(palm.forms.txtValueisNull(this.fields.boatnumber)){
					$(this.fields.boatnumber).getParent().getFirst().className = "error_info";
					this.str += "&bull; Please provide a Boat registration number<br/>";	
				}
				if(palm.forms.txtValueisNull(this.fields.mobilephoneNumber)){
					$(this.fields.mobilephoneNumber).getParent().getFirst().className = "error_info";
					this.str += "&bull; Please enter your Mobile number<br/>";	
				}
				if(palm.forms.txtValueisNull(this.fields.totalpeople)){
					$(this.fields.totalpeople).getParent().getFirst().className = "error_info";
					this.str += "&bull; Please state the Total number of people onboard<br/>";	
				}
				return this.str;
			}
		}
	},
	replaceSubmitBtn: function(btnSend){
		var cssBtnOff = "input_button_off";
		var cssBtnOn = "input_button_on";
		btnSend.addEvent("mouseover",function(e){
			btnSend.removeClass(cssBtnOff);
			btnSend.addClass(cssBtnOn);
		});
		btnSend.addEvent("mouseout",function(e){
			btnSend.removeClass(cssBtnOn);
			btnSend.addClass(cssBtnOff);
			
		});

		// Replace input button with styled <a> tag
		var jsButton = new Element("a",
		{
			href: "#",
			id: "btnSend"
		}).cloneEvents(btnSend,"click");
		jsButton.set("html",(btnSend.get("value"))).replaces(btnSend);
		return jsButton;
	},
	selectValueIsNull: function(divId){
		/*check dropdown list*/
		var isExit = false;
		var svlue=$(divId);
		svlue = svlue.selectedIndex;
		if(svlue == "0")
		{
			isExit = true;
		}
			
		return isExit;
	},
	txtValueisNull: function(txtBox){
		/*check input_txt*/
		var rtValue=false;

		var txtValu=$(txtBox).value;			
		if(txtValu != "")
		{
			rtValue = false;
			}
			else
			{
				rtValue = true;
				}
		return  rtValue ;
	},
	chkBoxUnChecked: function(chkBox){
		if($(chkBox).get('checked')){
			return false;
		}
		else{
			return true;
		}
	},
	verifyAddress: function(obj){ 
		/*email regex*/
		var email = $(obj).value; 
		var pattern = /^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/
		flag = pattern.test(email); 
		if(flag) 
		{ 
			return true; 
		} 
		else 
		{ 
			return false; 
		} 
	},
	chkByAjax: function(type,args){
		var output;

		var myRequest = new Request(
			{	
				url: 'http://'+location.host+'/contact-sales-ajax.php',
				method: 'get',
				async: false,
				data:
				{
					'type': type,
					'args': args
				},
				onSuccess: function(r){
					output = r;
				}
			}
		);
		
		myRequest.send();

		return output;
	},
	isNumber: function(s)
	{	
		var s = $(s).value; 
		var pattern =/^\d+(\\d+)?$/;
		//var pattern = /^[0-9][1-9][0-9]$/;
		flag = pattern.test(s); 
		if(flag) 
		{ 
			return true; 
		} 
		else 
		{ 
			return false; 
		} 
	},
	CS: {
		/* Country select auto-population */
		countryList             : 'country',
		mobileCountryList       : 'mobilephoneCode',
		mobileCountryOptions    : '',
		officeCountryList       : 'officephoneCode',
		homeCountryList       : 'homephoneCode',
		dialClassPrefix         : 'country_',
		dialClass               : '',
		selectedCountry         : '',
		init: function() {
			// This object only initialises when the required elements are present in the DOM
			// Ensure target elements are contained within the DOM
			if (!$(palm.forms.CS.countryList) || !$(palm.forms.CS.mobileCountryList) || !$(palm.forms.CS.officeCountryList) || !$(palm.forms.CS.homeCountryList)) {
				return false;
			}

			// Re-assign variables of ID strings to their matching DOM elements
			this.countryList = $(palm.forms.CS.countryList);
			palm.forms.CS.mobileCountryList = $(palm.forms.CS.mobileCountryList);
			palm.forms.CS.mobileCountryOptions = palm.forms.CS.mobileCountryList.getChildren('option');
			palm.forms.CS.officeCountryList = $(palm.forms.CS.officeCountryList);
			palm.forms.CS.homeCountryList = $(palm.forms.CS.homeCountryList);

			// Capture change or blur to the Country list
			palm.forms.CS.countryList.addEvent('change', palm.forms.CS.getCountry);
			palm.forms.CS.countryList.addEvent('keyup', palm.forms.CS.getCountry);

			// Remove events from Country list if user interacts with dial
			//number dropd-owns
			palm.forms.CS.mobileCountryList.addEvent('change', palm.forms.CS.removeEvents);
			palm.forms.CS.officeCountryList.addEvent('change', palm.forms.CS.removeEvents);
			palm.forms.CS.homeCountryList.addEvent('change', palm.forms.CS.removeEvents);
		},
		getCountry: function() {
			// Grab the selected country value
			palm.forms.CS.selectedCountry = palm.forms.CS.countryList.getChildren('option')[palm.forms.CS.countryList.selectedIndex].value;
			palm.forms.CS.updateDialCode(palm.forms.CS.selectedCountry);
		},
		removeEvents: function() {
			// revmoed the syncing of drop-down field events
			palm.forms.CS.countryList.removeEvent('change', palm.forms.CS.getCountry);
			palm.forms.CS.countryList.removeEvent('keyup', palm.forms.CS.getCountry);
			palm.forms.CS.mobileCountryList.removeEvents('change');
			palm.forms.CS.officeCountryList.removeEvents('change');
			palm.forms.CS.homeCountryList.removeEvents('change');
		},
		updateDialCode: function(country) {
			// Construct new country class name
			palm.forms.CS.dialClass = palm.forms.CS.dialClassPrefix + country;
			// Search for the option that has that ID
			$each(palm.forms.CS.mobileCountryOptions, function(option, index) {
				
				if (option.getProperty('id') == palm.forms.CS.dialClass) {
					palm.forms.CS.mobileCountryList.selectedIndex = index;
					palm.forms.CS.officeCountryList.selectedIndex = index;
					palm.forms.CS.homeCountryList.selectedIndex = index;
				}
			});
		}
	}
};

palm.forms.init();
