/* 
 author Marc Grabanski
 Modified by Ezekiel Motlana 2009-09-12
*/

var cleanValidator = {
	init: function (settings) {
		this.settings = settings;
		this.form = document.getElementById(this.settings["formId"]);
		formInputs = this.form.getElementsByTagName("input");
		
		// change color of inputs on focus
		for(i=0;i<formInputs.length;i++)
		{
			if(formInputs[i].getAttribute("type") != "submit" && formInputs[i].getAttribute("type") != "button") {
				input = formInputs[i];
				input.style.background = settings["inputColors"][0];
				input.onblur = function () {
					this.style.background = settings["inputColors"][0];
				}
				input.onfocus = function () {
					this.style.background = settings["inputColors"][1];
				}
			}
		};
		this.form.onsubmit = function () {
			error = cleanValidator.validate();
			if(error.length < 1) {
				return true;
			} else {
				cleanValidator.printError(error);
				return false;
			}
		};
	},
	validate: function () {
		error = '';
		validationTypes = new Array("isRequired", "isEmail", "isNumeric");
		for(n=0; n<validationTypes.length; n++) {
			var x = this.settings[validationTypes[n]];
			if(x != null) {
				for(i=0; i<x.length; i++) 
				{
					inputField = document.getElementById(x[i]);
					switch (validationTypes[n]) {
						case "isRequired" :
						valid = !isRequired(inputField.value);
						errorMsg = "is a required field.";
						break;
						case "isEmail" :
						valid = isEmail(inputField.value);
						errorMsg = "is an invalid email address.";
						break;
						case "isNumeric" :
						valid = isNumeric(inputField.value);
						errorMsg = "can only be a number.";
						break;
					}
					if(!valid) {
                                                // Remove an underscore at the beginning of input name
                                                inputName =  x[i];
                                                
                                                //inputName = inputName.substr(0, 1).toUpperCase() + inputName.substr(1);
						//inputName = cleanName(inputName);
						inputName = removeFormId(inputName);
						inputName = doCamelCase(inputName);
                                                error += inputName +" "+errorMsg+"\n";
						inputField.style.background = this.settings["errorColors"][0];
						inputField.style.border = "1px solid "+this.settings["errorColors"][1];
					} else {
						inputField.style.background = this.settings["inputColors"][0];
						inputField.style.border = '1px solid';
					}
				}
			}
		}
		return error;
	},
	printError: function (error) {
		alert(error);
	}
};

// returns true if the string is not empty
function isRequired(str){
	return (str == null) || (str.length == 0);
}
// returns true if the string is a valid email
function isEmail(str){
	if(isRequired(str)) return false;
	var re = /^[^\s()<>@,;:\/]+@\w[\w\.-]+\.[a-z]{2,}$/i
	return re.test(str);
}
// returns true if the string only contains characters 0-9 and is not null
function isNumeric(str){
	if(isRequired(str)) return false;
	var re = /[\D]/g
	if (re.test(str)) return false;
	return true;
}

function doCamelCase(str)
{
    str = str[0].toUpperCase() + str.substr(1);
    while (str.indexOf('_') != -1) {
                str = camelize(str);
    }
    return str;
}
  
function camelize(str)
{
    var strCamelized;
    var pattern = new RegExp('(_.)', 'i');
    var matches = str.match(pattern);

    if (matches != null) {
        strCamelized = str.replace(matches[1], matches[1].toUpperCase());
        strCamelized = strCamelized.replace('_', ' ');
        }
    return strCamelized;
}

function removeFormId(str)
{
	var strRemove = '_';
	arrInputName   =  str.split('_');
	strRemove       += arrInputName[arrInputName.length - 1];
	str = str.replace(strRemove, '');
	return str;
}

/**
 * Populate the state drop-down list with relevant states for the selected country 
 * @param strURL
 * @return
 */
function getState(strURL)
{         
	// fuction to get xmlhttp object	
	 var req = getXMLHTTP(); 
	 if (req) {
		  req.onreadystatechange = function() {
			  if (req.readyState == 4) { //data is retrieved from server
	              if (req.status == 200) { // which reprents ok status
					   document.getElementById('div_state').innerHTML=req.responseText;
				  }
			  } else {
				  document.getElementById('div_state').innerHTML='<img id="indicator" src="images/indicator.gif"/> Loading states...';  
			  }
		 }            
	  }        
	  //open url using get method
	  req.open("GET", strURL, true); 
	  req.send(null);
}

// Returns the xml http object for different browsers
function getXMLHTTP() { 
    var xmlhttp = false;	
	try{
		xmlhttp=new XMLHttpRequest();
	}
	catch(e){		
		try{			
			xmlhttp= new ActiveXObject("Microsoft.XMLHTTP");
		}
		catch(e){
			try{
			xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
			}
			catch(e1){
				xmlhttp=false;
			}
		}
	}
	return xmlhttp;
}


