// clear checked checkboxes

function clearAll() {
     var boxes = document.getElementsByTagName('input'); 
     for (i = 0; i < boxes.length; i++) {
          if (boxes[i].type == 'checkbox'){
                boxes[i].checked = false;
           }
     }
}

function addChecked(url){
	var boxes = document.getElementsByTagName('input'); 
        for (i = 0; i < boxes.length; i++) {
          if (boxes[i].type == 'checkbox'){
          	if(boxes[i].checked) {
          		//length = boxes[i].value.length;
          		categoryCode = boxes[i].value;

                	url = url + boxes[i].id + "=" + categoryCode  + "&";
                }
                else {
                	url = url + boxes[i].id + "=" + "&";
                } 

           }
     }
     return url
}

// Sets CSS to display or hide the Thank You module
function showThankYou(name) {

	var showModule = document.getElementById("DPCelebrationThankYouModule");
	var showBody = document.body;
	var hideModule = document.getElementById("DPCelebrationGADGADSignUpModule");
	var thankYouMessage = document.getElementById("thankYouMessage");
		
	if(showModule.style.display == "block"){
		showModule.style.display = "none";
	}
	else{
		//trackLink("landing_reminderconfirm");
		trackPage("reminderconfirm", "landing_thankyou");
		showBody.style.backgroundImage = "url(http://adisneyparks.disney.go.com/media/disneyparks/en_US/media/celebrations/WWYC/gadgad/thank_you_bg.jpg)";
			
		showModule.style.display = "block";
		var nameChange = document.getElementById("nameChange");
		nameChange.innerHTML = name;
		if(name != ""){
			thankYouMessage.innerHTML = thankYouMessage.innerHTML + ",";
		}
		hideModule.style.display = "none";
	}
}

// Display system error message
function showError() {

	var systemError = document.getElementById("systemMessage");
	var form = document.getElementById("DPCelebrationGADGADSignUpLightForm");
	form.style.paddingTop = "0px";
	systemError.style.display = "block";
}

// Validates the form content before submitting to Acxiom

	var lang = document.getElementById("lang");
	WDPRO_LOADER.require("dom");
	WDPRO_LOADER.require("formUtils");
	WDPRO_LOADER.require("connection");
	WDPRO_LOADER.addCallback(
		function() {
		
		//Detect language
		
			lang.value = lang.value.toLowerCase();
			index = lang.value.indexOf("_");
			lang.value = lang.value.slice(0, index);
			WDPRO_CONFIG.locale = lang.value;
			$D = YAHOO.util.Dom;
			$S = WDPRO.util.StringUtils;
	
			var frm = $D.get("sample-search-form");
	
			var highlight = function(el) {
				$D.setStyle(el, 'border-color', '#F00');
			}
	
			var clearHighlight = function(el) {
				$D.setStyle(el, 'border-color', '#000');
			}
	
			var tmpCfg = WDPRO.util.FormValidator.createConfigByClasses(frm, {email:"email",integer:"ints",notEmpty:"required",currency:"currency",date:"date"});
			
			
			tmpCfg.rules.push({inputs: frm.email, rule: function(elementValue) {
							      var isFormatted = false;
							     						      		
								var regExp = new RegExp(/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,80}$/);
								if(regExp.test(elementValue))
									isFormatted = true;
								 return isFormatted;
							}
						}
	       		);
	       		
			tmpCfg.rules.push({inputs: frm.postalCode, rule: function(elementValue) {
				      var isFormatted = false;
				      elementValue = elementValue.split(' ').join('');
				      					     
						var regExp = new RegExp(/^[A-Za-z0-9\s]{5,6}$/);
						if(regExp.test(elementValue))
							isFormatted = true;
						if(elementValue.length == 0) 
							isFormatted = true;
						 return isFormatted;
					}
	       			}
	       		);
			
			tmpCfg.rules.push({inputs: frm.firstName, rule: function(elementValue) {
				      var isFormatted = false;
					     
						//var regExp = new RegExp(/^[A-Za-z0-9'\-\s]{0,32}$/);
						var regExp = new RegExp(/^['\w\-\s\dÀÈÌÒÙàèìòùÁÉÍÓÚÝáéíóúýÂÊÎÔÛâêîôûÃÑÕãñõÄËÏÖÜäëïöüçÇßØøÅåÆæÞþÐð]{0,32}$/);
						if(regExp.test(elementValue))
							isFormatted = true;
						
						 return isFormatted;
					}
	       			}
	      		 );
	      		 
	      		 tmpCfg.rules.push({inputs: frm.lastName, rule: function(elementValue) {
			 			
				      var isFormatted = false;
					      	var regExp = new RegExp(/^['\w\-\s\dÀÈÌÒÙàèìòùÁÉÍÓÚÝáéíóúýÂÊÎÔÛâêîôûÃÑÕãñõÄËÏÖÜäëïöüçÇßØøÅåÆæÞþÐð]{0,32}$/);
						if(regExp.test(elementValue))
							isFormatted = true;
						
						 return isFormatted;
					}
				}
	      		 );
			

				
			YAHOO.util.Event.addListener($D.get("submitButton"), "click", function() {
					var resp = WDPRO.util.FormValidator.validate(tmpCfg);
					var errs = resp.errors;
					for (var i=0; i<errs.length; i++) {
						var errEl = errs[i].getElement();

						var errSpan = YAHOO.util.Dom.getPreviousSiblingBy(errEl, function(el) { return YAHOO.util.Dom.hasClass(el, "validationError");});
						if(errEl.id == "lastName") {
							$D.setStyle("firstNameError", "display", "block");
						}
						if(errEl.id == "postalCode") {
							$D.setStyle("VolunteerProjectInterestLabel", "marginTop", "-239px");
							
							if(navigator.appName == "Microsoft Internet Explorer"){

								$D.setStyle("VolunteerProjectInterestLabel", "marginTop", "-254px");
							}
							
							$D.setStyle("zipCodeMessage", "marginTop", "145px");
						}
						
						$D.setStyle(errSpan, "display", "block");
	
					}
					var scs = resp.successes;
					for (var i=0; i<scs.length; i++) {
						var scsEl = scs[i].getElement();
											
						if(scsEl.id == "postalCode") {
						
							$D.setStyle("VolunteerProjectInterestLabel", "marginTop", "-224px");
							$D.setStyle("zipCodeMessage", "marginTop", "130px");
							if(navigator.appName == "Microsoft Internet Explorer"){
								$D.setStyle("VolunteerProjectInterestLabel", "marginTop", "-240px");
							}
							
						}
						
						var errSpan = YAHOO.util.Dom.getPreviousSiblingBy(scsEl, function(el) { return YAHOO.util.Dom.hasClass(el, "validationError");});
						$D.setStyle(errSpan, "display", "none");
					}
					
					if(errs.length == 0){
						submitForm();
					}
					
				}
			);
		}
);


function submitForm() {
	var AjaxObject = {  

		handleSuccess:function(o){ 
		// This member handles the success response
		// and passes the response object o to AjaxObject's 
		// processResult member. 
			this.processResult(o); 
		}, 

		handleFailure:function(o){ 
			strProxyURL = 'http://disneyparks.disney.go.com/disneyparks/en_US/celebrations/modules/proxyServer';
			strProxyURL = strProxyURL + "?error=Connectivity";
			YAHOO.util.Connect.asyncRequest('GET', strProxyURL, errorCallback, null);
			showError();
		}, 

		processResult:function(o){ 
		
		strProxyURL = 'http://disneyparks.disney.go.com/disneyparks/en_US/celebrations/modules/proxyServer';
			if(o.responseText == 'true') {
				var name = '';
				var firstName = document.getElementById("firstName");
				var lastName = document.getElementById("lastName");

				if(firstName.value != '' || lastName.value!= ''){
					name = firstName.value +"<br />" + lastName.value;
				}
						
				showThankYou(name);
		
			}else if(o.responseText == 'false') {
				strProxyURL = strProxyURL + "?error=AcxiomFalse";
				YAHOO.util.Connect.asyncRequest('GET', strProxyURL, errorCallback , null);
				showError();
			}else {
				strProxyURL = strProxyURL + "?error=AcxiomBlank";
				YAHOO.util.Connect.asyncRequest('GET', strProxyURL, errorCallback , null);	
				showError();
			}
		}, 

		startRequest:function() { 
		
		//the strPostURL is the URL that will receive the GET request
		//strPostURL = 'http://disneyparks.disney.go.com/disneyparks/en_US/WhatWillYouCelebrate/success'; // Change to Acxiom’s URL when available for testing
		//strPostURL = 'https://disneybirthday.delivery.net:8443/disney-day/litesignup.do'; // Acxiom testing URL
		
		/*************************************************************************************************
		* PLEASE BE AWARE THAT THERE ARE A NUMBER OF URLs 
		* LOCAL, DEV AND QA SHOULD HAVE THE strPostURL SET TO THE Acxiom UAT URL
		* PROD MUST HAVE THE strPostURL SET TO THE Acxiom Production site URL
		***************************************************************************************************/
		strPostURL = 'https://disneyparks.delivery.net:8443/disney-day/litesignup.do'; // Acxiom UAT URL
		//strPostURL = 'https://disneyparks.delivery.net/disney-day/litesignup.do' // Production site URL
		
		/**************************************************************************************************
		* strProxyURL SHOULD NOT BE MODIFIED!!!! 
		**************************************************************************************************/
		strProxyURL = 'http://disneyparks.disney.go.com/disneyparks/en_US/celebrations/modules/proxyServer';
		
		strPostData = "";
		
		// go through inputs on form and aggregate into strPostData (i.e. firstName=Angela&lastName=Jay&...)
		var firstName = document.lightGADGADSignUpForm.firstName;
		var lastName = document.lightGADGADSignUpForm.lastName;
		var email = document.lightGADGADSignUpForm.email;
		var postalCode = document.lightGADGADSignUpForm.postalCode;
		
		// Remove white spaces from Canadian zip code
		postalCode.value = postalCode.value.split(' ').join('');
		var category1 = document.lightGADGADSignUpForm.category1;
		var category2 = document.lightGADGADSignUpForm.category2;
		var category3 = document.lightGADGADSignUpForm.category3;
		var category4 = document.lightGADGADSignUpForm.category4;
		var category5 = document.lightGADGADSignUpForm.category5;
		var category6 = document.lightGADGADSignUpForm.category6;
		var category7 = document.lightGADGADSignUpForm.category7;
		var category8 = document.lightGADGADSignUpForm.category8;
						
		strPostData = firstName.id + "=" + firstName.value + "&"
		+ lastName.id + "=" + lastName.value + "&"
		+ email.id + "=" + email.value + "&"; 
		strPostData  = addChecked(strPostData);
		
		strPostData  = strPostData + postalCode.id + "=" + postalCode.value + "&";
		strPostData  = strPostData + "lang=" + lang.value + "&";
		strPostData  = strPostData + "strPostURL=" + strPostURL;
		
		strProxyURL = strProxyURL + "?" + strPostData;
		
		YAHOO.util.Connect.asyncRequest('GET', strProxyURL, callback, null); 
		} 
		
	}; 
	
	var ErrorAjaxObject = {  

		handleSuccess:function(o){ 
		// This member handles the success response
		// and passes the response object o to AjaxObject's 
		// processResult member. 
		}, 

		handleFailure:function(o){ 
			// Created to handle error 
			//logging for SE - call back 
			//to do nothing
		}
	}
		
	var callback = 
	{ 
	    success:AjaxObject.handleSuccess, 
	    failure:AjaxObject.handleFailure, 
	    scope: AjaxObject 
	}; 

	// Start the transaction. 
	AjaxObject.startRequest(); 



	var errorCallback  = 
	{ 
	    success: ErrorAjaxObject.handleSuccess, 
	    failure: ErrorAjaxObject.handleFailure, 
	    scope: ErrorAjaxObject  
	}; 
}
