
var defaultValueNames = new Array();
var defaultValueValues = new Array();

function superform_loadSuperformDefaults(){
	var superform = document.getElementById("superform");
	var inputs = superform.getElementsByTagName("input");
	for (var i = 0; i < inputs.length; i++){
		if (inputs[i].type == 'text' || inputs[i].type == 'password'){
			defaultValueNames.push(inputs[i].name);
			defaultValueValues.push(inputs[i].value);
		}
	}
	var textareas = superform.getElementsByTagName("textarea");
	for (var i = 0; i < textareas.length; i++){
		defaultValueNames.push(textareas[i].name);
		defaultValueValues.push(textareas[i].value);
	}
}

function superform_onFieldFocus(field){
	// If the value in this field is the default value, then set it to empty
	var name = field.name;
	var defaultValueIndex = -1;
	for (var i = 0; i < defaultValueNames.length; i++){
		 if (defaultValueNames[i] == name){
			defaultValueIndex = i;
		 }
	}
	if (defaultValueIndex > -1){
		if (field.value == defaultValueValues[defaultValueIndex])
			field.value = '';
	}
}

function superform_isBlank(identifier, type){
	if (type == 'text' || type == 'textarea' || type == 'password'){
		var text = document.getElementsByName(identifier)[0].value;
		return superform_isEmpty(text);
	} else if (type == 'checkbox') {
		var checkboxes = document.getElementsByName(identifier);
		for (var i=0; i < checkboxes.length; i++){
			if (checkboxes[i].checked) return false;
		}
		return true;
	} else if (type == 'radio') {
		var buttons = document.getElementsByName(identifier);
		for (var i=0; i < buttons.length; i++){
			if (buttons[i].checked) return false;
		}
		return true;
	} else if (type == 'select-multiple') {
		var options = document.getElementsByName(identifier);
		for (var i=0; i < options.length; i++){
			if (options[i].selected) return false;
		}
		return true;
	}
	return false;
}

// Check to see if input is null or empty
 function superform_isBlankVal(val) {
     if(val == null) return true;
     if(val.length == 0) return true;
     return false;
 }

// Check to see if input is whitespace only
 function superform_isEmpty(val) {
     if (!superform_isBlankVal(val)) {
     	var reWhiteSpace = new RegExp(/^\s+$/);
     	return reWhiteSpace.test(val);
     }
     return true;
 }

// Removes newline characters from the string then
// removes leading and trailing spaces
function superform_cleanString(stringToClean) {
	return (stringToClean.replace(/\n/g,"")).replace(/^\s+|\s+$/g,"");
}

// Check to see if this is a valid date
// Checks for yyyymmdd, mmddyyyy and ddmmyyyy
function superform_isValidDate(val) {
	if (!superform_isEmpty()) {
		var yyyymmdd = "/^(19|20)\d\d[- /.](0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])$/";
		if (!val.match(yyyymmdd)) {
			var mmddyyyy = "/^(0|1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])[- /.](19|20)\d\d$/";
			if (!val.match(mmddyyyy)) {
				var ddmmyyyy = "/^(0[1-9]|[12][0-9]|3[01])[- /.](0[1-9]|1[012])[- /.](19|20)\d\d$/";
				return val.match(ddmmyyyy);
			}
			return true; // Format is mmddyyyy
		}
		return true; // Format is yyyymmdd
	}
	return false; // Date is empty
}


// Start code for intl phone validation

// Declaring required variables
var digits = "0123456789";
// non-digit characters which are allowed in phone numbers
var phoneNumberDelimiters = "()- ";
// characters which are allowed in international phone numbers
// (a leading + is OK)
var validWorldPhoneChars = phoneNumberDelimiters + "+";
// Minimum no of digits in an international phone no.
var minDigitsInIPhoneNumber = 10;

function superform_isInteger(s)
{   var i;
    for (i = 0; i < s.length; i++)
    {   
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}
function superform_trim(s)
{   var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not a whitespace, append to returnString.
    for (i = 0; i < s.length; i++)
    {   
        // Check that current character isn't whitespace.
        var c = s.charAt(i);
        if (c != " ") returnString += c;
    }
    return returnString;
}
function superform_stripCharsInBag(s, bag)
{   var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++)
    {   
        // Check that current character isn't whitespace.
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function superform_isValidOUSPhone(strPhone){
   var bracket=3
   strPhone=superform_trim(strPhone)
   if(strPhone.indexOf("+")>1) return false
   if(strPhone.indexOf("-")!=-1)bracket=bracket+1
   if(strPhone.indexOf("(")!=-1 && strPhone.indexOf("(")>bracket)return false
   var brchr=strPhone.indexOf("(")
   if(strPhone.indexOf("(")!=-1 && strPhone.charAt(brchr+2)!=")")return false
   if(strPhone.indexOf("(")==-1 && strPhone.indexOf(")")!=-1)return false
   s=superform_stripCharsInBag(strPhone,validWorldPhoneChars);
   return (superform_isInteger(s) && s.length >= minDigitsInIPhoneNumber);
}

// End code for intl phone validation

//Phone format
//phone:
//339-4248
//339-42-48
//339 42 48
//339 4248
//3394248
//(095) #phone#
//(095)#phone#
//+7 (095) #phone#
//+7 (095)#phone#
//+7(095) #phone#
//+7(095)#phone#
function superform_isValidUSPhone(str) 
{
	var phone2 = /^(\+\d)*\s*(\(\d{3}\)\s*)*\d{3}(-{0,1}|\s{0,1})\d{2}(-{0,1}|\s{0,1})\d{2}$/; 
	if (str.match(phone2)) {
   		return true;
 	} else {
 		return false;
 	}
}


// Validate the zip code
function superform_isValidZipCode(val) {
	var re = /^\d{5}([\-]\d{4})?$/;
	if (val.match(re)) {
		return true;
	} else {
		return false;
	}
}

// Check to see if input is a valid email address
function superform_isEmailAddress(val) {
	var reRegex = /^([a-zA-Z0-9])+([.a-zA-Z0-9_-])*@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-]+)+/;
	
	var delimiter = null;
	if (val.indexOf(";") > -1) delimiter = ";";
	if (val.indexOf(",") > -1) delimiter = ",";
	
	// If we don't have a delimiter we might have 2 or more
	// email addresses run into each other
	if (delimiter == null) {
		if (val.split("@").length > 2) {
			return false;
		}
	}
	
	// If we have a delimter then
	// we have multiple email addresses
	if (delimiter != null){
		var flag = true;
		var addrarray = val.split(delimiter);
		for (var i = 0; i < addrarray.length; i++){
			if (!superform_isEmailAddress(addrarray[i]))
				flag = false;
		}
		return flag;
	}
	
    return reRegex.test(val);
}

// Add an error to error list
function superform_raiseError(msg) {
    this.errorList[this.errorList.length] = msg;
}

// The numErrors() method returns the size of the "errorList" array
// if the size of the array is greater than 1, it implies that one
// or more errors have occurred while validating the form data.

// return number of errors in error array
function superform_numErrors() {
    return this.errorList.length;
}

// Display all errors
// Iterate through error array and print each item
function superform_displayErrors() {
	var errormsg = "";
    for (x = 0; x < this.errorList.length; x++) {
    	errormsg += this.errorList[x];
    }
    alert(errormsg);
}


// Returns the items selected from a multi-select control
function superform_getSelected(opt) {
    var selected = new Array();
    var index = 0;
    for (var intLoop=0; intLoop < opt.length; intLoop++) {
       if (opt[intLoop].selected) {
          index = selected.length;
          selected[index] = new Object;
          selected[index].value = opt[intLoop].value;
          selected[index].index = intLoop;
       }
    }
    return selected;
 }

// we use labels for names
function superform_getLabelForName(name) {
	var inputElem = document.getElementsByName(name)[0];
	if(inputElem.parentNode){
		if(inputElem.parentNode.tagName == 'label'){
			return inputElem.parentNode;
		}
	}
	var labels=document.getElementsByTagName("label"),i;
	for( i=0; i<labels.length;i++ ){
		if(labels[i].htmlFor==inputElem.name){
			return labels[i];
		}
	}
	return false;
}



// This function accepts arrays but is only expecting one entry
// If the array length is not = 1 then return null
function superform_getSingleField(fieldName) {
	var fieldValue = null;
	var elements = document.getElementsByName(fieldName);
	if (elements.length == 1) {
		// if (!superform_isEmpty(elements[0].value)) {  TODO: Fix validation to new function
			fieldValue = elements[0].value;
		// }
	}
	return fieldValue;
}

// Validate the contents of the form and assemble the XML file
function superform_validateForm(myForm) {
	
	var xmlMessage = "";

	// Check to see if we have a form name
	// If we are missing this field then signal an error
	var formname = superform_getSingleField("form_name");
	var missingFormNameMsg = document.getElementById("missing_form_name_msg").innerHTML;
	if (formname == null) {
		this.raiseError(missingFormNameMsg + "\n");
	}
	xmlMessage = "<Form name=" + '"' + encodeURIComponent(formname) + '"' + ">\n";
		
	// The form_email_addr is optional but if we have it make sure
	// that is has a valid email address.
	// There also could be more than one destination address so each
	// must be checked.
	var form_email_addr = superform_getSingleField("form_email_addr");
	
	if (form_email_addr != null) {
		if (isEmailAddress(form_email_addr)) {
			xmlMessage += "<Email Address=" + '"' + encodeURIComponent(form_email_addr) + '" ';
		} else {
			var invalidToEmailMsg = document.getElementById("invalid_to_email_msg").innerHTML;
			this.raiseError(invalidToEmailMsg + form_email_addr + "\n");
		}
	} else {
		xmlMessage += "<Email Address= ";			
	}
	
	// Get the subject
	var form_email_subject = superform_getSingleField("form_email_subject");
	if (form_email_subject != null) {
		xmlMessage += " Subject=" + '"' + encodeURIComponent(form_email_subject) + '"';
	} else {
		xmlMessage += " Subject= ";			
	}
	
	// Get the Country Name - If null default to US
	var form_country_name = superform_getSingleField("form_country_name");
	if (form_country_name == null) form_country_name = "US";
	xmlMessage += " CountryName=" + '"' + encodeURIComponent(form_country_name) + '"';

	// If the form_email_format is missing then set it to Text
	var form_email_format = superform_getSingleField("form_email_format").toLowerCase();
	if (form_email_format == null) form_email_format = "text";
	if (form_email_format == "text/plain") {
		xmlMessage += " Format=" + '"' + "text/plain" + '"' + " />";
	} else if (form_email_format == "text/html") {
		xmlMessage += " Format=" + '"' + "text/html" + '"' + " />";
	} else {
		var invalidToEmailFormatMsg = document.getElementById("invalid_to_email_format").innerHTML;
		this.raiseError(invalidToEmailFormatMsg + form_email_format + "\n");
	}

	// Now read and parse through the other types
    var msg = "<Form_Data>";
    var controltype = "";
    var isRequired = false;
    var formcontrol = new Object();
    var controlname = null;
    var missingFields = new Array();
    
    // Enumerate through all the controls
    for (x = 0; x < myForm.elements.length; x++) {
    	formcontrol = myForm.elements[x];
    	controltype = formcontrol.type;
	if (controltype != "hidden" && controltype != "button" && controltype != "reset")
		controlname = superform_cleanString(superform_getLabelForName(formcontrol.name).innerHTML);


    	// Check to see if the field is required
    	var classNames = new Array();
		classNames = formcontrol.className.split(" ");
		isRequired = false;
		for (var i = 0; i < classNames.length; i++){
			if (classNames[i] == "superform_required")
				isRequired = true;
		}

		// Process the appropriate type of control
    	switch (controltype) {
    	case "radio":
    		if (formcontrol.checked) {
     			msg += "<form_field>" + encodeURIComponent(controlname) + "</form_field><form_value>" + encodeURIComponent(formcontrol.value) + "</form_value>\n";
    		}
	    	if (isRequired && superform_isBlank(formcontrol.name, "radio") && !superform_contains(missingFields, controlname)){
			missingFields.push(controlname);
		}
    		break;
    		
    	case "checkbox":
    		if (formcontrol.checked) {
     			msg += "<form_field>" + encodeURIComponent(controlname) + "</form_field><form_value>" + encodeURIComponent(formcontrol.value) + "</form_value>\n";
    		}
	    	if (isRequired && superform_isBlank(formcontrol.name, "checkbox") && !superform_contains(missingFields, controlname)){
			missingFields.push(controlname);
		}
     		break;
    		
    	case "select-multiple":
    		var selected = superform_getSelected(formcontrol);
    		for (var item=0; item < selected.length; item++) {
    			msg += "<form_field>" + encodeURIComponent(controlname) + "</form_field><form_value>" + encodeURIComponent(selected[item].value) + "</form_value>\n";
    		}
	    	if (isRequired && selected.length < 1 && !superform_contains(missingFields, controlname)){
			missingFields.push(controlname);
		}
    		break;
    		
    	case "text":
    		// Use the label as the name
    		for (var i = 0; i < classNames.length; i++) {
	    		switch (classNames[i]) {
	    		case "phone_us":
	    			if (!superform_isEmpty(formcontrol.value)) {
		    			if (!superform_isValidUSPhone(formcontrol.value)) {
						var invalidPhoneMsg = document.getElementById("invalid_phone_msg").innerHTML;
		    				this.raiseError(invalidPhoneMsg + formcontrol.value + "\n");
		    			}
	    			}
	    			break;
	    			
	    		case "phone_eu":
	    			if (!superform_isEmpty(formcontrol.value)) {
		    			if (!superform_isValidOUSPhone(formcontrol.value)) {
						var invalidPhoneMsg = document.getElementById("invalid_phone_msg").innerHTML;
		    				this.raiseError(invalidPhoneMsg + formcontrol.value + "\n");
		    			}
	    			}
	    			break;

	    		case "zip":
	    			if (!superform_isEmpty(formcontrol.value)) {
		    			if (!superform_isValidZipCode(formcontrol.value)) {
						var invalidZipMsg = document.getElementById("invalid_zip_msg").innerHTML;
		    				this.raiseError(invalidZipMsg + formcontrol.value + "\n");
		    			}
	    			}
	    			break;
	    			
	    		case "email":
	    			if (!superform_isEmpty(formcontrol.value)) {
		    			if (!superform_isEmailAddress(formcontrol.value)) {
						var invalidEmailMsg = document.getElementById("invalid_email_msg").innerHTML;
		    				this.raiseError(invalidEmailMsg + formcontrol.value + "\n")
		    			}
	    			}
	    			break;
	    		}
	    	}

    		msg += "<form_field>" + encodeURIComponent(controlname) + "</form_field><form_value>" + encodeURIComponent(formcontrol.value) + "</form_value>\n";
	    	if (isRequired && superform_isBlank(formcontrol.name, "text") && !superform_contains(missingFields, controlname)){
			missingFields.push(controlname);
		}

    		break;
    		
    	case "textarea":
    		// Use the label as the control name
    		msg += "<form_field>" + encodeURIComponent(controlname) + "</form_field><form_value>" + encodeURIComponent(formcontrol.value) + "</form_value>\n";
	    	if (isRequired && superform_isBlank(formcontrol.name, "textarea") && !superform_contains(missingFields, controlname)){
			missingFields.push(controlname);
		}

    		break;
    		
    	case "password":
    		// Use the label as the control name
    		msg += "<form_field>" + encodeURIComponent(controlname) + "</form_field><form_value>" + encodeURIComponent(formcontrol.value) + "</form_value>\n";
	    	if (isRequired && superform_isBlank(formcontrol.name, "password") && !superform_contains(missingFields, controlname)){
			missingFields.push(controlname);
		}

    		break;
    		
    	case "select-one":
    		msg += "<form_field>" + encodeURIComponent(controlname) + "</form_field><form_value>" + encodeURIComponent(formcontrol.value) + "</form_value>\n";
    		break;

    	default:
    		break;
    	}

    	controlname = null;

    }
	var missingRequiredValMsg = document.getElementById("missing_required_val_msg").innerHTML + '\n';
	for (var i = 0; i < missingFields.length; i++){
		missingRequiredValMsg += '\t' + missingFields[i] + '\n';
	}
	if (missingFields.length > 0)
		this.raiseError(missingRequiredValMsg);
       msg += "</Form_Data></Form>"
       xmlMessage += msg;	
	return xmlMessage;
}

// Processes the Submit Form button
// The form data gets submitted via AJAX
function superform_submitForm() {
    var formName = document.getElementById("superform");
    if (formName == null) {
    	alert("Missing SuperForm");
    } else {
    	var myForm = document.forms["superform"];
    	
	    // Change the submit button to say "processing"
	    var buttons = getElementsByClassName(myForm, "form_button");
	    var submitMessage = document.getElementById("superform_submit_button_txt").innerHTML;
	    var processingMessage = document.getElementById("superform_submit_button_processing_txt").innerHTML;
	    for (var i=0; i < buttons.length; i++){
	    	if (buttons[i].value == submitMessage) 
	    		buttons[i].value = processingMessage;
	    }

	    // Set up array to hold error messages
	    this.errorList = new Array;
	
	    // Set up object methods
	    this.isEmpty = superform_isEmpty;	
	    this.isEmailAddress = superform_isEmailAddress;	
	
	    this.raiseError = superform_raiseError;	
	    this.numErrors = superform_numErrors;	
	    this.displayErrors = superform_displayErrors;
	 
	    // Validate the form and display the errors
	    var xmlMessage = superform_validateForm(myForm);
	    var xmlData = superform_cleanString(xmlMessage);
	    if (this.numErrors() > 0) {
	    	this.displayErrors();
	    } else {
			var request = createRequest();
			var url = '/MicrositeSuperform.bsci';
			var params = 'superformXML=' + encodeURIComponent(xmlData);
			request.open("POST", url, true);
			request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
			request.setRequestHeader("Content-length", params.length);
			request.setRequestHeader("Connection", "close");
			request.onreadystatechange = function(){superform_processServerSuperformResponse(request);};
			request.send(params);
	    }
	    
	    // Change the submit button from Processing to Submit
	    var submitMessage = document.getElementById("superform_submit_button_txt").innerHTML;
	    var processingMessage = document.getElementById("superform_submit_button_processing_txt").innerHTML;
	    for (var item=0; item < buttons.length; item++) {
	    	if (buttons[item].value == processingMessage) buttons[item].value = submitMessage;
	    }
    }
    
    // Process the response from AJAX
    function superform_processServerSuperformResponse(request){
    	// if server response is success, display a success message
    	// if server response is failure or anything else, display a failure message
    	if (request.readyState == 4){
    		if (request.status == 200){

    			if (request.responseText == 'success'){
    				alert(document.getElementById("form_success_msg").innerHTML);
    				superform_clearForm();
    			} else {
    				alert(document.getElementById("form_failure_msg").innerHTML);
    			}
    		} else {
    			document.getElementById("form_failure_msg").style.display = "block";
    		}
    	}
    }
}

function superform_clearForm(){
	var inputs = document.documentElement.getElementsByTagName("input");
	for (var i = 0; i < inputs.length; i++){
		if (inputs[i].type != "hidden" && inputs[i].type != "button" && inputs[i].type != "reset")
			inputs[i].value = "";
	}
	var textareas = document.documentElement.getElementsByTagName("textarea");
	for (var i = 0; i < textareas.length; i++){
		textareas[i].value = "";
	}
}

function superform_contains(array, element){
	for (var i = 0; i < array.length; i++){
		if (array[i] == element) return true;
	}
	return false;
}

