/**
 * This file contains the functions for validation and other common form handling.
 *
 * By hodgsonConsulting September 2011 <http://www.hodgsonconsult.com>
 *
 * Contains:
 *	-form-validation.js (which was a combination of FormValidator.js, nbvalidation.js, NewValidation.js)
 *	-formBasics.js
 *	-script to capture cid (campaign id)
 **/

/*
*   Form validation and Show/Hide for state field, from form-validation.js
*/
// Show state option list when user selects USA
jQuery(document).ready(function() {
	jQuery(".stateFld").hide();
	
	jQuery("#country").change(function() { 
			if (jQuery("option:selected").hasClass("showState")) {
				jQuery(".stateFld").show();
				//focus on the state field once it's unhidden (so not skipped in tab order in some browsers)
				jQuery("#state").focus();
			}
			else {
				jQuery(".stateFld").hide();
			};
	});
});
/*
*   Adds trim function to String objects which will remove white space from 
*   the beginning and end of the string
*/
String.prototype.trim = function() {  // {{{
   return this.replace(/^\s+|\s+$/g,"");
}  // }}}

/*
*   FormValidator objects are to be created on form submit.  All validation
*   processing is done by the object's methods, and output is received by 
*   calling is getValidationOutput()
*   introMessage    the intro text for the validation failed message
*/
function FormValidator(introMessage, duplicateValuesMessage) {  // {{{
    var groups = new Array();
    var errorMessage = "";
    
    /*
    *   Handles any errors found by the check methods in this object
    *   outputType  the type of output to be used (Options: "CONTAINER", "ALERT")
    *   containerId the id of the container for output (Only necessary for "CONTAINER")
    *   returns     true if validation is passed successfully
    */
    this.handleErrors = function(outputType, containerId) {  // {{{
        // Ensure groups don't contain duplicate field values
        var groupsWithDuplicates = new Array();
        var duplicateFieldsMessage = "";
        for (i in groups) {
            var containsDuplicates = false;
            for (j in groups[i]) {
                var identicalFields = new Array();
                for (k in groups[i]) {
                    if (groups[i][j] != groups[i][k]) {
                        //alert(groups[i][j] + "!=" + groups[i][k]);
                        if (groups[i][j].field.value == groups[i][k].field.value) {
                            //alert(groups[i][j].value + "==" + groups[i][k].value);
                            containsDuplicates = true;
                        }
                    }
                }
            }
            
            // Add to the groupsWithDuplicates array if applicable
            if (containsDuplicates)
                groupsWithDuplicates.push(groups[i]);
        }
        
        // Assemble error message from groupsWithDuplicates
        for (i in groupsWithDuplicates) {
            var fieldNames = "";
            for (j in groupsWithDuplicates[i]) {
                if (j > 0) {
                    fieldNames += ", ";
                }
                
                fieldNames += groupsWithDuplicates[i][j].fieldTitle;
            }
            
            duplicateFieldsMessage += fieldNames + "<br />";
        }
        
        var output = "";
        if (errorMessage) {
            output += "<strong>" + introMessage + "</strong>" + "<br />" + errorMessage;
        }
        if (duplicateFieldsMessage) {
            if (output) {
                output += "<br />";
            }
            output += "<strong>" + duplicateValuesMessage + "</strong>" + "<br />" + duplicateFieldsMessage;
        }
        
        if (output) {
            if (outputType == "ALERT") {
                output = output.replace(/<br \/>/gi, "\n");
                output = output.replace(/<.+?>/gi, "");
                alert(output);
            } else if (outputType == "CONTAINER") {
                var outputBox = document.getElementById(containerId);
                outputBox.style.display = "block";
                outputBox.innerHTML = output;
                window.scrollTo(outputBox.offsetLeft, outputBox.offsetTop);
            } else {
                alert("Invalid Output Type");
            }
            
            return false;
        } else {
            if (outputType == "CONTAINER") {
                var outputBox = document.getElementById(containerId);
                outputBox.style.display = "none";
                
            }
            
            return true;
        }
    }   // }}}
    
    /*
    *   Adds a field to a group.  In getErrorMessage(), these groups will be 
    *   checked to ensure that none carry the same values.
    *   field   the field to be added
    *   fieldTitle  the title of the field
    *   groupNumber the group number of the field.  Fields with the same group 
    *   number cannot have the same value.  (Optional Field)
    */
    this.addToGroup = function(field, fieldTitle, groupNumber) {  // {{{
        if (groupNumber != null) {
            if (groupNumber >= groups.length) {
                // Create arrays on each row up to the new group number
                for (var i = 0; i <= groupNumber; i++) {
                    if (i >= groups.length) {
                        groups[i] = new Array();
                    }
                }
            }
            
            var formField = new FormField(field, fieldTitle);
            groups[groupNumber].push(formField);
        }
    }  // }}}
    
    /*
    *   Validates a generic field
    *   field   the field to be validated
    *   fieldTitle  the title of the field
    */
    this.checkGeneric = function(field, fieldTitle, groupNumber) {  // {{{
        if (!field.disabled) {
            if (field.value.trim()) {
                // Adds to duplicate checking group if groupNumber != null
                this.addToGroup(field, fieldTitle, groupNumber);
            } else {
                // Append to error message
                errorMessage += fieldTitle + "<br />";
            }
        }
    }  // }}}
    
    /*
    *   Validates name field
    *   field   the field to be validated
    *   fieldTitle  the title of the field
    *   groupNumber the group number of the field.  Fields with the same group 
    *   number cannot have the same value.  (Optional Field)
    */
    this.checkName = function(field, fieldTitle, groupNumber) {  // {{{
        if (!field.disabled) {
            field.value = field.value.trim();
            
            var pattern = /^[^~`!@#$%\^&*()_+=[\]{}|\\<>,?";:/]{2,}$/;
            var isValid = true;
            
            // valid characters
            isValid = (field.value.match(pattern) && isValid) ? true : false;
            // no letter streak
            isValid = (!this.containsLetterStreak(field.value, 3) && isValid) ? true : false;
            // junk text
            isValid = (!this.containsJunkText(field.value) && isValid) ? true : false;
            // consonant streak
            isValid = (!this.containsConsonantStreak(field.value, 6) && isValid) ? true : false;
            
            if (isValid) {
                // Adds to duplicate checking group if groupNumber != null
                this.addToGroup(field, fieldTitle, groupNumber);
            } else {
                // Append to error message
                errorMessage += fieldTitle + "<br />";
            }
        }
    }  // }}}
    
    /*
    *   Validates a title field
    *   field   the field to be validated
    *   fieldTitle  the title of the field
    *   groupNumber the group number of the field.  Fields with the same group 
    *   number cannot have the same value.  (Optional Field)
    */
    this.checkTitle = function(field, fieldTitle, groupNumber) {  // {{{
        if (!field.disabled) {
            field.value = field.value.trim();
            
            var pattern = /^[^~`!@#$%\^&*()_+=[\]{}|\\<>,?";:/]{2,}$/;
            var isValid = true;
            
            // valid characters
            isValid = (field.value.match(pattern) && isValid) ? true : false;
            // no letter streak
            isValid = (!this.containsLetterStreak(field.value, 3) && isValid) ? true : false;
            // junk text
            isValid = (!this.containsJunkText(field.value) && isValid) ? true : false;
            // junk start text
            isValid = (!this.containsJunkStartText(field.value) && isValid) ? true : false;
            // consonant streak
            isValid = (!this.containsConsonantStreak(field.value, 6) && isValid) ? true : false;
            // same first two consonant streak
            isValid = (!this.containsSameConsonantStreakAtStart(field.value, 2) && isValid) ? true : false;
            // number streak
            isValid = (!this.containsNumberStreak(field.value, 3) && isValid) ? true : false;
            
            if (isValid) {
                // Adds to duplicate checking group if groupNumber != null
                this.addToGroup(field, fieldTitle, groupNumber);
            } else {
                // Append to error message
                errorMessage += fieldTitle + "<br />";
            }
        }
    }  // }}}
    
    /*
    *   Validates a company field
    *   field   the field to be validated
    *   fieldTitle  the title of the field
    *   groupNumber the group number of the field.  Fields with the same group 
    *   number cannot have the same value.  (Optional Field)
    */
    this.checkCompany = function(field, fieldTitle, groupNumber) {  // {{{
        if (!field.disabled) {
            field.value = field.value.trim();
            
            var isValid = true;
            
            // at least two characters
            isValid = ((field.value.trim().length > 1) && isValid) ? true : false;
            // junk text
            isValid = (!this.containsJunkText(field.value) && isValid) ? true : false;
            // don't allow all punctuation
            isValid = (!this.containsOnlyPunctuation(field.value) && isValid) ? true : false;
            
            if (isValid) {
                // Adds to duplicate checking group if groupNumber != null
                this.addToGroup(field, fieldTitle, groupNumber);
            } else {
                // Append to error message
                errorMessage += fieldTitle + "<br />";
            }
        }
    }  // }}}
    
    /*
    *   Validates an email field
    *   field   the field to be validated
    *   fieldTitle  the title of the field
    */
    this.checkEmail = function(field, fieldTitle) {  // {{{
        if (!field.disabled) {
            field.value = field.value.trim();
            
            var typicalEmail = /^[a-zA-Z0-9\-%+_.]{1,}@[a-zA-Z0-9.\-]{2,}\.[^.]{2,}$/;
            if (!field.value.match(typicalEmail)) {
                // Append to error message
                errorMessage += fieldTitle + "<br />";
            }
        }
    }  // }}}
    
    /*
    *   Validates a phone field
    *   field   the field to be validated
    *   fieldTitle  the title of the field
    */
    this.checkPhone = function(field, fieldTitle) {  // {{{
        if (!field.disabled) {
            field.value = field.value.trim();
            
            var isValid = true;
            
            // basic formatting
            var typicalPhone = /^[0-9\.\-/\+()\s]{7,20}$/;
            isValid = ((field.value.match(typicalPhone)) && isValid) ? true : false;
            // minimum digit requirement (6)
            var specialCharacters = /[.\-+()\s]/g;
            var numbersOnly = field.value.replace(specialCharacters, "");
            isValid = ((numbersOnly.length > 5) && isValid) ? true : false;
            // typical fake strings
            var fakePattern = /123456|123123/;
            isValid = (!numbersOnly.match(fakePattern) && isValid) ? true : false;
            // no character streak
            isValid = (!this.containsLetterStreak(numbersOnly, numbersOnly.length) && isValid) ? true : false;
            
            if (!isValid) {
                // Append to error message
                errorMessage += fieldTitle + "<br />";
            }
        }
    }  // }}}
    
	/*
    *   Validates a radio button set
    *   group   the button group to be validated
    *   fieldTitle  the title of the field
    */
    this.checkRadio = function(group, fieldTitle) {  // {{{
		if (!group.disabled) {
			var isValid = false;
            
			for (var i=0; i<group.length; i++) {
				if (group[i].checked)
					isValid = true;
			}
			
			if (!isValid) {
                // Append to error message
                errorMessage += fieldTitle + "<br />";
            }
        }
    }  // }}}
			/*
			*   Validates a check box set
			*   group   the group of boxen to be validated
			*   minimum   the minimum number of boxes to be valid
			*   fieldTitle  the title of the field
			*/
			this.checkCheckBox = function(group, fieldTitle, minimum, maximum) {  // {{{
				
				if (!group.disabled) {
					if (group.length != null) {
						var count = 0;
						
						for (var i=0; i<group.length; i++) {
							if (group[i].checked)
								count++;
						}
						
						if (maximum == null) {
							if (count < minimum) {
								// Append to error message
								errorMessage += fieldTitle + " (Select at least " + minimum + " option(s))<br />";
							}
						} else {
							if ((count < minimum) || (count > maximum)) {
								// Append to error message
								errorMessage += fieldTitle + " (Select " + minimum + 
										"-" + maximum + " options)<br />";
							}
						}
					} else {
						if (!group.checked) {
							// Append to error message
							errorMessage += fieldTitle + "<br />";
						}
					}
				}
			}  // }}}
			
    /*
    *   Internal: 
    *   Checks to see if the provided value contain a streak of numbers
    *   value   the string to be searched
    *   count   the number of numbers in the streak required to return true
    *   returns true if the value contains at least X number where X = count
    */
    this.containsNumberStreak = function(value, count) {  // {{{
        // Set default count
        if (count == null)
            count = 3;
        
        var pattern = new RegExp("[0-9]{" + count + ",}", "");;
        var results = value.match(pattern);
        if (value.match(pattern)) {
            return true;
        } else {
            return false;
        }
    }  // }}}
	
    /*
    *   Internal:
    *   Checks for typical combinations of random letters entered to fool validation
    *   value   the string to be checked
    *   returns true if it finds junk text
    */
    this.containsJunkText = function(value) {  // {{{
        var pattern = /asdf|asdg|sdf|xxx|abc|Rreifsoscick|xyz|zzz/i;
        if (value.match(pattern)) {
            return true;
        } else {
            return false;
        }
    }  // }}}
    
    /*
    *   Internal:
    *   Checks for typical combinations of random letters entered at the beginning of the field
    *   value   the string to be checked
    *   returns true if it finds junk text
    */
    this.containsJunkStartText = function(value) {  // {{{
        var pattern = /jkl|jkj|kkk|lkj/i;
        value = value.substring(0, 2);
        
        if (value.match(pattern)) {
            return true;
        } else {
            return false;
        }
    }  // }}}
    
    /*
    *   Internal:
    *   Checks if string contains only punctuation
    *   value   the string to be checked
    *   returns true if it finds junk text
    */
    this.containsOnlyPunctuation = function(value) {  // {{{
        var pattern = /^[~`!@#$%\^&*()_\-+=[\]{}|\\<>,.?'";:/]+$/i;
        if (value.match(pattern)) {
            return true;
        } else {
            return false;
        }
    }  // }}}
    
    /*
    *   Internal:
    *   Checks for overlong streaks of letters in the string
    *   value   the value to be checked
    *   count   the length of streak that will cause method to return true
    *   returns true if a streak exists of at least *count* characters
    */
    this.containsLetterStreak = function(value, count) {  // {{{
        // set default value for count
        if (count == null)
            count = 3;
        
        var streak = 1;
        var previousCharacter = "";
        for (var i = 0; i < value.length; i++) {
            if (value.charAt(i) == previousCharacter) {
                streak++;
                if (streak >= count)
                    return true;
            } else {
                streak = 1;
            }
            previousCharacter = value.charAt(i);
        }
        
        return false;
    }  // }}}
    
    /*
    *   Internal:
    *   Checks for overlong streaks of consonants in the string
    *   value   the string to be checked
    *   count   the length of the streak that will cause method to return true
    *   returns true if a consonant streak of at least *count* exists
    */
    this.containsConsonantStreak = function(value, count) {  // {{{
        // remove combinations from test that are often part of names that fail
        var exceptionPattern = /ndths|ghths|ghts|sch|spr/i;
        value = value.replace(exceptionPattern, "");
        
        // set default value for count
        if (count == null)
            count = 6;
        
        var pattern = /[BCDFGHJKLMNPQRSTVWXZ]/i;
        var streak = 0;
        for (var i = 0; i < value.length; i++) {
            if (value.charAt(i).match(pattern)) {
                streak++;
                if (streak >= count)
                    return true;
            } else {
                streak = 0;
            }
        }
        
        return false;
    }  // }}}
    
    /*
    *   Internal:
    *   Checks for streaks of the same consonant at beginning of the string
    *   value   the string to be checked
    *   count   the length of the streak that will cause method to return true
    *   returns true if a consonant streak of at least *count* exists
    */
    this.containsSameConsonantStreakAtStart = function(value, count) {  // {{{
        // set default value for count
        if (count == null)
            count = 2;
        
        // crop down to applicable characters
        value = value.substring(0, 1);
        
        var pattern = /[BCDFGHJKLMNPQRSTVWXZ]/i;
        var currentCount = 0;
        for (i in value) {
            for (j in value) {
                if ((i != j) && (value[i] == value[j])) {
                    currentCount++;
                    
                    if (currentCount >= count) {
                        return true;
                    }
                }
            }
        }
        
        return false;
    }  // }}}
}  // }}}

/*
*   Provides objects containing data significant to a form field
*   field   the form field itself
*   fieldTitle  the title of the form field as it will be displayed in the validation
*/
function FormField(field, fieldTitle) {  // {{{
    this.field = field;
    this.fieldTitle = fieldTitle;
}  // }}}

function validateForm(registration_form) {
    var validator = new FormValidator("The following fields contain invalid values:", "Fields with duplicate values:");
    
    // validate fields
    validator.checkName(registration_form.first_name, "First Name", 0);
    validator.checkName(registration_form.last_name, "Last Name", 0);
    validator.checkTitle(registration_form.job_title, "Job Title", 0);
    validator.checkCompany(registration_form.company_name, "Company", 0);
    validator.checkGeneric(registration_form.country, "Country");
    if ((registration_form.country.value == "United States") && (registration_form.state.selectedIndex == "0") || (registration_form.country.value == "USA") && (registration_form.state.selectedIndex == "0") || (registration_form.country.value == "Canada") && (registration_form.state.selectedIndex == "0")){ 
		validator.checkGeneric(registration_form.state, "State");
	}
	validator.checkGeneric(registration_form.industry, "Industry");
    validator.checkPhone(registration_form.phone, "Phone Number");
    validator.checkEmail(registration_form.email, "Email");
	//validator.checkGeneric(registration_form.city_town, "City/Town");
    
    // output results
    return validator.handleErrors("CONTAINER", "validation_output");
}

//NEW BASIC VALIDATION FOR WHETHER FORM INPUT LOOKS LIKE REAL EMAIL OR PHONE NUMBER
//Email validation: there must be a @ sign followed by any combination of letters, numbers, and - (dash) or _ (underscore), followed by one . (dot) and then followed by at least 2 more characters (including other dots or whatever)
//Phone validation: there can only exist the following characters: digits 0-9, ".", "-", "+", "(", ")", and "(space)" characters, and the total length must be between 8 to 20 characters long.
function isEmail(str) {
	var typicalEmail = /@[a-zA-Z0-9\-_]{1,}\..{2,}$/;
	if (!str.match(typicalEmail)) {
			return false;
	}
	return true;
}

function isPhone(num) {
	var typicalPhone = /^[0-9|\.\-/\+()\s]{8,20}$/;
	if (!num.match(typicalPhone)) {
			return false;
	}
	return true;
}
// -->

/*
*    Theatre selection by country, from formBasics.js
*/
//COUNTRY / STATE SELECTION CODE - (previously AJAX)
	<!--
	if (window.addEventListener) // W3C standard
	{
	  window.addEventListener('load', submit, false); // NB **not** 'onload'
	   window.addEventListener('load', initialize, false); // NB **not** 'onload'
	} 
	else if (window.attachEvent) // Microsoft
	{
	  window.attachEvent('onload', submit);
	  window.attachEvent('onload', initialize);
	}
	/*
	function showStates(str)  // JavaScript adaptation of code to pull appropriate state list from TANDBERG database (in this version, activates one set or the other)
	{
		if(str == "USA") {
			document.getElementById("usa_state").selectedIndex = 0;
			stateChanged("");
			document.getElementById("au_state_container").style.display = "none";
			document.getElementById("au_state").disabled = true;
			document.getElementById("usa_state").selectedIndex = 0;document.getElementById("state_container").style.display = "inline";
			document.getElementById("usa_state").disabled = false;
		} else if (str == "Australia") {
			document.getElementById("au_state").selectedIndex = 0;
			stateChanged("");
			document.getElementById("state_container").style.display = "none";
			document.getElementById("usa_state").disabled = true;
			document.getElementById("au_state_container").style.display = "inline";
			document.getElementById("au_state").disabled = false;
		} else {
			document.getElementById("usa_state").selectedIndex = 0;
			document.getElementById("au_state").selectedIndex = 0;
			document.getElementById("au_state").disabled = true;
			document.getElementById("au_state_container").style.display = "none";
			document.getElementById("state_container").style.display = "inline";
			document.getElementById("usa_state").disabled = true;
			stateChanged("");
		}
	}
	
	function stateChanged(newstate) {  // sets hidden state field to value of whichever country-specific state field is currently active
		document.getElementById("state").value = newstate;
	}
	*/
	// Changes theatre code based on selected country
	var i, j, selector;
	var theatres = new Array();
	var countries = new Array();
	var countryName;
	var theatre;
	
	theatres = ["Americas", "APAC", "EMEA"];
	countries[0] = ["Canada","USA"];
	countries[1] = ["Australia","Bangladesh","Bhutan","Brunei","Cambodia","China","East Timor","Fiji","Hong Kong, China","India","Indonesia","Japan","Kiribati","Laos","Malaysia","Maldives","Marshall Islands","Micronesia","Mongolia","Nauru","Nepal","New Zealand","Palau","Papua New Guinea","Philippines","Samoa","Singapore","Solomon Islands","South Korea","Sri Lanka","Taiwan","Thailand","Tonga","Tuvalu","Vanuatu","Vietnam"];
	countries[2] = ["Afghanistan","Albania","Algeria","Andorra","Angola","Antigua and Barbuda","Argentina","Armenia","Austria","Azerbaijan","Bahamas","Bahrain","Barbados","Belarus","Belgium","Belize","Benin","Bolivia","Bosnia and Herzegovina","Botswana","Brazil","Bulgaria","Burkina Faso","Burundi","Cameroon","Cape Verde","Central African Republic","Chad","Chile","Colombia","Comoros","Congo","Congo (Brazzaville)","Costa Rica","Croatia","Cyprus","Czech Republic","Denmark","Djibouti","Dominica","Dominican Republic","Ecuador","Egypt","El Salvador","Equatorial Guinea","Eritrea","Estonia","Ethiopia","Finland","France","Gabon","Gambia","Georgia","Germany","Ghana","Greece","Grenada","Guatemala","Guinea","Guinea-Bissau","Guyana","Haiti","Honduras","Hungary","Iceland","Iraq","Ireland","Israel","Italy","Jamaica","Jordan","Kazakhstan","Kenya","Kuwait","Kyrgyzstan","Latvia","Lebanon","Lesotho","Liberia","Libya","Liechtenstein","Lithuania","Luxembourg","Macedonia","Madagascar","Malawi","Mali","Malta","Mauritania","Mauritius","Mexico","Moldova","Monaco","Morocco","Mozambique","Namibia","Netherlands","Nicaragua","Niger","Nigeria","Norway","Oman","Pakistan","Panama","Paraguay","Peru","Poland","Portugal","Qatar","Romania","Russia","Rwanda","Saint Kitts and Nevis","Saint Lucia","Saint Vincent and The Grenadines","San Marino","Sao Tome and Principe","Saudi Arabia","Senegal","Serbia and Montenegro","Seychelles","Sierra Leone","Slovakia","Slovenia","Somalia","South Africa","Spain","Suriname","Swaziland","Sweden","Switzerland","Tajikistan","Tanzania","Togo","Trinidad and Tobago","Tunisia","Turkey","Turkmenistan","Uganda","Ukraine","United Arab Emirates","United Kingdom","Uruguay","Uzbekistan","Vatican City","Venezuela","Western Sahara","Yemen","Zambia","Zimbabwe"];
	
	function changeTheatre() {
		selector = document.getElementById("country");
		theatre = document.getElementById("theatre");
		for (i = 0; i < selector.length; i++) {
			if (selector.options[i].selected) {
				countryName = selector.options[i].value;
			}
		}
		
		if (countryName == "_Other") {
			theatre.value = "no theatre";
		} else {
			for(i = 0; i < 3; i++) {
				for(j = 0; j < countries[i].length; j++) {
					if(countries[i][j] == countryName) {
						theatre.value = theatres[i];
					}
				}
			}
		}
	}
	// -->
	
	function initialize() {  // set URL source, returnPage, and cid values with JavaScript instead of PHP; also resets country field so refreshes don't break state selector
		if (document.getElementById("url_source") != null)
            var urlPath = window.location.toString().split("/");
            if (urlPath[urlPath.length - 1] == "FormPopUp.html")
                document.getElementById("url_source").value = window.parent.location;
            else 
                document.getElementById("url_source").value = window.location;
		if(document.getElementById("returnPage") != null && document.getElementById("returnPage").value == "" ) {
			//document.getElementById("returnPage").value = window.location + "?submitted=true";  // alternate version using this page as its own thank-you page
			/* If the URL contains an anchor link (#), add the submitted=true before it on the return page (required to function properly) */
			var location = window.location.toString();
			var anchorcheck = location.split('#');
			var anchorcheck = location.split('?');
			// urlparta = URL up to # or ?
			var urlparta = anchorcheck[0];
			var urlpartb = "";
			if( location.indexOf("?cid") != -1 ){
				var urlpartb = "&";
			} 
			if( location.indexOf("#") != -1){
				var urlpartb = "#";
			}
			if( anchorcheck.length > 1 ){
			// urlpartb = #anchor	
			urlpartb += anchorcheck[1];
			}
			document.getElementById("returnPage").value = urlparta + "?submitted=true" + urlpartb;
		}
		
		var i,x,y,queries = window.location.search.split("&");
		if( queries.length > 0 ) {
			for( i=0; i<queries.length; i++ ) {
				x=queries[i].substr(0,queries[i].indexOf("="));
				y=queries[i].substr(queries[i].indexOf("=")+1);
				x=x.replace(/\?/g,"");
				if( x == "cid" ) {
					document.getElementById("cid").value = y;
				} else if( x == "submitted" ) {
					document.getElementById("the_form").style.display = "none";
					document.getElementById("thank_you").style.display = "block";
				}
				
			}
		}
		if (document.getElementById("country") != null)
			document.getElementById("country").selectedIndex = 0;
	}
	
	function getQuerystring(key, default_)
	{
	  if (default_==null) 
		  default_=""; 
	  key = key.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
	  var regex = new RegExp("[\\?&]"+key+"=([^&#]*)");
	  var qs = regex.exec(window.location.href);
	  if(qs == null)
		return default_;
	  else
		return qs[1];
	}
	function submit(){
		var isSubmitted = getQuerystring('submitted',null);                 
		if(isSubmitted == 'true')
		{
			document.getelementbyid('the_form').style.display = 'none';
			document.getelementbyid('thank_you').style.display = 'block';
		}
	}
/*
*    Script to capture cid (campaign id) - **NOTE: you must set form name in call to campid on form for this to work properly**
*/
function gup( name ) {
	  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
	  var regexS = "[\\?&]"+name+"=([^&#]*)";
	  var regex = new RegExp( regexS );
	  var results = regex.exec( window.location.href );
	  if( results == null )
		return "";
	  else
		return results[1];
}
	var campid = gup('cid');

