/**
 * Reference: Sandeep V. Tamhankar (stamhankar@hotmail.com),
 * http://javascript.internet.com
 */
var firstErrorFocus = null;
var errorLabelList = new Array();
var errorMsgList = new Array();

// Trim whitespace from left and right sides of s.
function trim(s) {
	return s.replace(/^\s*|\s*$/g, "");
}
function trimAjax(s) {
	var r = s.replace(/^(\r\n)*|(\r\n)*$/g, "");
	r = trim(r);
	return r;
}
/* QUERY STRING -------------------------------------------------------------*/
function Querystring(qs) { // optionally pass a querystring to parse
	this.params = new Object()
	this.get=Querystring_get
	if (qs.length == 0) return

// Turn <plus> back to <space>
// See: http://www.w3.org/TR/REC-html40/interact/forms.html#h-17.13.4.1
	qs = qs.replace(/\+/g, ' ')
	var args = qs.split('&') // parse out name/value pairs separated via &

// split out each name=value pair
	for (var i=0;i<args.length;i++) {
		var value;
		var pair = args[i].split('=')
		var name = unescape(pair[0])
		if (pair.length == 2)
			value = unescape(pair[1])
		else
			value = name
		this.params[name] = value;
	}
}
function Querystring_get(key, default_) {
	// This silly looking line changes UNDEFINED to NULL
	if (default_ == null) default_ = null;
	var value=this.params[key]
	if (value==null) value=default_;
	//alert("key : " + key + " value : " + value);
	return value;
}
/* QUERY STRING END ---------------------------------------------------------*/
function isNumeric(sText)
{
   var validChars = "0123456789.";
   var isNumber=true;
   var char;
   for (i = 0; i < sText.length && isNumber == true; i++)
   {
      char = sText.charAt(i);
      if (validChars.indexOf(char) == -1) {
         isNumber = false;
         break;
      }
   }
   return isNumber;
}
/* fieldTypes.js **************************************************************/
function numbersOnly(myfield, e, dec)
{
var key;
var keychar;

if (window.event)
   key = window.event.keyCode;
else if (e)
   key = e.which;
else
   return true;
keychar = String.fromCharCode(key);

// control keys
if ((key==null) || (key==0) || (key==8) ||
    (key==9) || (key==13) || (key==27) )
   return true;

// numbers
else if ((("0123456789").indexOf(keychar) > -1))
   return true;

// decimal point jump
/*
else if (dec && (keychar == "."))
   {
   myfield.form.elements[dec].focus();
   return false;
   }
*/
else if ((keychar == ".") && dec && (dec==true))
   {
   return true;
   }
else
   return false;
}
// -----------------------------------------------------------------------------

function checkEmail(emailStr) {
   if (emailStr.length == 0) {
       return true;
   }
   var emailPat=/^(.+)@(.+)$/;
   var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]";
   var validChars="\[^\\s" + specialChars + "\]";
   var quotedUser="(\"[^\"]*\")";
   var ipDomainPat=/^(\d{1,4})[.](\d{1,4})[.](\d{1,4})[.](\d{1,4})$/;
   var atom=validChars + '+';
   var word="(" + atom + "|" + quotedUser + ")";
   var userPat=new RegExp("^" + word + "(\\." + word + ")*$");
   var domainPat=new RegExp("^" + atom + "(\\." + atom + ")*$");
   var matchArray=emailStr.match(emailPat);
   if (matchArray == null) {
       return false;
   }
   var user=matchArray[1];
   var domain=matchArray[2];
   if (user.match(userPat) == null) {
       return false;
   }
   var IPArray = domain.match(ipDomainPat);
   if (IPArray != null) {
       for (var i = 1; i <= 4; i++) {
          if (IPArray[i] > 255) {
             return false;
          }
       }
       return true;
   }
   var domainArray=domain.match(domainPat);
   if (domainArray == null) {
       return false;
   }
   var atomPat=new RegExp(atom,"g");
   var domArr=domain.match(atomPat);
   var len=domArr.length;
   if ((domArr[domArr.length-1].length < 2) ||
       (domArr[domArr.length-1].length > 4)) {
       return false;
   }
   if (len < 2) {
       return false;
   }
   return true;
}

function getFieldValue(field){
	var value = '';
	if (field){
    	// get field's value
    	if (field.type == "select-one") {
       		var si = field.selectedIndex;
        	if (si >= 0) {
            	value = field.options[si].value;
        	}
    	} else if (field.type == 'checkbox') {
        	if (field.checked) {
            	value = field.value;
        	}
    	} else if ((field.length > 0) && (field[0].type == 'radio' || field[0].type == 'checkbox')) {
            var isChecked=-1;
            for (loop=0; loop < field.length; loop++) {
                if (field[loop].checked) {
                    isChecked=loop;
                    value = field[loop].value;
                    break; // only one needs to be checked
                }
            }
    	} else {
        	value = field.value;
    	}
    }
    return value;
}

function resetNormalStyle(){
	while(errorLabelList.length > 0){
		var label = errorLabelList.pop();
		if (label.defaultColor!=undefined) {
			label.style.color = label.defaultColor;
		}
	}
}

function setErrorStyle(labelId){
	var label = document.getElementById(labelId);
	//alert("setErrorStyle :" + labelId);
	if (label) {
		if (label.defaultColor==undefined) {
			label.defaultColor = (label.style.color!=undefined ? label.style.color : '');
		}
		label.style.color = 'red';
		errorLabelList.push(label);
	}
}

function displayErrorMessages(elementId){
	var errorHTML = '';
	if (errorMsgList.length > 0){
		errorHTML += "<ul>";
		for (var i = 0; i < errorMsgList.length; i++) {
			errorHTML += "<li>" + errorMsgList[i] + "</li>\n";
		}
		errorHTML += "</ul>";
		var elementObj = document.getElementById(elementId);
		if (elementObj) 
			elementObj.innerHTML = errorHTML ;
	}	
}

function clearErrorMessages(elementId){
	errorMsgList.length = 0;
	var elementObj = document.getElementById(elementId);
	if (elementObj) 
		elementObj.innerHTML = '' ;
}

function validate_abstract(form,validator_name){
	var valid = true;
	var formName = form.getAttributeNode("name"); 
	var oAbstract = window[formName.value + '_' + validator_name];

    for (var i = 0; i < oAbstract.length; i++){
        var field = form[oAbstract[i]];
        var thisValid = window[validator_name](field);
		if (!thisValid) {
			valid = false;
			setErrorStyle(oAbstract[i] + '_label');
			if (firstErrorFocus==null) {
				firstErrorFocus = ((field.length > 0) ? field[0] : field);
			}
		}
	}
	if (!valid && (window[validator_name + '_msg'])){
		errorMsgList.push(window[validator_name + '_msg']);
	}
	return valid;
}
/*
function validate_equals2(form,fieldArray){
	var valid = true;
	var i = 0;
	var validator_name = 'validate_equals';
	if (fieldArray.length <= 1) return valid;
	for (i in fieldArray){ 
		valid = valid && 
			(getFieldValue(form[fieldArray[0]]) == getFieldValue(form[fieldArray[i]])); 
		if (!valid) break;
	}
	var field = form[fieldArray[i]];
	if (!valid) {
		setErrorStyle(field.name + '_label');
		if (firstErrorFocus==null) firstErrorFocus = field;
		if (window[validator_name + '_msg'])
			errorMsgList.push(window[validator_name + '_msg']);
	}	
	return valid;
}
*/
function validate_required(field){
	var valid = true;
    if ((field.length > 0) && (field[0].type == 'radio' || field[0].type == 'checkbox')) {
        var isChecked=-1;
        for (loop=0; loop < field.length; loop++) {
            if (field[loop].checked) {
                isChecked=loop;
                break; // only one needs to be checked
                //alert('checked  = ' + field[loop].value);
            }
        }
        if (isChecked < 0) {
        	valid = false;
        }
    } else {
		valid = (trim(getFieldValue(field)).length > 0);
    }
    return valid;
}

function validate_email(field){
    var emailStr = getFieldValue(field);
	return (emailStr=='' || checkEmail(emailStr));
}

function validate_password(field){
	var valid = true;
	var password = getFieldValue(field);
	var illegalChars = /[\W_]/; // allow only letters and numbers
	var re = /^\w*(?=\w*\d)(?=\w*[a-z])\w*$/i;
	if (password.length < 8) {
		valid = false;
	} else if (illegalChars.test(password)) {
		valid = false;
	} else if (!re.test(password)){
		valid = false;
	}
    return valid;
}
// Still abstract 
function validate_equals(field_1,field_2){
    var valid = getFieldValue(field_1) == getFieldValue(field_2);
	if (!valid) {
		setErrorStyle(field_2.name + '_label');
		if (firstErrorFocus==null) firstErrorFocus = field_2;
		if (window['validate_equals_msg']) 
			errorMsgList.push(window['validate_equals_msg']);
	}
	return valid;
}
