//----------------------------------------------
// This library of JS functions are used throughout the application
// for general functions that should be shared
//----------------------------------------------

//Fix for IE6 and below not using AJAX as native object
if (!window.XMLHttpRequest) {
	window.XMLHttpRequest = function() { return new ActiveXObject('Microsoft.XMLHTTP') }
}

//Prebuilt trim function
String.prototype.trim = function () {
    return this.replace(/^\s*/, "").replace(/\s*$/, "");
}

//This function will add a field tip in the field
function fieldHelper(id,value) {
	//Find out which element
	fldId             = document.getElementById(id);
	fldId.value       = value;       //The default value
	fldId.style.color = '#999999';   //A grey color
	fldId.onfocus     = function() {this.value='';this.style.color='#000';this.onfocus = null;}  //A script to undo when it gets focus
}

function disableObj(tmp_obj_id,tmpState) {
	//Get the DOM ID and hide it's display attribute
	tmp_obj = document.getElementById(tmp_obj_id);
	tmp_obj.disabled=tmpState;		
}

function setIndexObj(tmp_obj_id,tmpIndex) {
	//Get the DOM ID and hide it's display attribute
	tmp_obj = document.getElementById(tmp_obj_id);
	tmp_obj.selectedIndex=tmpIndex;		
}

function hideObj(tmp_obj_id) {
	//Get the DOM ID and hide it's display attribute
	tmp_obj = document.getElementById(tmp_obj_id);
	tmp_obj.style.display = "none";
}

function showObj(tmp_obj_id) {
	//Get the DOM ID and show it's display attribute
	tmp_obj = document.getElementById(tmp_obj_id);
	tmp_obj.style.display = "";
}

function fixWindowSize() {
	win.updateHeight();
	win.updateWidth();
}

function makeWaitingWindow(msg) {
	if (!msg) { msg = 'Please wait...processing'; }
	popupWindow("waiting","","html","<center><br><br>"+msg+"<br><br><img src='images/bar_loading.gif'><br><br></center>",350,110,'y');
}

function makeConfirmWindow(tmpMsg,tmpTitle,yesFunction,noFunction) {
	popupWindow("confirm",tmpTitle,"html","<br><center>"+tmpMsg+"<br /><br><img src='images/btn_yes.jpg' style='cursor:pointer' onclick='"+yesFunction+"'  /><img src='images/btn_no.jpg'  style='cursor:pointer' onclick='"+noFunction+"'/></center><br>",350,110,'y');
}

function popupWindow(tmpName,tmpTitle,tmpType,tmpCode,tmpWidth,tmpHeight) {
	tmpName = tmpName + Math.random();
	Windows.closeAll();
	win = new Window({id: tmpName, className: "greylighting", title: tmpTitle, width: tmpWidth, height: tmpHeight, destroyOnClose: true, recenterAuto:false, resizable: true, minimizable: false, maximizable: false, maxHeight: 700});
	win.setZIndex(999);
	//Determine if this is a URL or Static code to show
	if (tmpType == "url") {
		win.setAjaxContent(tmpCode, "", true, false)
	} else {
		win.setHTMLContent(tmpCode);
		win.showCenter();
		win.updateWidth();
		win.updateHeight();
	}
	return win;
}

function disable_fields(form_id) {
	f      = document.getElementById(form_id);
	inputs = f.getElementsByTagName("input");
	for (i=0; i<inputs.length; i++) {
		inputs[i].disabled = true;
	}
}

//Gets the checked value of a radio button control
function getRadioValue(formObj) {
	radioObj = document.getElementsByName(formObj);
	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 "";
}

function getCheckboxValue(formObj) {
	tmpCheck = document.getElementById(formObj);
	if (tmpCheck.checked) {
		return tmpCheck.value;
	} else {
		return "";
	}
}

//Gets the value of select/combo boxes
function getSelectedValue(field_id) {
	tmpIdx = document.getElementById(field_id).selectedIndex;
	tmpVal = document.getElementById(field_id)[tmpIdx].value;	
	return tmpVal;
}

function getSelectedText(field_id) {
	tmpIdx = document.getElementById(field_id).selectedIndex;
	tmpVal = document.getElementById(field_id)[tmpIdx].text;	
	return tmpVal;
}

function setSelectedIndex(field_id,idx) {
	document.getElementById(field_id).selectedIndex = idx;
}

//Sets value of text box
function setValue(field_id, tmpValue) {
	tmpObjSet = document.getElementById(field_id);
	tmpObjSet.value = tmpValue;
}

//Gets value of text box
function getValue(field_id) {
	tmpObjGet = document.getElementById(field_id);
	return tmpObjGet.value;
}

//Sets innerHTML of a HTML element
function setInnerHTML(dom_id,dom_value) {
	tmpObj = document.getElementById(dom_id);
	tmpObj.innerHTML = dom_value;
}

function ajaxCall(ajaxPage,sendType,sendParms,rtnFunction) {
	//Deal with the IE vs Firefox issues
	var xmlhttp = false;
	try {
		xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
	} catch (e) {
		try {
			xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
		} catch (E) {
			xmlhttp = false;
		}
	}
	
	if (!xmlhttp && typeof XMLHttpRequest != 'undefinded') { xmlhttp = new XMLHttpRequest(); }
	
	//Figure out if this is a POST or GET	
	if (sendType == "post" || sendType == "POST") {		
		//Define the AJAX call's parms
		xmlhttp.open("POST", ajaxPage, true);
		xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		xmlhttp.setRequestHeader("Content-length", sendParms.length);
		xmlhttp.setRequestHeader("Connection", "close");
		xmlhttp.send(sendParms);	
	} else {
		xmlhttp.open("GET",ajaxPage);
		xmlhttp.send(null);
	}	
	
	//Define what to do with a response
	xmlhttp.onreadystatechange = function() {
		if (xmlhttp.readyState == 4) {
			
			//Call the return function 
			if (rtnFunction != "") {
				
				//if return function doesn't have "("  then append the response text, otherwise accept the function as is
				tmpVar   = rtnFunction.replace("(","XX");
				tmpDelta = tmpVar.length-rtnFunction.length;
				if (tmpDelta == 0) { rtnFunction = rtnFunction + "(xmlhttp.responseText)"; }
	
				eval(rtnFunction);
			}
		}
	}

}

function objFocus(tmpId) {
	tmpObjFocus = document.getElementById(tmpId);
	tmpObjFocus.focus();
}

function setCookie(c_name,value,expiredays) {
	var exdate=new Date();exdate.setDate(exdate.getDate()+expiredays);
	document.cookie=c_name+ "=" +escape(value)+((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
} 

function getCookie(c_name) {
	if (document.cookie.length>0) {
	  c_start=document.cookie.indexOf(c_name + "=");
	  if (c_start!=-1){ 
		c_start=c_start + c_name.length+1; 
		c_end=document.cookie.indexOf(";",c_start);
		if (c_end==-1) c_end=document.cookie.length;
		return unescape(document.cookie.substring(c_start,c_end));
		} 
	  }
	return "";
}

function errorField(id,tmpState) {
	tmpObj1 = document.getElementById(id);
	if (tmpState==1) {
		tmpObj1.className="formFieldsError";
	} else {
		tmpObj1.className="formFields";
	}
}

function errorFields(objStr) {
	objList = objStr.split("|");
	for (i=0;i<objList.length;i++) {
		tmpObj2 = document.getElementById(objList[i]);
		tmpObj2.className = "errorBox";
	}
}

function requiredFields(objStr) {
	objList = objStr.split("|");
    for (i=0;i<objList.length;i++) {
        tmpObj3 = document.getElementById(objList[i]);
        tmpObj3.className = "formFieldsRequired";
    }
} 

function refreshPage() {
	document.location = document.location;	
}

function addCart(item_id,result) {
	if (result == "") {
		ajaxCall("ajax_cart_add.php?item_id="+item_id,"get","","alert");
	} else {
		ajaxCall("ajax_cart_add.php?item_id="+item_id,"get","","document.location='cart.php';");
	}
}

function updateCart(item_id,qty) {
	ajaxCall("ajax_cart_add.php?qty="+qty+"&item_id="+item_id,"get","","document.location=document.location;")	
}

function updateTotal() {
	total = getValue('hidSub');
	state = getSelectedValue('ship_state');
	ship  = parseFloat(getSelectedValue('shipping_cost'));
	setValue('order_shipping_method',getSelectedText('shipping_cost'));
	if (state == "CA") { pct = 7.25; } else { pct = 0; }
	tax   = Math.round(((pct/100) * total) * 100)/100;
	total = parseFloat(total) + parseFloat(tax) + parseFloat(ship);
	ship  = formatCurrency(ship);
	tax   = formatCurrency(tax);
	total = formatCurrency(total);
	setInnerHTML('ttl_ship',ship);
	setInnerHTML('ttl_tax',tax);
	setInnerHTML('ttl_total',total);
}

function formatCurrency(num) {
	num = num.toString().replace(/\$|\,/g,'');
	if(isNaN(num))
	num = "0";
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*100+0.50000000001);
	cents = num%100;
	num = Math.floor(num/100).toString();
	if(cents<10)
	cents = "0" + cents;
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
	num = num.substring(0,num.length-(4*i+3))+','+
	num.substring(num.length-(4*i+3));
	return (((sign)?'':'-') + '$' + num + '.' + cents);
}
