// wForms - a javascript extension to web forms.
// Customization Example (wForms v0.94 - April 26 2005)
// Copyright (c) 2005 Cédric Savarese <pro@4213miles.com>
// This software is licensed under the CC-GNU LGPL <http://creativecommons.org/licenses/LGPL/2.1/>


//The Repeat behavior preserves the name attribute of radio inputs 
// accross repeated elements, effectively expanding the radio group. 
// Set to ‘false’ to make repeated radio inputs independant.
wf.preserveRadioName = true; // default: true.

// The validation routine will display an alert box if there’s an error, with the message in wf.arrErrorMsg[8]
wf.showAlertOnError = true; // default: true. 

// Error message displayed in the alert box.
wf.arrErrorMsg[8] = "%% error(s) detected. Your form has not been submitted yet.\nPlease check the information you provided."; // %% will be replaced by the actual number of errors.
wf.arrErrorMsg[9] = "The phone number does not appear to be valid.";
wf.arrErrorMsg[10] = "Please select one of the following choices.";
wf.arrErrorMsg[11] = "The passwords do not match. Please reenter the confirmation password.";

// overwrite the default form submission handler with a custom one.
wf.functionName_formValidation = "customValidation";

//evt : onSubmit event
function customValidation(evt) {

	if(wf.formValidation(evt)) {	// call the default error management.
		//var f = document.forms[0];
		var srcE = wf.utilities.getSrcElement(evt);
		
		while (srcE && srcE.tagName.toUpperCase() != 'FORM') {
			srcE = srcE.parentNode;
		}				
		var x = wf.utilities.getElements(srcE); //srcE.elements;  
		var nbTotalErrors = 0;

		for (var i=0;i<x.length;i++) {
			var nbErrors = 0;
			if ((' '+x[i].className+' ').indexOf(' '+wf.className_required+' ') != -1) {		
				if(wf.utilities.checkVisibility(x[i])) {
					isVisible = true;
					var v = true; // is Valid				
					switch(x[i].tagName.toUpperCase()) {
						case "INPUT":
							switch(x[i].getAttribute("type").toUpperCase()) {
								case "CHECKBOX":
									v = x[i].checked; 
									break;
								case "RADIO":
									v = x[i].checked; 
									break;
								default:
									v = !wf.isEmpty(x[i].value);
							}
							break;
						case "SELECT":
							v = !wf.isEmpty(x[i].options[x[i].selectedIndex].value);
							break;
						case "TEXTAREA":
							v = !wf.isEmpty(x[i].value);
							break;
						//case "FIELDSET":
						//	v = checkOneRequired(x[i]);
						//	break;
						case "DIV":
							v = checkOneRequired(x[i]);
							break;
						case "SPAN":
							v = checkOneRequired(x[i]);
							break;
					} // end switch
					if(!v) {
						// flag error
						wf.ShowError(x[i],wf.arrErrorMsg[1]);
						nbErrors++;
					}  else { // remove required error flag if any.
						var rErrClass = new RegExp(wf.className_validationError_fld,"gi");
						x[i].className = x[i].className.replace(rErrClass,"");
						var fe = document.getElementById(x[i].id +  self.idSuffix_fieldError);
						if(fe) fe.parentNode.removeChild(fe);
					} 
				} else { // not visible
				}
			} // end test=required

			// input validation
			if (x[i].className.indexOf(wf.classNamePrefix_validation) != -1) {
				if(!isVisible) isVisible =  wf.utilities.checkVisibility(x[i]);
				if(isVisible) {
					var arrClasses = x[i].className.split(" ");
					for (j=0;j<arrClasses.length;j++) {
						switch(arrClasses[j]) {
							case "validate-select":
								var xid = false;
								xid = wf.SelectRequired(x[i]);
								if(!xid) {
									// flag error
									wf.ShowError(x[i],wf.arrErrorMsg[10]);
									nbErrors++;
								}
								break;
							case "validate-phone":
								try
	  							{
									var xContent = srcE.Country.value;
									
									if ( (srcE.Country.value == "") || (srcE.Country.value == null) ) {
										xContent = srcE.country.value;
									}
									var strPhone = "";
									strPhone = wf.isValidPhone(x[i].value,x[i].name,xContent);
									//alert("Phone is " + strPhone);
									if(strPhone == null) {
										wf.ShowError(x[i],wf.arrErrorMsg[9]);
										nbErrors++;
									}
									else {
										if(strPhone == true)
											x[i].value = "";
										else
											x[i].value = strPhone;
									}
								}
								catch (e)
								{ /*Do nothing*/}
								break;
							case "validate-confpwd":
								var oPwd = srcE.pwd.value;
								var xPwd = srE.confpwd.value;
								if( oPwd != xPwd ) {
									// flag error
									wf.ShowError(x[i],wf.arrErrorMsg[11]);
									nbErrors++;
								}
								break;
							//case "validate-atleast5":
								//var iLength = x[i].value.length;
								//alert(iLength);
								//break;
						} // end switch
					} // end for
				}  else { // not visible
				}
			} // end validation check
				
			if(nbErrors>0) {
				nbTotalErrors+= nbErrors;
			} else {
				var rErrClass = new RegExp(self.className_validationError_fld,"gi");
				x[i].className = x[i].className.replace(rErrClass,"");
				var fe = document.getElementById(x[i].id +  wf.idSuffix_fieldError);
				if(fe) fe.parentNode.removeChild(fe);
			} 
		}
		if (nbTotalErrors > 0) {
			if(wf.showAlertOnError){  wf.showAlert(nbTotalErrors); }
			return wf.utilities.XBrowserPreventEventDefault(evt);
		}
		return true;
	} else {
		return wf.utilities.XBrowserPreventEventDefault(evt);  // will prevent the form from being submitted.
	}
}

// Validation Private Method
	// -------------------------
wf.SelectRequired = function(n) {	
	var v=null;
	if(n.nodeType != 1) return false;
	if(n.tagName.toUpperCase() == "INPUT") {
		switch(n.type.toLowerCase()) {
			case "checkbox":
				v = n.checked; 
				break;
			case "radio":
				v = n.checked; 
				break;
			default:
				v = n.getAttribute("value");
		}
	} else v = n.getAttribute("value");
	if(v && !self.isEmpty(v)) {
		return true;
	}
	for(var i=0; i<n.childNodes.length;i++) {
		if(checkOneRequired(n.childNodes[i])) return true;
	}
	return false;
}

wf.isValidPhone = function(sValue,sKey,sCtry) {

	var iLen = sCtry.length;
	var info = sCtry.lastIndexOf(" ");
	var sCountry = "";
	var strPhone = "";
	
	if (info > 0) { 
		sCountry = sCtry.substr(info+1,iLen);	
	}
	else { //Only a country is found
		sCountry = sCtry;
	}
	
	if ((sCountry == "US") || (sCountry == "CA")) {
		return wf.isEmpty(sValue) || FormatPhoneNum(sValue,sKey);
		//return wf.isEmpty(sValue) || isPhoneNum(sValue,sKey);
	}
	else {
		return wf.isEmpty(sValue) || FormatIntPhoneNum(sValue,sKey);
		//return wf.isEmpty(sValue) || isIntPhoneNum(sValue, sKey);
	}
}

/* Checks for invalid characters and phone number length 
   Formats phone number to xxx-xxx-xxxx (adds a space then ext if entered).
*/
function FormatPhoneNum(str,mType) 
{ 
	var sFormat = new String("");					//Phone String
    	var len = str.length;
	
   	//fax number is not required
   	if (mType == "fax"){
    		if (str == "") { return null;}
   	}
	
	//return false if phone value is empty
	if (len == 0)
		return null;
	
	/* Invalid characters check */
	str = str.replace(/_+/g,"");					//remove underscores				
	str = str.replace(/[A-Z,a-z,\s+,\W+]/gi,""); 	//remove all else except numbers

   	if(str.length == 0) 
  		return null;
   
   	if (str.length < 10)
		return null; 
   	  
	var sTemp = new String("");					//Initialize temp string
	var idx = 0;								//Initialize array index
	
	//Need to exclude leading 1's or 0's
	while( (str.charAt(idx) == 1) || (str.charAt(idx) == 0) ) {
		if(str.charAt(idx) == "")
			break;
		idx++;					//If 1 or 0 was entered first, increment idx
	}
	
	if (idx == str.length) 
		return null;	
	else 
		sTemp = str.substr(idx,str.length);			//Initialize temporary string with substring	
	
	sFormat = "(" + sTemp.substr(0,3) + ")";			//areacode + hyphen 
	sFormat += sTemp.substr(3,3) + "-";				//prefix + hyphen
	sFormat += sTemp.substr(6,4);						//next 4 numbers
	
	if (mType == "phone"){
		if ((sTemp.length > 10) && (sTemp.length < 16)) { //If ext entered
			sFormat += " ext. " + sTemp.substr(10,5);
		}
	}

	return sFormat;			// Set formated phone value
} //End of isPhoneNum()	
 
/* Checks for alpha characters and phone number length 
   for international numbers.
*/
function FormatIntPhoneNum(str,mType) 
{ 
	var sFormat = new String("");					//Phone String
    	var len = str.length;
		
   	//fax number is not required
   	if (mType == "fax"){
    	if (str == "") { return null;}
   	}
	
	//return false if phone value is empty
	if (len == 0)
		return null;
	
	/* Invalid characters check */
	sFormat = str.replace(/[A-Z,a-z]/gi,""); 	//remove all characters
	
	if(sFormat.length == 0)
		return null;
		
	//if(str.length == 0) 
  	//	return null;
	
	return sFormat;			// Return phone number
}

// Strips tags to retrieve the InnerText from a control
function ReplaceTags(xStr){
	var regExp = /<\/?[^>]+>/gi; 
     
	xStr = xStr.replace(regExp,"");
     return xStr;
}

function getHTML(sField)
{
	var xContent = document.getElementById(sfield).innerHTML;
	alert(xContent);
	
	var fixedContent = ReplaceTags(xContent);
     alert(fixedContent);
}


// Validation Private Method
// -------------------------
function checkOneRequired(n) {	
	var v=null;
	if(n.nodeType != 1) return false;
	if(n.tagName.toUpperCase() == "INPUT") {
		switch(n.type.toLowerCase()) {
			case "checkbox":
				v = n.checked; 
				break;
			case "radio":
				v = n.checked; 
				break;
			default:
				v = n.getAttribute("value");
		}
	} else v = n.getAttribute("value");
	if(v && !self.isEmpty(v)) {
		return true;
	}
	for(var i=0; i<n.childNodes.length;i++) {
		if(checkOneRequired(n.childNodes[i])) return true;
	}
	return false;
}

/*wf.ShowError = function (n,errorMsg) {		
	if(n.className.indexOf(wf.className_validationError_fld)!= -1) {
		return;
	}
	if (!n.id) n.id = wf.utilities.randomId(); // we'll need an id here.		
	// Add error flag to the field
	n.className += " " + wf.className_validationError_fld;
	// Prepare error message
	var msgNode = document.createTextNode(" " + errorMsg);
	// Find error message placeholder.
	var fe = document.getElementById(n.id +  wf.idSuffix_fieldError);
	if(!fe) { // create placeholder.
		fe = document.createElement("div"); 
		fe.setAttribute('id', n.id +  wf.idSuffix_fieldError);			
		// attach the error message after the field label if possible
		var fl = document.getElementById(n.id +  wf.idSuffix_fieldLabel);
		//var f1 = document.getElementById(n.id).getElementsByTagName("p");
		//alert(n.id);
		//alert(f1.parentNode);
		if(fl)
			fl.parentNode.insertBefore(fe,fl.nextSibling);
		else
			// otherwise, attach it after the field tag.
			n.parentNode.insertBefore(fe,n.nextSibling);
	}
	// Finish the error message.
	fe.appendChild(msgNode);  	
	fe.className += " " + wf.className_validationError_msg;
}*/


