// Replacing the createRandomBox function
// if jQuery is included
if(typeof(jQuery) === 'function') {
	$(document).ready( function() {
		
		setRegAction();
		
		shuffleFindEHValues();
		
		insertLandingPageTrackingValue();
		
	}); // End (on ready)
} // End if ( jQuery exists )


function shuffleFindEHValues() {
	// If there is a reg form with <select name="findEH"></select>
	if( $("select[name=findEH]").length ) {
		
		// Select all the findEH options (except "Please select...")
		var options = $("select[name=findEH] option").not(":eq(0)");
		
		var tempHTML;
		var tempValue;
		var randomNumber;
		
		options.each(function(){
			
			// Choose a random option
			randomNumber = Math.floor( Math.random() * 16 ) % options.length;
			
			// Then swap HTML and values with that random option...
			// it's not the best shuffle algorithm, but it's certainly random.
			tempHTML = $(this).html();
			tempValue = $(this).val();
			$(this).html( options.eq(randomNumber).html() );
			$(this).val( options.eq(randomNumber).val() );
			options.eq(randomNumber).html( tempHTML );
			options.eq(randomNumber).val( tempValue );

		}); // End foreach ( options in findEH select )
	} // End if ( findEH select exists )
} // End function


function insertLandingPageTrackingValue() {		
	
	// If there's a reg form on this page
	if( $("form[name=registrationForm]").length ) {
		
		var landingPageTrackingValue = '';
		
		// Checking for s.prop31
		if( typeof(s) != 'undefined' ) {
			if( typeof(s.prop31) != 'undefined' ) {
				
				landingPageTrackingValue = s.prop31;
				
			} // End if
		} // End if
		
		// Using parent-page if s.prop31 == ''
		if( landingPageTrackingValue == '' ) {
			if( typeof(sbms) != 'undefined' ) {
				if( typeof(sbms.parent) != 'undefined' ) {
					if( typeof(sbms.page) != 'undefined' ) {
						
						landingPageTrackingValue = sbms.parent + '-' + sbms.page;
						
					} // End if
				} // End if
			} // End if
		} // End if
		
		// If there is a landingPage hidden input field
		if( $("input[name=landingPage]").length ) {
			$("input[name=landingPage]").val( landingPageTrackingValue );
			
		// Else, append it to the reg form
		} else {
			$("form[name=registrationForm]").append('<input type="hidden" name="landingPage" value="'+landingPageTrackingValue+'" />');
		} // End if
		
	} // End if
} // End function


function validateReg(theForm) {
  var reason = "";
  
  reason += validateEmpty(theForm.firstName,"Please enter your first name.");
  reason += validateEmpty(theForm.gender,"Please select your gender.");
  reason += validateEmpty(theForm.postalCode,"Please enter your postal code");
  reason += validateEmail(theForm.emailAddress,theForm.confirmEmail);
  reason += validateEmpty(theForm.password,"Please enter a password.");
  reason += validateEmpty(theForm.findEH,"Please select how you found out about eHarmony.");
      
  if (reason != "") {
    alert("Some fields need correction:\n\n" + reason);
    return false;
  }

  return true;
}


function validateEmpty(fld, fldError) {
    var error = "";
  
    if (fld.value.length == 0) {
        fld.style.background = 'Yellow'; 
        error = fldError+"\n"
    } else {
        fld.style.background = 'White';
    }
    return error;   
}


function trim(s) {
  return s.replace(/^\s+|\s+$/, '');
} 


function validateEmail(fld, fldConfirm) {
    var error="";
    var tfld = trim(fld.value); 
	var tfldConfirm = trim(fldConfirm.value); 
    var emailFilter = /^[^@]+@[^@.]+\.[^@]*\w\w$/ ;
    var illegalChars= /[\(\)\<\>\,\;\:\\\"\[\]]/ ;
    
    if (fld.value == "") {
        fld.style.background = 'Yellow';
        error = "Please enter an email address.\n";
    } else if (!emailFilter.test(tfld)) {              //test email for illegal characters
        fld.style.background = 'Yellow';
        error = "Please enter a valid email address.\n";
    } else if (fld.value.match(illegalChars)) {
        fld.style.background = 'Yellow';
        error = "The email address contains illegal characters.\n";
    } else {
        fld.style.background = 'White';
		if (tfld != tfldConfirm) {
			 error = "The confirm email address does not match.\n";
			 fld.style.background = 'Yellow';
			 fldConfirm.style.background = 'Yellow';
		}
    }
    return error;
}


function insertAffiliateTracking() {
   dList = location.search.substring(1);  dAr = dList.split("&");  rAr = new Array();  tval = 0;  
   for (var i=0;i<dAr.length;i++) { rAr = dAr[i].split("=");  
      if (rAr.length == 2) { 
      	
      	rAr[0] = rAr[0].replace( new RegExp('[^a-zA-Z0-9-_]+', 'g'), '' );
      	rAr[1] = rAr[1].replace( new RegExp('[^a-zA-Z0-9-_]+', 'g'), '' );
      	
      	rAr[0] = rAr[0].substr( 0, 70 );
      	rAr[1] = rAr[1].substr( 0, 70 );
      	
      	document.writeln('<input type="hidden" name="'+rAr[0]+'" value="'+rAr[1]+'" />');
      } 
   }
}


function setRegAction() {

	// If there's a reg form on this page
	if( $("form[name=registrationForm]").length ) {
		
		if (document.domain == "dating.comcast.net") {
			document.registrationForm.action = "https://www.eharmony.com/singles/servlet/homeRegS";
		} else {
			document.registrationForm.action = "https://"+document.domain+"/singles/servlet/homeRegS";
		} // End if
		
	} // End if
	
} // End function


function setRegActionToLocale(selObj) {
	var submitDomain = window.location.host;
	switch(selObj.options[selObj.selectedIndex].value){
		case "1":
			submitDomain = "www.eharmony.com";
			break;
		case "14":
			submitDomain = "www.eharmony.com.au";
			break;
		case "39":
			submitDomain = "www.eharmony.ca";
			break;
		case "215":
			submitDomain = "www.eharmony.co.uk";
			document.location = "http://www.eharmony.co.uk/register";
			break;
	}
	document.registrationForm.action = "https://"+submitDomain+"/singles/servlet/homeRegS"
}


function createRandomBox(selectBox) {
	var options = new Array();
	options[0] = new Option("Word of Mouth", 30);
	options[1] = new Option("Newspaper/Magazine", 28);
	options[2] = new Option("Radio", 25);
	options[3] = new Option("Television", 26);
	options[4] = new Option("Online (Search, Banner, Email", 27);
	options[5] = new Option("Direct Mail", 29);
	options[6] = new Option("Press (News Interview or Article)", 31);
	options.sort(function(a,b){return Math.round(Math.random())*-1})

	selectBox.options[0] = new Option("Please select...","", true);
	for (i=0; i<options.length; i++) {
	  selectBox.options[i+1] = options[i];
	}
}


function getParameter ( queryString, parameterName ) {
	// Add "=" to the parameter name (i.e. parameterName=value)
	var parameterName = parameterName + "=";
	
	if ( queryString.length > 0 ) {
		// Find the beginning of the string
		begin = queryString.indexOf ( parameterName );
		// If the parameter name is not found, skip it, otherwise return the value
		if ( begin != -1 ) {
			// Add the length (integer) to the beginning
			begin += parameterName.length;
			// Multiple parameters are separated by the "&" sign
			end = queryString.indexOf ( "&" , begin );
			if ( end == -1 ) {
				end = queryString.length
			} // End if
			
			// Return the string
			return unescape ( queryString.substring ( begin, end ) );
		} // End if
	} // End if
	return "";
} // End function
