// JavaScript Document
var popup = null;
var urlToRefreshTo = window.location.href;
var windowWidth = 0;
var windowHeight = 0;
var screenResolutionWidth = 0;
var screenResolutionHeight = 0;

setWindowDimensions();

function validateForm(arrFields) {
	var ret = true;
	for (var i = 0; i < arrFields.length; i++) {
		var field = arrFields[i];
		//var value = hasValue(field);

		var fld = document.getElementById(field.id);
		
		if (fld) {
			//alert(fld);
			//alert(field.id);
			var valid = true;
			var checkValidator = false;
			var fieldValue = getFieldValue(fld);
			
			if (field.required == true) {
				valid = requiredValidation(fieldValue);
				
				if( valid == true ) {
					checkValidator = true;
				}
			}
			else if (fieldValue != '') {
				checkValidator = true;
			}

			// Check further validation
			if (checkValidator == true) {
				//alert(field.validator);

				if (field.validation && field.validation.validator) {

					if (field.validation.params) {
						valid = field.validation.validator(fieldValue, field.validation.params);
					}
					else {
						valid = field.validation.validator(fieldValue);
					}
				}
			}

			if (valid == false) {
				ret = false;

				if (field.errormessage == undefined) {
					setFormFieldInError(field.id);
				}
				else {
					setFormFieldInError(field.id, field.errormessage);
				}
			}
			else {
				resetFormFieldInError(field.id);
			}
		}
	}

	return ret;
}


function getFieldValue(fld) {
	var ret = "";
	if (fld) {
		switch (fld.type.toLowerCase()) {
			case "checkbox":
				var checkBoxes = document.forms[0].elements[fld.name];
				if (checkBoxes.length == undefined) {
					if (checkBoxes.checked) {
						if (checkBoxes.value != undefined && checkBoxes.value != "") {
							ret = checkBoxes.value;
						}
						else {
							ret = "on";
						}
					}
				}
				else {
					var checkValues = "";
					for (var c = 0; c < checkBoxes.length; c++) {
						if (checkBoxes[c].checked) {

							if (checkValues != "") {
								checkValues += ",";
							}

							checkValues += checkBoxes[c].value;
						}
					}

					ret = checkValues;
				}

				break;

			case "radio":
				var radioButtons = document.forms[0].elements[fld.name];

				if (radioButtons) {
					if (radioButtons.length == undefined) {
						if (radioButtons.checked) {
							ret = radioButtons.value;
						}
					}
					else {
						for (var r = 0; r < radioButtons.length; r++) {
							if (radioButtons[r].checked) {
								ret = radioButtons[r].value;
								break;
							}
						}
					}
				}

				break;

			default:
				if (fld.value != undefined) {
					ret += fld.value;
				}
				break;
		}
	}

	return ret;
}

function gatherPostParams(arrFields) {
	var ret = "";
	for (var i = 0; i < arrFields.length; i++) {
		var field = arrFields[i];

		if (i > 0) {
			ret += "&";
		}

		ret += field.id + "=";

		var fld = document.getElementById(field.id);
		if (fld) {
			switch(fld.type.toLowerCase()) {

				case "checkbox":
					var checkBoxes = document.forms[0].elements[fld.name];
					if (checkBoxes.length == undefined) {
						if (checkBoxes.checked) {
							if (checkBoxes.value != undefined && checkBoxes.value != "") {
								ret += encodeURIComponent(checkBoxes.value);
							}
							else {
								ret += "on";
							}
						}
					}
					else {
						var checkValues = "";
						for (var c = 0; c < checkBoxes.length; c++) {
							if (checkBoxes[c].checked) {

								if (checkValues != "") {
									checkValues += ",";
								}

								checkValues += encodeURIComponent(checkBoxes[c].value);
							}
						}

						ret += checkValues;
					}

					break;

				case "radio":
					var radioButtons = document.forms[0].elements[fld.name];

					if (radioButtons) {
						if (radioButtons.length == undefined) {
							if (radioButtons.checked) {
								ret += encodeURIComponent(radioButtons.value);
							}
						}
						else {
							for (var r = 0; r < radioButtons.length; r++) {
								if (radioButtons[r].checked) {
									ret += encodeURIComponent(radioButtons[r].value);
									break;
								}
							}
						}
					}

					break;

				default:
					if (fld.value != undefined) {
						ret += encodeURIComponent(fld.value);
					}
					break;

				
			}
			
		}
	}

	return ret;
}


function requiredValidation(value) {
	var valid = ( value != "" && value != undefined && value != null );
	return valid;
}

function matchValidation(value, params) {
	var ret = false;
	if (params != undefined) {
		if (params.id != undefined) {
			var otherForm = document.getElementById(params.id);
			if (otherForm) {
				var otherFormValue = getFieldValue(otherForm);
				if (otherFormValue != "" && otherFormValue == value) {
					ret = true;
				}
			}
		}
	}
	return ret;
}

function minValidation(value, params) {
	var ret = false;

	//( value >= param[0] && value <= param[1] );
	
	if( params != undefined ) {
		if( params.min != undefined ) {
			if( value >= params.min ) {
				ret = true;
			}
		}
	}

	return ret;

}

function maxValidation(value, params) {
	var ret = false;

	//( value >= param[0] && value <= param[1] );

	if (params != undefined) {
		if (params.max != undefined) {
			if (value <= params.max) {
				ret = true;
			}
		}
	}

	return ret;

}

function rangeValidation(value, params) {
	var ret = false;

	//( value >= param[0] && value <= param[1] );

	if (params != undefined) {
		if (params.min != undefined && params.max != undefined) {
			if (value >= params.min && value <= params.max) {
				ret = true;
			}
		}
	}

	return ret;

}

function numbersOnlyValidation(value) {
	return /^-?(?:\d+|\d{1,3}(?:,\d{3})+)(?:\.\d+)?$/.test(value);
}

function emailValidation(value) {
	return /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i.test(value);
}

function phoneValidation(value) {
	return /^((\+\d{1,3}(-| )?\(?\d\)?(-| )?\d{1,5})|(\(?\d{2,6}\)?))(-| )?(\d{3,4})(-| )?(\d{4})(( x| ext)\d{1,5}){0,1}$/i.test(value);
}

function testPattern (value, pattern) { 

	var regExp = new RegExp(pattern, "");
	return regExp.test(value);
}

function setFormFieldInError(id) {
	setFormFieldInError(id, "");
}

function setFormFieldInError(id, msg) {
	setFormFieldInError(id, msg, true);
}

function setFormFieldInError(id, msg, doSetFocus) {
	//alert(id);
	var divFormElement = document.getElementById(id);

	if (divFormElement) {

		if (doSetFocus == true || doSetFocus == undefined) {
			divFormElement.focus();
		}

		setFormElementToError(divFormElement, msg);

		switch (divFormElement.type.toLowerCase()) {
			case "radio":
			case "checkbox":
				var i = 1;

				var checkedDiv = document.getElementById(id + i.toString());

				while (checkedDiv) {
					setFormElementToError(checkedDiv);

					i++;
					checkedDiv = document.getElementById(id + i.toString());

				}

				break;
		}

	}
}

function setFormElementToError(divFormElement, msg) {
	addOrSetElementCssClass(divFormElement, "inputerror");
	addOrSetElementCssClass(document.getElementById(divFormElement.id + "_row"), "rowerror");
	addOrSetElementCssClass(document.getElementById(divFormElement.id + "_star"), "starerror");

	if (msg != undefined && msg != null && msg != "") {
		openDiv(divFormElement.id + "_message", msg);
	}
}

function addOrSetElementCssClass(element, className) {
	if (element) {
		if (element.className == "") {
			element.className = className;
		}
		else {
			// DO NOT ADD AGAIN
			if (element.className.indexOf(className) < 0) {
				element.className += " " + className;
			}
		}
	}
}

function removeElementCssClass(element, className) {
	if (element) {
		if (element.className == className) {
			element.className = "";
		}
		else {
			element.className = element.className.replace(" " + className, "");
		}
	}
}

function resetFormElementFromError(divFormElement) {
	removeElementCssClass(divFormElement, "inputerror");
	removeElementCssClass(document.getElementById(divFormElement.id + "_row"), "rowerror");
	removeElementCssClass(document.getElementById(divFormElement.id + "_star"), "starerror");
	closeDiv(divFormElement.id + "_message");
}

function resetFormFieldInError(id) {

	var divFormElement = document.getElementById(id);

	if (divFormElement) {

		resetFormElementFromError(divFormElement);

		switch (divFormElement.type.toLowerCase()) {
			case "radio":
			case "checkbox":
				var i = 1;

				var checkedDiv = document.getElementById(id + i.toString());

				while (checkedDiv) {
					resetFormElementFromError(checkedDiv);

					i++;
					checkedDiv = document.getElementById(id + i.toString());

				}

				break;
		}

	}
}



function doSleep(func, ms) {
	window.setTimeout(func, ms);
}

function openPopupAndRefreshParentWhenClosed(url, name, options) {
	if (popup) {
		popup.close();
		popup = null;
	}

	setWindowDimensions();

	// Parse Width
	var reg = /width\=(\d+)/gi;

	options.match(reg);
	windowWidth = RegExp.$1;

	// Center
	var leftPos = (window.screen.width - windowWidth) / 2;
	var topPos = (window.screen.height - windowHeight) / 2;

	// Remove Hash
	window.location.hash = "";
	urlToRefreshTo = window.location.href.replace('#', "");

	//alert(urlToRefreshTo);
	
	
	//alert(urlToRefreshTo);
	popup = window.open(url, name, options + ",height=" + windowHeight + ",top=" + topPos + ",left=" + leftPos);
	//popup = window.open(url, name, options + ",top=" + topPos + ",left=" + leftPos);

	doSleep("refreshParentOfPopupOrWait()", 100);
}

function openPopupAndRefreshToUrlWhenClosed(url, refreshUrl, name, options) {
	if (popup) {
		popup.close();
		popup = null;
	}
	
	setWindowDimensions();
	
	// Parse Width
	var reg = /width\=(\d+)/gi;

	options.match(reg);
	windowWidth = RegExp.$1;
	
	// Center
	var leftPos = (window.screen.width - windowWidth) / 2;
	var topPos = (window.screen.height - windowHeight) / 2;


	urlToRefreshTo = refreshUrl;
	popup = window.open(url, name, options + ",height=" + windowHeight+",top=" + topPos + ",left=" + leftPos);
	//popup = window.open(url, name, options + ",top=" + topPos + ",left=" + leftPos);

	doSleep("refreshToUrlOrWait()", 100);
}

function refreshToUrlOrWait() {
	if (popup) {
		if (!popup.closed) {
			doSleep("refreshToUrlOrWait()", 100);
		}
		else {
			popup = null;
			// Refresh this page to view changes
			window.location.href = urlToRefreshTo;
		}
	}
}

function refreshParentOfPopupOrWait() {
	if (popup) {
		if (!popup.closed) {
			doSleep("refreshParentOfPopupOrWait()", 100);
		}
		else {
			popup = null;
			// Refresh this page to view changes
			//alert("refreshParentOfPopupOrWait()\r\n\r\n" + urlToRefreshTo);

			if (window.location.reload) {
				window.location.reload(false);
			}
			else {
				window.location.href = urlToRefreshTo; // Without HASH
			}
			
		}
	}
}

function setWindowDimensions() {

	if (typeof (window.innerWidth) == 'number') {
		//Non-IE
		windowWidth = window.innerWidth;
		windowHeight = window.innerHeight;
	} else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
		//IE 6+ in 'standards compliant mode'
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body && (document.body.clientWidth || document.body.clientHeight)) {
		//IE 4 compatible
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}

	screenResolutionWidth = window.screen.width;
	screenResolutionHeight = window.screen.height;
}

function toggleDiv(id) {
	var div = document.getElementById(id);

	if (div) {
		div.style.display = ( ( div.style.display == "none" ) ? "block" : "none");
	}
}

function openDiv(id) {
	openDiv(id, null);
}

function openDiv(id, html) {
	var div = document.getElementById(id);

	if (div) {
		div.style.display = "block";
		if (html != null) {
			div.innerHTML = html;
		}
		
	}
}

function closeDiv(id) {
	var div = document.getElementById(id);

	if (div) {
		div.style.display = "none";
	}
}

function opendiv(id) {  
for (i=1;i<=4;i++) { // so you can add more than 2  
var divname = 'div'+i;  
var divStyle = document.getElementById(divname).style;  
divStyle.display=(id==divname)?'block':'none';  
} 
} 

function swapTextForDefault(textBox, defaultValue)
{
	if( textBox.value == "" )
	{
		textBox.value = defaultValue;
	}
}

function removeTextDefault(textBox, defaultValue)
{
	
	if( textBox.value == defaultValue )
	{
		textBox.value = "";
	}
}

function openPopup(url, name, options) {
	
	var popup = window.open(url, name, options);

	return popup;
}

function toggleSelect(check, chks)
{
	//alert(check.checked);

	if( chks != undefined )
	{
		if( chks.length != undefined )
		{
			for( var i = 0; i < chks.length; i++ )
			{
				chks[i].checked = check.checked;
			}
		}
		else
		{
			chks.checked = check.checked;
		}
	}
}

function checkChecks(chks, checked) 
{
	//alert("checkChecks");
	if (chks != undefined) 
	{
		//alert(chks.length);
		if( chks.length != undefined )
		{
			for( var i = 0; i < chks.length; i++ )
			{
				chks[i].checked = checked;
			}
		}
		else
		{
			chks.checked = checked;
		}
	}
}

function toggleSelectedOptions(select, selected) 
{
	if (select.options != undefined && select.length != undefined) 
	{
		for (var i = 0; i < select.length; i++) 
		{
			select.options[i].selected = selected;
		}
	}	
}

function changeQuantity(textBoxId, booleanUp)
{
	var textDiv = document.getElementById(textBoxId);
	
	if( textDiv )
	{
		if( booleanUp )
		{
			textDiv.value++;
		}
		else
		{
			if( textDiv.value > 0 )
			{
				textDiv.value--;
				
				if( textDiv.value == 0 )
				{
					textDiv.value = "";
				}
			}
		}
	}
}

function confirmAction(ask) 
{
	return confirm(ask);
}

function set_cookie ( name, value, exp_y, exp_m, exp_d, path, domain, secure )
{
	var cookie_string = name + "=" + escape ( value );

	if ( exp_y )
	{
		var expires = new Date ( exp_y, exp_m, exp_d );
		cookie_string += "; expires=" + expires.toGMTString();
	}

	if ( path )
		cookie_string += "; path=" + escape ( path );

	if ( domain )
		cookie_string += "; domain=" + escape ( domain );

	if ( secure )
		cookie_string += "; secure";

	document.cookie = cookie_string;
}

function delete_cookie ( cookie_name )
{
	var cookie_date = new Date ( );  // current date & time
	cookie_date.setTime ( cookie_date.getTime() - 1 );
	document.cookie = cookie_name += "=; expires=" + cookie_date.toGMTString();
}


function get_cookie ( cookie_name )
{
	var results = document.cookie.match ( '(^|;) ?' + cookie_name + '=([^;]*)(;|$)' );

	if ( results )
		return ( unescape ( results[2] ) );
	else
		return null;
}

function setSelectedToValue(lstBoxId, theValue)
{
	
    var listBox = document.getElementById(lstBoxId);
    if( listBox )
    {
        if( listBox.length != undefined )
        {
            for( i = 0; i < listBox.length; i++ )
            {
                if( listBox[i].value == theValue )
                {
                    listBox[i].selected = true;
                    break;
                }
            }
        }
    }
}

function clearDropDown(id)
{
    var dropDown = document.getElementById(id);
    if( dropDown )
    {
        var numberOfOptions = dropDown.length;
        if( numberOfOptions > 0 )
        {
            for( i = 0; i < numberOfOptions; i++ )
            {
                dropDown.remove(0); // 0 and NOT i as removing the first element makes the next one 0 (zero).
            }
        }
    }   
}

function appendOption(dropDown, ddOption)
{
    try
    {
        dropDown.add(ddOption, null);
    }
    catch(ex) // IE Only
    {
        dropDown.add(ddOption);
    }

}

