function $(id)
{
	return document.getElementById(id);
}

var mandatoryFieldsList = [];

function main_body_onloaded()
{
	// call bodyOnLoad() function, if defined
	if (self.bodyOnLoad)
	{
		bodyOnLoad();
	}
	// initialize mandatory fields
	if ( checkBrowser() )
	{
		for (var i = 0; i < mandatoryFieldsList.length; ++i)
		{
			var id = mandatoryFieldsList[i];
			$(id).setAttribute('onblur', 'mandatory(["' + id + '"])');
		}
	}
	else
	{
		for (var i = 0; i < mandatoryFieldsList.length; ++i)
		{
			$(mandatoryFieldsList[i]).setAttribute('onblur', function () { mandatory([(window.event.srcElement || window.event.target).getAttribute('id')]) });
		}
	}
	// disable forms on unload
	setOnUnload( 'disable_all_forms' );
}

function setOnUnload( _funcName )
{
	other_unloads = document.body.getAttribute('onunload');
	if ( other_unloads )
	{
	    document.body.setAttribute('onunload', other_unloads + _funcName + '();');
	}
	else
	{
	    document.body.setAttribute('onunload', _funcName + '();');
	}
}

function disable_all_forms()
{
	// on submit, disable all forms submit controls
	var forms = document.getElementsByTagName('form');
	for (var i = 0 ; i < forms.length; ++i)
	{
		forms[i].setAttribute('onsubmit', 'return false');
	}
}

function canDelete()
{
	return confirm('Are you sure you want to delete this record?');
}

// returns TRUE if all the fields with the given id's have values, FALSE otherwise
// param string[] field_list
// examples: mandatory(['name'])  ;  mandatory(['first_name', 'last_name']);
// loops through all the fields:
//   if a field's value is empty, appends a <br> and a <span> with the 'This field is mandatory' message
//   if a field has a value and it already has a 'mandatory' <span>, the <br> and <span> are removed
// WARNING: the given fields must not have any other siblings!
function mandatory(field_list, regexp, err_msg)
{
	var ok = true; // assume all values are ok
	var element;
	var parent;
	var warn;
	// default expression: field must not be empty
	if ((typeof regexp) == 'undefined')
	{
		regexp = /(.+)/;
	}
	// default message: This field is mandatory
	if ((typeof err_msg) == 'undefined')
	{
		err_msg = 'This field is mandatory';
	}
	// if the first parameter isn't an array of fields, make it
	if ((typeof field_list) == 'string')
	{
		field_list = [field_list];
	}
	// loop through the fields list, checking if the values match the given regexp
	for (var i = 0; i < field_list.length; ++i)
	{
		// get each element (if it's a string, get the element with that id)
		if ((typeof field_list[i]) == 'string')
		{
			element = document.getElementById(field_list[i]);
		}
		else
		{
			element = field_list[i];
		}
		// find the parent to which we will attach the warning message
		parent = element.parentNode;
		if ( parent )
		{
    		// remove dummy text nodes (as W3C specifies, blank characters are included in the nodes tree by some browsers)

		}
		var has_warn = (element.nextSibling && element.nextSibling.nextSibling && element.nextSibling.nextSibling.getAttribute && (element.nextSibling.nextSibling.getAttribute('name') == 'mandatory'));

        // empty value & warn doesn't exist: display warning
		if (!regexp.test(element.value))
		{
			ok = false;
			// warn doesn't exist: create it
			if (!has_warn)
			{
				parent.appendChild(document.createElement('BR'));
				warn = document.createElement('SPAN');
				warn.appendChild(document.createTextNode(err_msg));
				warn.setAttribute('name', 'mandatory');
				warn.style.color = 'red';
				parent.appendChild(warn);
			}
			// warn exists: change/update it's text
			else
			{
				// parent.firstChild.nextSibling.nextSibling.innerHTML = err_msg;
			}
		}
		// non-empty value & warn exists: remove warning
		else
		{
			if (has_warn)
			{
				parent.removeChild(element.nextSibling);
				parent.removeChild(element.nextSibling);
			}
		}
	}
	return ok;
}
function mandatory3(field_list, regexp, err_msg)
{
	var ok = true; // assume all values are ok
	var element;
	var parent;
	var warn;
	// default expression: field must not be empty
	if ((typeof regexp) == 'undefined')
	{
		regexp = /(.+)/;
	}
	// default message: This field is mandatory
	if ((typeof err_msg) == 'undefined')
	{
		err_msg = 'This field is mandatory';
	}
	// if the first parameter isn't an array of fields, make it
	if ((typeof field_list) == 'string')
	{
		field_list = [field_list];
	}
	// loop through the fields list, checking if the values match the given regexp
	for (var i = 0; i < field_list.length; ++i)
	{
		// get each element (if it's a string, get the element with that id)
		if ((typeof field_list[i]) == 'string')
		{
			element = document.getElementById(field_list[i]);
		}
		else
		{
			element = field_list[i];
		}
		// find the parent to which we will attach the warning message
		parent = element.parentNode;
		if ( parent )
		{
    		// remove dummy text nodes (as W3C specifies, blank characters are included in the nodes tree by some browsers)

		}
		var has_warn = (element.nextSibling && element.nextSibling.nextSibling);
        // empty value & warn doesn't exist: display warning
		if (!regexp.test(element.value))
		{
		    ok = false;
			// warn doesn't exist: create it
			if (!has_warn)
			{
				parent.appendChild(document.createElement('BR'));
				warn = document.createElement('SPAN');
				warn.appendChild(document.createTextNode(err_msg));
				warn.setAttribute('name', 'mandatory');
				warn.style.color = 'red';
				parent.appendChild(warn);
			}
			// warn exists: change/update it's text
			else
			{
				// parent.firstChild.nextSibling.nextSibling.innerHTML = err_msg;
			}
		}
		// non-empty value & warn exists: remove warning
		else
		{
			if (has_warn)
			{
				parent.removeChild(element.nextSibling);
				parent.removeChild(element.nextSibling.nextSibling);
			}
		}
	}
	return ok;
}

function mandatory2(field_list, regexp, err_msg)
{
	var ok = true; // assume all values are ok
	var element;
	var parent;
	var warn;
	var error_string = '';
	var not_filled = new Array();
	// default expression: field must not be empty
	if ((typeof regexp) == 'undefined')
	{
		regexp = /(.+)/;
	}
	// default message: This field is mandatory
	if ((typeof err_msg) == 'undefined')
	{
		err_msg = 'This field is mandatory';
	}
	// if the first parameter isn't an array of fields, make it
	if ((typeof field_list) == 'string')
	{
		field_list = [field_list];
	}
	// loop through the fields list, checking if the values match the given regexp
	for (var i = 0; i < field_list.length; ++i)
	{
		// get each element (if it's a string, get the element with that id)
		if ((typeof field_list[i]) == 'string')
		{
			element = $(field_list[i]);
		}
		else
		{
			element = field_list[i];
		}
		// find the parent to which we will attach the warning message
		parent = element.parentNode;
		// remove dummy text nodes (as W3C specifies, blank characters are included in the nodes tree by some browsers)
		while (element.nextSibling && (element.nextSibling.nodeType == 3))
		{
			parent.removeChild(element.nextSibling);
		}
		var has_warn = (element.nextSibling && element.nextSibling.nextSibling && element.nextSibling.nextSibling.getAttribute && (element.nextSibling.nextSibling.getAttribute('name') == 'mandatory'));
		// empty value & warn doesn't exist: display warning
		if (!regexp.test(element.value))
		{
			ok = false;
			error_string += 'Field "' + field_list[i] + '" is required!\n';
			array_push(not_filled, field_list[i]);
			// warn doesn't exist: create it
			if (!has_warn)
			{
				parent.appendChild(document.createElement('br'));
				warn = document.createElement('span');
				warn.appendChild(document.createTextNode(err_msg));
				warn.setAttribute('name', 'mandatory');
				warn.style.color = 'red';
				parent.appendChild(warn);
			}
			// warn exists: change/update it's text
			else
			{
				// parent.firstChild.nextSibling.nextSibling.innerHTML = err_msg;
			}
		}
		// non-empty value & warn exists: remove warning
		else
		{
			if (has_warn)
			{
				parent.removeChild(element.nextSibling);
				parent.removeChild(element.nextSibling);
			}
		}
	}
	if (error_string)
	{
	    error_string += 'Please fill in the fields having red warning text below them!';
	    if (not_filled.length)
	    {
		document.getElementById(not_filled[0]).focus();
	    }

	}
	return ok;
}

function array_push(vector)
{
    var i;
    var argv = arguments;
    var argc = argv.length;

    for (i = 1; i < argc; ++i)
    {
	vector[vector.length++] = argv[i];
    }
    return vector.length;
}

// any number of digits
function checkNumeric(elements, is_optional)
{
	var exp;
	if (is_optional)
	{
		exp = /^\d*$/;
	}
	else
	{
		exp = /^\d+$/;
	}
	return mandatory(elements, exp, 'Invalid number');
}

// five digits or: AdA dAd (A => capital letter, d => digit)
var _validation_state = false;
function checkZip(elements, is_optional, _validation_state)
{
	var exp;
	if ( _validation_state != false )
	{

        _validation_state = $(_validation_state).value;

	    var state = [];
        state['AB'] = 'CA';
        state['AK'] = 'US';
        state['AL'] = 'US';
        state['AR'] = 'US';
        state['AZ'] = 'US';
        state['BC'] = 'CA';
        state['CA'] = 'US';
        state['CO'] = 'US';
        state['CT'] = 'US';
        state['DC'] = 'US';
        state['DE'] = 'US';
        state['FL'] = 'US';
        state['GA'] = 'US';
        state['HI'] = 'US';
        state['IA'] = 'US';
        state['ID'] = 'US';
        state['IL'] = 'US';
        state['IN'] = 'US';
        state['KS'] = 'US';
        state['KY'] = 'US';
        state['LA'] = 'US';
        state['MA'] = 'US';
        state['MB'] = 'CA';
        state['MD'] = 'US';
        state['ME'] = 'US';
        state['MI'] = 'US';
        state['MN'] = 'US';
        state['MO'] = 'US';
        state['MS'] = 'US';
        state['MT'] = 'US';
        state['NB'] = 'CA';
        state['NC'] = 'US';
        state['ND'] = 'US';
        state['NE'] = 'US';
        state['NH'] = 'US';
        state['NJ'] = 'US';
        state['NL'] = 'CA';
        state['NM'] = 'US';
        state['NS'] = 'CA';
        state['NT'] = 'CA';
        state['NU'] = 'CA';
        state['NV'] = 'US';
        state['NY'] = 'US';
        state['OH'] = 'US';
        state['OK'] = 'US';
        state['ON'] = 'CA';
        state['OR'] = 'US';
        state['PA'] = 'US';
        state['PE'] = 'CA';
        state['PR'] = 'US';
        state['QC'] = 'CA';
        state['RI'] = 'US';
        state['SC'] = 'US';
        state['SD'] = 'US';
        state['SK'] = 'CA';
        state['TN'] = 'US';
        state['TX'] = 'US';
        state['UT'] = 'US';
        state['VA'] = 'US';
        state['VT'] = 'US';
        state['WA'] = 'US';
        state['WI'] = 'US';
        state['WV'] = 'US';
        state['WY'] = 'US';
        state['YT'] = 'CA';
        validation_type = state[_validation_state];

        if ( !validation_type )
        {
            alert('Select a state first!');
        }

    	if (is_optional)
    	{
    	    if ( validation_type == 'US' )
    	    {
        		exp = /^(\d{5})?$/;
    	    }
        	else if ( validation_type == 'CA' )
        	{
        	    exp = /^([A-Za-z]\d[A-Za-z] ?\d[A-Za-z]\d)?$/;
        	}
    	}
    	else
    	{
    	    if ( validation_type == 'US' )
    	    {
        		exp = /^(\d{5})$/;
    	    }
        	else if ( validation_type == 'CA' )
        	{
        	    exp = /^([A-Za-z]\d[A-Za-z] ?\d[A-Za-z]\d)$/;
        	}
    	}
	}
	else
	{
    	if (is_optional)
    	{
       	    exp = /^((\d{5})|([A-Za-z]\d[A-Za-z] ?\d[A-Za-z]\d))?$/;
    	}
    	else
    	{
            exp = /^((\d{5})|([A-Za-z]\d[A-Za-z] ?\d[A-Za-z]\d))$/;
    	}
	}
	return mandatory(elements, exp, 'Invalid zip code');
}

function checkZip2(elements, is_optional)
{
	var exp;
	if (is_optional)
	{
		exp = /^((\d{5})|([A-Z]\d[A-Z] \d[A-Z]\d))?$/;
	}
	else
	{
		exp = /^((\d{5})|([A-Za-z]\d[A-Za-z] ?\d[A-Za-z]\d))$/;
	}
	return mandatory2(elements, exp, 'Invalid zip code');
}


function checkZipUS(elements, is_optional)
{
	var exp;
	if (is_optional)
	{
		exp = /^(\d{5})?$/;
	}
	else
	{
		exp = /^(\d{5})$/;
	}
	return mandatory(elements, exp, 'Invalid zip code');
}


//added function to handle the tabbing between the fields for the Phone numbers
//and saving them in a hidden field
function autotab(fieldname, original, destination){
	var phone_number = "("+document.getElementById(fieldname+'_1').value+") ";
	phone_number += document.getElementById(fieldname+'_2').value + "-";
	phone_number += document.getElementById(fieldname+'_3').value;
	if ( !document.getElementById(fieldname+'_1').value
	  && !document.getElementById(fieldname+'_2').value
	  && !document.getElementById(fieldname+'_3').value ){
		phone_number = '';
	}
	document.getElementById(fieldname).value = phone_number;
	if(fieldname == 'phone2' || fieldname == 'phone4' || fieldname == 'fax'){
		if(document.getElementById(fieldname).value.length > 4){
			//if(fieldname == "fax") checkFax(fieldname, true);
			//else checkPhone(fieldname, true);
		}else{
			phone_number = "";
			document.getElementById(fieldname).value = phone_number;
			//if(fieldname == "fax") checkFax(fieldname, true);
			//else checkPhone(fieldname, true);
		}
	}
	else{
		//checkPhone(fieldname, true);
	}
	if (document.getElementById(fieldname).value.length > 13) {
		checkPhone(fieldname, true);
	}
	original.focus();
	if(original.name == fieldname+"_1" || original.name == fieldname+"_2"){
		if (original.getAttribute&&original.value.length==original.getAttribute("maxlength")){
			document.getElementById(destination).focus();
		}
	}
}
function checkPhone3(elements, is_optional)
{
	var exp;
	if (is_optional)
	{
		exp = /^(\(?\d{3}\)?(\s|-)?\d{3}(\s|-)?\d{4})?$/;
	}
	else
	{
		exp = /^(\(?\d{3}\)?(\s|-)?\d{3}(\s|-)?\d{4})$/;
	}
	var phone_number = "("+document.getElementById('phone_1').value+") ";
	phone_number += document.getElementById('phone_2').value + "-";
	phone_number += document.getElementById('phone_3').value;
	document.getElementById(elements).value = phone_number;
	return mandatory3(elements, exp, 'Invalid phone number');
}

// (000) ddd-dddd (brackets, space and minus are optional)
function checkFax3(elements, is_optional)
{
	var exp;
	if (is_optional)
	{
		exp = /^(\(?\d{3}\)?(\s|-)?\d{3}(\s|-)?\d{4})?$/;
	}
	else
	{
		exp = /^(\(?\d{3}\)?(\s|-)?\d{3}(\s|-)?\d{4})$/;
	}
	var fax_number = "("+document.getElementById('fax_1').value+") ";
	fax_number += document.getElementById('fax_2').value + "-";
	fax_number += document.getElementById('fax_3').value;
	if( document.getElementById('fax_1').value!='' || document.getElementById('fax_2').value!='' ||document.getElementById('fax_3').value!='' )
	   document.getElementById(elements).value = fax_number;
	else{

	    element = document.getElementById(elements);
        parent = element.parentNode;
	    if ( element.nextSibling && element.nextSibling.nextSibling ){
            parent.removeChild(element.nextSibling);
    		parent.removeChild(element.nextSibling.nextSibling);
    	}
        return true
    }
	return mandatory3(elements, exp, 'Invalid fax number');
}

// (000) ddd-dddd (d => digit, space => optional space)
function checkPhone(elements, is_optional)
{
	var exp;
	if (is_optional)
	{
		exp = /^(\(?\d{3}\)?(\s|-)?\d{3}(\s|-)?\d{4})?$/;
	}
	else
	{
		exp = /^(\(?\d{3}\)?(\s|-)?\d{3}(\s|-)?\d{4})$/;
	}
	return mandatory(elements, exp, 'Invalid phone number');
}

// (000) ddd-dddd (brackets, space and minus are optional)
function checkFax(elements, is_optional)
{
	var exp;
	if (is_optional)
	{
		exp = /^(\(?\d{3}\)?(\s|-)?\d{3}(\s|-)?\d{4})?$/;
	}
	else
	{
		exp = /^(\(?\d{3}\)?(\s|-)?\d{3}(\s|-)?\d{4})$/;
	}
	return mandatory(elements, exp, 'Invalid fax number');
}

function checkFax2(elements, is_optional)
{
	var exp;
	if (is_optional)
	{
		exp = /^(\(\d{3}\)\s?\d{3}-\d{4})?$/;
	}
	else
	{
		exp = /^(\(\d{3}\)\s?\d{3}-\d{4})$/;
	}
	return mandatory2(elements, exp, 'Invalid fax number');
}


// Aa_-0.Aa_-0.. @ Aa_-0.Aa (email address)
function checkMail(elements, is_optional)
{
	var exp;
	if (is_optional)
	{
		exp = /^(([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4}))?$/;
	}
	else
	{
		exp = /^(([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4}))$/;
	}
	return mandatory(elements, exp, 'Invalid email address');
}

function isFloat(element_id, is_optional)
{
	if (is_optional)
	{
		return /^(\d+(\.\d+)?)?$/.test($(element_id).value);
	}
	else
	{
		return /^\d+(\.\d+)?$/.test($(element_id).value);
	}
}

function isSerial(element_id, is_optional)
{
    if (is_optional)
    {
        return /^([0-9]{8,9})?$/.test($(element_id).value);
    }
    else
    {
        return /^[0-9]{8,9}$/.test($(element_id).value);
    }
}

function IE6()
{
	return (navigator.appName=="Microsoft Internet Explorer");
}

function verifySerial(serial)
{
	if (!IsNumeric(serial) ||
					serial.length < 8 ||
					serial.length > 9 ||
					(parseInt(serial, 10) <= 0) )
	{
		return false;
	}
	return true;
}

function trim(str, chars) {
	return ltrim(rtrim(str, chars), chars);
}

function ltrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}

function rtrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}

function checkBrowser()
{
    return (
        navigator.appName == 'Netscape'
        || navigator.appName == 'Opera'
        || (navigator.appName == 'Microsoft Internet Explorer' && appVersion() >= 8)
    );
}

function appVersion()
{
    var versMajor = parseInt(navigator.appVersion,10);
    var appVers = navigator.appVersion;
    var pos, versMinor = 0;

    if ((pos = appVers.indexOf("MSIE")) > -1) {
        versMinor = parseFloat(appVers.substr(pos+5));
    } else {
        versMinor = parseFloat(appVers);
    }

    return (versMinor);
}

function formatName( _field )
{
	var name = '';
	var str = _field.value;
	var words = str.split(' ');
	for ( var i in words )
	{
		if ( words[i] )
		{
			name += words[i].substr(0, 1).toUpperCase() + words[i].slice(1).toLowerCase();
			name += ' ';
		}
	}
	_field.value = name.substr(0, name.length-1);
}