var firstPassOnEnter = null;
var tbArray = new Array();
var isIE = (navigator.appName.indexOf("Internet Explorer")>=0);
var isFF = (navigator.appName.indexOf("Netscape")>=0);
var isSafari = (navigator.appVersion.indexOf("Safari")>=0);
//alert(isSafari);

window.onload = function(){
	isIE = (navigator.appName.indexOf("Internet Explorer")>=0);
	isFF = (navigator.appName.indexOf("Netscape")>=0);
	isSafari = (navigator.appVersion.indexOf("Safari")>=0);
	
	/// Fixes the flash activation problem
	objects = document.getElementsByTagName("object");
	for (var i = 0; i < objects.length; i++){
		objects[i].outerHTML = objects[i].outerHTML;
	}
	
	/// Sets input parameter actions
	objects = document.getElementsByTagName("input");
	var j = 0;
	for (var i = 0; i < objects.length; i++){
		if(objects[i].type == "text"){
			tbArray[j++] = objects[i]; 
		}
	}
	
	for (var i = 0; i < tbArray.length; i++){
		if(isSafari) {
			tbArray[(tbArray.length - 1) - i].onkeyup = doEnterFF;
			tbArray[(tbArray.length - 1) - i].arrayID = i;
			continue;
		}
		/// makes sure the inputs value is numeric
		if(tbArray[i].attributes["numeric"] != null && tbArray[i].attributes["numeric"].value == "true"){
			if (isIE || isSafari){ tbArray[i].onkeypress = event57IE; }
			if (!isIE){ tbArray[i].onkeypress = event57FF; }
		}
		if(tbArray[i].attributes["alpha"] != null && tbArray[i].attributes["alpha"].value == "true"){
			if (isIE || isSafari){ tbArray[i].onkeypress = event5748IE; }
			if (!isIE){ tbArray[i].onkeypress = event5748FF; }
		}
		
		/// allows the enter key to jump to the next field
		if(tbArray[(tbArray.length - 1) - i].attributes["alpha"] != null ||
				tbArray[(tbArray.length - 1) - i].attributes["passonenter"].value == "true"){
			if(firstPassOnEnter == null){
				firstPassOnEnter = i;
			}
			tbArray[(tbArray.length - 1) - i].arrayID = i;
			if (isIE){
				tbArray[(tbArray.length - 1) - i].onkeypress = disableEnterIE;
				tbArray[(tbArray.length - 1) - i].onkeyup = doEnterIE;
			} else {
				tbArray[(tbArray.length - 1) - i].onkeypress = disableEnterFF;
				tbArray[(tbArray.length - 1) - i].onkeyup = doEnterFF;
			}
		}
	}
	
}
function event57IE() {
	if (event.keyCode > 57){
		event.returnValue = false;
	}
}
function event57FF(event) {
	if (event.keyCode > 57){
		event.returnValue = false;
	}
}
function event5748IE() {
	if (event.keyCode <= 57 && event.keyCode >= 48){
		event.returnValue = false;
	}
}
function event5748FF(event) {
	if (event.keyCode <= 57 && event.keyCode >= 48){
		event.returnValue = false;
	}
}
function disableEnterIE() {
	if(event.keyCode == 13){
		return false;
	}
}
function disableEnterFF(event) {
	if(event.keyCode == 13){
		return false;
	}
}
function doEnterIE(){
	if(event.keyCode == 13){
		if(tbArray[tbArray.length - this.arrayID]){
			tbArray[tbArray.length - this.arrayID].focus();
		}else{
			tbArray[firstPassOnEnter].blur();
			tbArray[firstPassOnEnter].focus();
		}				
		
	} else if(event.keyCode == 38 && 
			tbArray[tbArray.length - this.arrayID - 2] != null &&
			tbArray[tbArray.length - this.arrayID - 2].attributes["passonenter"].value == "true"){ //up
		tbArray[tbArray.length - this.arrayID - 2].focus();
		
	} else if(event.keyCode == 40){ //down
		if(tbArray[tbArray.length - this.arrayID]){
			tbArray[tbArray.length - this.arrayID].focus();
		}else{
			tbArray[firstPassOnEnter].blur();
			tbArray[firstPassOnEnter].focus();
		}
	}
}
function doEnterFF(event){
	if(event.keyCode == 13){
		if(tbArray[tbArray.length - this.arrayID]){
			tbArray[tbArray.length - this.arrayID].focus();
		}else{
			tbArray[firstPassOnEnter].blur();
			tbArray[firstPassOnEnter].focus();
		}				
		
	} else if(event.keyCode == 38 && tbArray[tbArray.length - this.arrayID - 2] != null && tbArray[tbArray.length - this.arrayID - 2].attributes["passonenter"].value == "true"){ //up
		tbArray[tbArray.length - this.arrayID - 2].focus();
		
	} else if(event.keyCode == 40){ //down
		if(tbArray[tbArray.length - this.arrayID]) {
			tbArray[tbArray.length - this.arrayID].focus();
		} else {
			tbArray[firstPassOnEnter].blur();
			tbArray[firstPassOnEnter].focus();
		}
	}
}


/// Disable Right Click

var message="We're sorry, but the right click option has been disabled";
function clickIE4(){ if (event.button==2){alert(message); return false; } }
function clickNS4(e){ if (document.layers||document.getElementById&&!document.all){ if (e.which==2||e.which==3){ alert(message); return false; } } }
if (isFF/*document.layers*/){
	//isFF = true; isIE = false;
	document.captureEvents(Event.MOUSEDOWN);
	document.onmousedown=clickNS4;
} else if (isIE/*document.all && !document.getElementById*/){
	//isIE = true; isFF = false;
	document.onmousedown=clickIE4;
}
document.oncontextmenu=new Function("alert(message);return false") 


/// Gets the page element by its id
function getObject(name){
	return document.getElementById(name);
}

/// Gets the page element's value by its id
function getValue(name){
	return getObject(name).value;
}

// Builds the mandatory message
function AddToMandatoryMessage(msg, name){
	if(msg == ""){
		msg = "The following fields are mandatory:\n";
	}
	msg += "  - " + name + "\n";
	return msg;
}

/// Checks if a field is blank
function ValidateNotBlank(name){
	return (getValue(name) == "");	
}

function ValidateValueLength(name, size){
	return (getValue(name).length < size);
}

function ValidateNumericValue(name){
	return isNaN(getValue(name));
}

/// Checks if a field has a valid email address
function ValidateEmail(name){
	var emailReg = "^[\\w-_\.]*[\\w-_\.]\@[\\w]\.+[\\w]+[\\w]$";
	var regex = new RegExp(emailReg);
	return regex.test(getValue(name));
}

function getCheckedValue(radioObj) {
	if(!radioObj)
		return "";
	var radioLength = radioObj.length;
	if(radioLength == undefined)
		if(radioObj.checked)
			return radioObj.value;
		else
			return "";
	for(var i = 0; i < radioLength; i++) {
		if(radioObj[i].checked) {
			return radioObj[i].value;
		}
	}
	return "";
}

/// Form validator object
function FormValidator(){
	msg = "";
	valid = true;
	
	this.Valid = function(){
		return valid;
	}
	
	this.CheckTextField = function(labelName, fieldName, displayName){
		ResetStyle(fieldName);
		ResetStyle(labelName);
		if(ValidateNotBlank(fieldName)){
			NotValid(labelName, displayName);
		}
	}
	
	this.CheckEmail = function(labelName, fieldName, displayName){
		ResetStyle(fieldName);
		ResetStyle(labelName);
		if(!ValidateEmail(fieldName)){
			NotValid(labelName, displayName);
		}
	}
	
	this.CheckNumeric = function(labelName, fieldName, displayName){
		ResetStyle(fieldName);
		ResetStyle(labelName);
		if(ValidateNotBlank(fieldName) || ValidateNumericValue(fieldName)){
			NotValid(labelName, displayName);
		}
	}
	
	this.CheckRange = function(fieldName, displayName, from, to){
		ResetStyle(fieldName);
		if(ValidateNumericValue(fieldName) && !(getValue(fieldName) >= from && getValue(fieldName) <= to)){
			NotValid(fieldName, displayName);
		}
	}
	
	this.ValidateNumericLength = function(labelName, fieldName, displayName, size){
		ResetStyle(fieldName);
		ResetStyle(labelName);
		if(ValidateValueLength(fieldName, size) || ValidateNotBlank(fieldName) || ValidateNumericValue(fieldName)){
			NotValid(labelName, displayName);
		}
	}
	
	function ResetStyle(fieldName){
		var myObj = getObject(fieldName);
		if (myObj != null) {
			myObj.style.backgroundColor = "";
			myObj.style.color = "";
		}
	}
	
	function NotValid(fieldName, displayName){
		valid = false;
		//getObject(fieldName).style.backgroundColor = "red";
		//getObject(fieldName).style.color = "white";
		getObject(fieldName).style.color = "red";
		var tmp = displayName ? displayName : fieldName;
		msg = AddToMandatoryMessage(msg, tmp);
	}
	
	this.ShowAlert = function(){
		if(!valid){
			alert(msg);
		}
	}
}

/// Add Events to objects
function addEventListener( element, event_name, observer, capturing ) {
    if ( element.addEventListener )  // the DOM2, W3C way
        element.addEventListener( event_name, observer, capturing );
    else if ( element.attachEvent )  // the IE way
        element.attachEvent( "on" + event_name, observer );
}

function CreateXMLHTTP(){
	var xmlhttp = false;
	/*@cc_on @*/
	/*@if (@_jscript_version >= 5)
	// JScript gives us Conditional compilation, we can cope with old IE versions.
	// and security blocked creation of the objects.
	try {
		xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
	} catch (e) {
		try {
			xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
		} catch (E) {
			xmlhttp = false;
		}
	}
	@end @*/
	
	if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
		try {
			xmlhttp = new XMLHttpRequest();
		} catch (e) {
			xmlhttp = false;
		}
	}
	if (!xmlhttp && window.createRequest) {
		try {
			xmlhttp = window.createRequest();
		} catch (e) {
			xmlhttp = false;
		}
	}
	
	if(!xmlhttp){
		alert("Problem loading Http request object");
	}
	
	return xmlhttp;
}

function GetHTML(url){
	xmlhttp = CreateXMLHTTP();
	xmlhttp.open("GET", url, false);
	xmlhttp.send(null);
	return xmlhttp.responseText;
}

/// Create Http request object
function HTTPConnection(method, url, complete){
	var xmlhttp = CreateXMLHTTP();
	//response = "N/A";	
	
	xmlhttp.open(method, url, !isSafari);
	xmlhttp.onreadystatechange = function() {
		if (xmlhttp.readyState == 4) {
			switch (xmlhttp.status){
				case 200: // All OK
					//alert("AOK");
					if(complete != null){
						complete();
					}
					//response = xmlhttp.responseText;
					break;
				case 404: // URL not found
					alert("\"" + url + "\" Not found");
					break;
				/*case 500: // Server error
					break;*/
				default: // Any other status
					alert("Problem [" + xmlhttp.status + "] loading \"" + url + "\"");
					//getObject("ShoppingCartFrame").innerHTML = xmlhttp.responseText;
					
					break;
			}
		}
	}
	
	//this.ResponseTxt = function(){
	//	return response;
	//}
	
	this.Execute = function(){
		xmlhttp.send(null);
	}
}

/// Validate the text boxes value and sets it to the closest value allowed
function ValidateValue(obj, multiplication){
	var origValue = parseInt(obj.value);
	var newValue = origValue;
	
	if(isNaN(obj.value) || trim(obj.value) == ""){
		obj.value = "";
		return;
	}
	
	if((origValue % multiplication) > 0){
		if (origValue < multiplication){
			newValue = multiplication;
		}else{
			newValue = origValue - (origValue % multiplication) + multiplication;
		}
		alert("This should be a multiple of " + multiplication + " and will be rounded up to " + newValue);
	}
	
	obj.value = newValue;
}

var lastMarkedRow;
function RowHover(obj){
	if(lastMarkedRow){
		lastMarkedRow.style.backgroundColor = "";
	}
	if(obj.style.backgroundColor == "#d8edc9")
		obj.style.backgroundColor = "";
	else
		obj.style.backgroundColor = "#d8edc9";
}

function ShowImagePopup(vbn, name, family){
	var t = window.open("../common/imagepopup.asp?vbn=" + vbn + "&name=" + name + "&family=" + family, "ImagePopup","width=300,height=300");
	if(!t){
		alert("Please disable popup blocker");
	}
}

function ShowImagePopup2(vbn, name, family){
	var t = window.open("common/imagepopup.asp?vbn=" + vbn + "&name=" + name + "&family=" + family, "ImagePopup","width=300,height=300");
	if(!t){
		alert("Please disable popup blocker");
	}
}

function ShowAdminImagePopup(vbn, name, family){
	var t = window.open("../common/BackOffice/imagepopup.asp?vbn=" + vbn + "&name=" + name + "&family=" + family, "ImagePopup","width=300,height=340");
	if(!t){
		alert("Please disable popup blocker");
	}
}

function ShowColorLegend(){
	var t = window.open("../common/colorlegend.htm", "ImagePopup","width=300,height=450,resizable=yes,scrollbars=yes");
	if(!t){
		alert("Please disable popup blocker");
	}
}

function SetRow(id, status){
	getObject("CatalogRow" + id).className = status ? "SelectedRow" : "RegularRow";
}

function SetMarkedRow(id, status){
	getObject("CatalogRow" + id).className = status ? "SelectedRow Marked" : "RegularRow Marked";
}

function GeneralConfirm(txt){
	var ltxt = (txt == undefined) ? "Are you sure?" : txt;
	if(!confirm(ltxt)){
		event.returnValue = false;
	}
}

function trim(stringToTrim) {
	return stringToTrim.replace(/^\s+|\s+$/g,"");
}
function ltrim(stringToTrim) {
	return stringToTrim.replace(/^\s+/,"");
}
function rtrim(stringToTrim) {
	return stringToTrim.replace(/\s+$/,"");
}
