/*
logval.js
Validation Script and many other supporting JS functions
CVS $Revision: 1.70 $ $Date: 2011/06/16 16:33:36 $
*/

//fix PNG transparency in IE 5.5 and 6!!!!
function correctPNG() // correctly handle PNG transparency in Win IE 5.5 & 6.
{
	var arVersion = navigator.appVersion.split("MSIE")
	var version = parseFloat(arVersion[1])
	if ((version >= 5.5) && (document.body.filters))
	{
		for(var i=0; i<document.images.length; i++)
		{
			var img = document.images[i]
			var imgName = img.src.toUpperCase()
			if (imgName.substring(imgName.length-3, imgName.length) == "PNG")
			{
				var imgID = (img.id) ? "id='" + img.id + "' " : ""
				var imgClass = (img.className) ? "class='" + img.className + "' " : ""
				var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='" + img.alt + "' "
				var imgStyle = "display:inline-block;" + img.style.cssText
				if (img.align == "left") imgStyle = "float:left;" + imgStyle
				if (img.align == "right") imgStyle = "float:right;" + imgStyle
				if (img.parentElement.href) imgStyle = "cursor:hand;" + imgStyle
				var strNewHTML = "<span " + imgID + imgClass + imgTitle
				+ " style=\"" + "width:" + img.width + "px; height:" + img.height + "px;" + imgStyle + ";"
				+ "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
				+ "(src=\'" + img.src + "\', sizingMethod='scale');\"></span>"
				img.outerHTML = strNewHTML
				i = i-1
			}
		}
	}
}
if (window.attachEvent) {
	window.attachEvent("onload", correctPNG);
}




// JavaScript Document
function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
	 d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}


function MM_validateForm() { //v4.0
	var i,p,q,nm,test,num,min,max,errors='',args=MM_validateForm.arguments;
	
	for (i=0; i<(args.length-2); i+=3) { 
		test=args[i+2]; 
		val=MM_findObj(args[i]);
		if (val) { 
			nm=val.name; 
			desc=args[i+1]; 
			if (""==desc) {
				desc=nm;
			}; 
			if ((val=val.value)!="") {
				if (test.indexOf('isEmail')!=-1) { 
					p=val.indexOf('@');
					if (p<1 || p==(val.length-1)) {
						errors += '- ' + desc + ' must be valid.\n';
					}
				} else if (test!='R') { 
					num = parseFloat(val);
					if (isNaN(val)) errors += '- ' + desc + ' must contain a number.\n';
					if (test.indexOf('inRange') != -1) { 
						p=test.indexOf(':');
						min=test.substring(8,p); 
						max=test.substring(p+1);
						if (num<min || max<num) {
							errors += '- ' + desc + ' must contain a number between ' + min + ' and ' + max + '.\n';
						}
					} 
				} 
			} else if (test.charAt(0) == 'R') {
				errors += '- ' + desc + ' is required.\n';
			}
		}
	}
	if (errors) alert('The following error(s) occurred:\n'+errors);
	document.MM_returnValue = (errors == '');
}



//format display of currency (decimals -- no dollars...)
function decimal2Formatted(amount)
{
	var i = parseFloat(amount);
	var s = "";
	if(isNaN(i)) { i = 0.00; }
	var minus = '';
	if(i < 0) { minus = '-'; }
	i = Math.abs(i);
	i = parseInt((i + 0.005) * 100, 10);
	i = i / 100;
	s = i + ""; //convert i to string
	if(s.indexOf('.') < 0) { s += '.00'; }
	if(s.indexOf('.') === (s.length - 2)) { s += '0'; }
	s = minus + s;
	return s;
}


function disableElement(e) {
	e.disabled = "true";
}



// format display of currency as dollars
function fmtCurrency(strValue)
{
	strValue = strValue.toString().replace(/\$|\,/g,'');
	var dblValue = parseFloat(strValue);

	var blnSign = (dblValue == (dblValue = Math.abs(dblValue)));
	dblValue = Math.floor(dblValue*100+0.50000000001);
	var intCents = dblValue%100;
	var strCents = intCents.toString();
	dblValue = Math.floor(dblValue/100).toString();
	if(intCents<10)
		strCents = "0" + strCents;
	for (var i = 0; i < Math.floor((dblValue.length-(1+i))/3); i++)
		dblValue = dblValue.substring(0,dblValue.length-(4*i+3))+','+
		dblValue.substring(dblValue.length-(4*i+3));
	return (((blnSign)?'':'-') + '$' + dblValue + '.' + strCents);
}


/****** OLD LOGIC
function buildOrderLines(forwardto) {
	var linecount = document.holdorderlines.linecount.value;
	var orderString = "";
	var FD = "\01";
	var LD = "\02";

	if (null == forwardto) {
		forwardto = "";
	}

	//order_notes
	//order_ref
	//order_shipto
	//
	//qty
	//prodid
	//price

	// see if the order reference is available for update
	var order_ref = "";
	if (null != document.info) {
		if (null != document.info.order_ref) {
			order_ref = document.info.order_ref.value;
		}
	}

	orderString = "" + LD + order_ref + LD + "" + LD;
	if (linecount > 0) {
		var qtyval;
		for (var idx = 1; idx <= linecount; idx++) {
			qtyval = eval("document.qtyform" + idx + ".qty" + idx + ".value");
			if (qtyval != "") {
				orderString = orderString + eval("document.qtyform" + idx + ".qty" + idx + ".value") + FD +
				eval("document.qtyform" + idx + ".prodid" + idx + ".value") + FD +
				formatPrice( eval("document.qtyform" + idx + ".price" + idx + ".value") ) + LD;
			}
		}
	}
	orderString = escape(orderString);
	setEnabledById("recalcButton", false);
	window.location = "saveOrder.cfm?orderlines=" + orderString + "&forwardto=" + forwardto;
}
******/


function clicked_addToOrder() {

	//this function gets all page elements and only deals with groupings with 'qty_' as their leading value
	//this was made for the specials page with multiple part listing widgets
	var orderString = "";
	var forwardto = "";
	var FD = "\01";
	var LD = "\02";

	//get every element in page and put it in an array
	var allElements = document.getElementsByTagName("*");

	//order ref is blank by default
	var order_ref = "";

	//start off the orderString
	orderString = "" + LD + order_ref + LD + "" + LD;

	for(idx=0; idx < allElements.length; idx++) {
		var e = allElements[idx];
		//find the proper qty_ value in the list of IDs
		if( 0 <= e.id.indexOf("_qty_") ) {

			//only pay attention to qty_ values that are not null
			if(null != e.value && '' != e.value){

					holdNum = e.id.substring(5,99);
					quant = e.value;
					prodID = "_id_" + holdNum;
					priceID = "_price_" + holdNum;
					prod = document.getElementById(prodID).value;
					price = document.getElementById(priceID).value;
					orderString = orderString + quant + FD + prod + FD + formatPrice(price) + LD;
			}
		}

	}

	orderString = escape(orderString);
	setEnabledById("recalcButton", false);
	window.location = "saveOrder.cfm?orderlines=" + orderString + "&forwardto=" + forwardto;

}



function checkAll(formname) {
	var n;
	for (n=0; n<formname.elements.length; n++) {
		if (formname.elements[n].type === "text") {
			validateText(formname.elements[n].value)
		} else if (formname.elements[n].type === "select-one") {
			validateSelect1(formname.elements[n].selectedIndex)
		} else if (formname.elements[n].type === "select-multiple") {
			validateSelect2(formname.elements[n].selectedIndex)
		}
	}
}



function deleteLine(prodID) {
   if ("" != prodID) {
	  window.location = "deleteFromOrder.cfm?prodID=" + prodID;
   }
}



//functions that enable and disable buttons on order page and warranty page
function disableButton(id) {
	var elements = getElementsById(id);
	for(var idx = 0; idx < elements.length; idx++) {
		elements[idx].className = "button disabledButton";
		elements[idx].disabled = true;
	}
}

function enableButton(id) {
	var elements = getElementsById(id);
	for(var idx = 0; idx < elements.length; idx++) {
		elements[idx].disabled = false;
		elements[idx].className = "button enabledButton";
	}
}



function filterInteger(obj) {
	obj.value = obj.value.replace(/[^0-9]/g,'');
}



function formatPrice(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++) {
		// '' was a comma, but we shouldn't use it
		num = num.substring(0, num.length-(4*i+3)) + '' + num.substring(num.length-(4*i+3));
	}
	// '' was a dollar sign; we shouldn't use it either
	return (((sign)?'':'-') + '' + num + '.' + cents);
}



function IsEmpty(aTextField) {
	if ((aTextField.value.length==0) ||
		(aTextField.value==null)) {
		return true;
	} else {
		return false;
	}
}



function valSearchfields(thisform) {
	if (IsEmpty(thisform.descrip) && IsEmpty(thisform.partno)) {
		alert('Please use at least one of the two search fields!')
		return false;
	 }
	return true;
}



function validateText(numb){
	if (parseInt(numb)=="Nan") {
		alert("this is not an integer value");
		return false;
	}
	return true;
}




	function getElementsByClass(classname) {
		var idx = 0;
		var results = new Array();
		var alltags = document.all ? document.all : document.getElementsByTagName("*");
		// pad classname so indexOf() will find an exact hit
		var classname = " " + classname + " ";
		for (i = 0; i < alltags.length; i++) {
			if (0 <= (" " + alltags[i].className + " ").indexOf(classname)) {
				results[idx++] = alltags[i];
			}
		}
		return results;
	}
	function getElementsById(id) {
		var idx = 0;
		var results = new Array();
		var alltags = document.all ? document.all : document.getElementsByTagName("*");
		for (i = 0; i < alltags.length; i++) {
			 if (alltags[i].id == id) {
				results[idx++] = alltags[i];
			}
		}
		return results;
	}



	function setStyleByClass(classname, property, value) {
		var elements = getElementsByClass(classname);
		for(var idx = 0; idx < elements.length; idx++) {
			elements[idx].style[property] = value;
		}
	}

	function setEnabledById(id, bool) {
		var elements = getElementsById(id);
		for(var idx = 0; idx < elements.length; idx++) {
			elements[idx].disabled = (!bool);
		}
	}

	function setEnabledByClass(classname, bool) {
		var elements = getElementsByClass(classname);
		for(var idx = 0; idx < elements.length; idx++) {
			elements[idx].disabled = (!bool);
		}
	}




// round number to 2 decimals
function roundNumber(value) {
	var rnum = value;
	var rlength = 2; // The number of decimal places to round to
	if (rnum > 8191 && rnum < 10485) {
		rnum = rnum-5000;
		var newnumber = Math.round(rnum*Math.pow(10,rlength))/Math.pow(10,rlength);
		//newnumber = newnumber+5000;
	} else {
		var newnumber = Math.round(rnum*Math.pow(10,rlength))/Math.pow(10,rlength);
	}
	return newnumber;
}



/*
* AJAX FUNCTIONS
*/


function createRequestObject() {
	 var ro;
	 var browser = navigator.appName;
	 if(browser == "Microsoft Internet Explorer"){
		  ro = new ActiveXObject("Microsoft.XMLHTTP");
	 }else{
		  ro = new XMLHttpRequest();
	 }
	 return ro;
}



function saveOrderRef(ref) {
	 http.open('post', 'saveOrderRef.cfm?ref='+ref);
	 http.onreadystatechange = handleResponse;
	 http.send(null);
}



//(HANDLE RESPONSE FOR ORDER PAGE)
function handleResponse() {
	 if(http.readyState == 4){
		  document.info.order_ref.style.backgroundColor = 'white';
	 }
}



function clearDropdown(objSelect){

	  for (var i = (objSelect.options.length-1); i >= 0; i--){
			options[i]=null;
	  }
	  //options[0]=new Option('--------------------------', '0');
}



/*----------------- DELETE ENTIRE ORDER JS -------------------*/
function deleteThisOrder() {
	window.location = "deleteOrder.cfm";
}



function areYouSure(message) {
	var agree = confirm(message);
	if (agree) {
		deleteThisOrder();
		return true ;
	} else {
		return false ;
	}
}



//set order total price display in checkout page
//function recalcCheckoutTotal() {
//			  var shipTot = document.getElementById('order_total').value * 1;
//			  //shipTot = shipTot * 1;
//			  var orderTotVal =	document.getElementById('order_total').value * 1;
//			  document.getElementById('order_total').value = orderTotVal + shipTot;
//}
//set initial order total for checkout page
//function setInitOrderTotal(passedTotal) {
//   var thisOrderTotal = passedTotal;
//		  thisOrderTotal = thisOrderTotal *1;
//
//}




// Dynamic Dropdown List Functions (for Checkout Page)

function addOptions(chosen) {
var selbox = document.myform.opttwo;
if (selbox.options[0].value == " ") {
selbox.options.length = 0;
}
var fnd = 0;
for (n=0;n<selbox.length;n++){
if(selbox.options[n].text == chosen){
fnd = 1;
}}
if (!fnd) selbox.options[selbox.options.length] = new Option(chosen, selbox.options.length);
}



function delOptions(chosen) {
var selbox = document.myform.opttwo;
if (selbox.options[0].value != " ") {
nomatch = new Array();
for (n=0;n<selbox.length;n++){
if(selbox.options[n].text != chosen){
nomatch[nomatch.length] = new Array(selbox.options[n].value, selbox.options[n].text);
}}
selbox.options.length = 0;
if (nomatch.length == 0) {
selbox.options[0]= new Option("Select entries from the list at left"," ");
} else {
for (n=0;n<nomatch.length;n++){
selbox.options[n] = new Option(nomatch[n][1], nomatch[n] [0]);
}}}}



/*
Availability Widget Code Below
*/


//changed function that builds lines for order

function buildOrderLines(forwardto) {
	var linecount = document.holdorderlines.linecount.value;
	var order_notes = "";
	var order_ref = "";
	var order_spclins = "";
	var orderString = "";
	var SM = "\01"; //SUBVALUE MARK" <01>";//
	var VM = "\02"; //VALUE MARK "<02>";//
	var FM = "\03"; //FIELD MARK "<03>";//
	var IM = "\04"; //ITEM MARK "<04>";//

	if (null == forwardto) {
		forwardto = "";
	}

	// see if the order reference is available for update
	if (null != document.info) {
		if (null != document.info.order_ref) {
			order_ref = document.info.order_ref.value;
		}
	}
	if ("" == order_ref) {
		var textbox = document.getElementsByName("order_ref");
		if (1 <= textbox.length) {
			order_ref = textbox[0].value;
		}
	}

	orderString = order_notes + IM + order_ref + IM + order_spclins + IM;
	if (linecount > 0) {
		var qtyval;
		for (var idx = 1; idx <= linecount; idx++) {
			currentProdId = eval("document.qtyform" + idx + ".prodid" + idx + ".value");

			//get array of input objects that hold the WH name and qty val for the current product id
			prodIdQuants = getProdidElements(currentProdId);
			qtyval = eval("document.qtyform" + idx + ".qty" + idx + ".value");

			//qtyval (from the indexed form 'qtyform1,qtyform2, etc.) must have some sort of value to be dealt with
			//this form value is actually the main qty sum displayed on each line!!
			if (qtyval != "") {
				var subDataset = "";
				var ftsw = true;
				for (i = 0; i < prodIdQuants.length; i++) {
					locNameAndProdid = prodIdQuants[i].getAttribute("id").split("_");
					locName = locNameAndProdid[0];
					if (locName != "main" && locName != "defaultFlag") {
						if (!ftsw) { subDataset = subDataset + VM; }
						ftsw = false;
						if (prodIdQuants[i].value < 1) {
							ordqty = 0;
						} else {
							ordqty = prodIdQuants[i].value;
						}
						subDataset = subDataset + ordqty + SM + locName;
					}
				}

				orderString = orderString + subDataset + FM +
					eval("document.qtyform" + idx + ".prodid" + idx + ".value") + FM +
					  formatPrice( eval("document.qtyform" + idx + ".price" + idx + ".value") ) + IM;

			}
		}
	}
	orderString = escape(orderString);
	window.location = "saveOrder.cfm?orderlines=" + orderString + "&forwardto=" + forwardto;
}



function showAvailWidget(movethisel,clickedEl,prodid) {
	invisibleAll();
	//note: the coordinates below are hard coded.
	//		  we may want to pull that from config values at some point

	//how far to push to the left?
	xOffset = 0;
	//how far to push down?
	yOffset = 15;
	moveEl = document.getElementById(movethisel);

	linkEl = document.getElementById(clickedEl);
	linkElx = xPageX(linkEl) - xOffset;
	linkEly = xPageY(linkEl) + yOffset;

	xMoveTo(moveEl,linkElx,linkEly);
	moveEl.style.display = "block";

	var mainQtyId = "main_qty_" + prodid;
	disableQty(mainQtyId);
	poppedProdid = prodid;

}

function closeThisPop(prodid) {
	var mainQtyId = "main_qty_" + prodid;

	eleList = getProdidElements(prodid);

	var enableMainQty = false;
	for (idx = 0; idx < eleList.length; idx++) {
		if (eleList[idx].getAttribute("deflocflag") == "1") {
			enableMainQty = true;
		}
		if (eleList[idx].getAttribute("deflocflag") == "0" && eleList[idx].value > 0) {
			enableMainQty = false;
			break;
		}
	}
	if (enableMainQty == true) {
		enableQty(mainQtyId);
	} else {
		disableQty(mainQtyId);
	}
}

//Replaces the filterInteger funct on the quantity fields
function addQuantIntegers(obj, prodid, locIDs) {
	var mainQtyId = "main_qty_" + prodid;
	var mainQty = document.getElementById(mainQtyId);
	var quantSum = 0;
	for (idx = 0; idx < locIDs.length; idx++) {
		sourceQuantId = locIDs[idx] + "_" + prodid;
		sourceQuant = document.getElementById(sourceQuantId);
		sourceVal = sourceQuant.value;
		if (sourceVal > 0) {
			quantSum = (quantSum * 1) + (sourceVal * 1);
		}
	}
	if (quantSum > 0) {
		mainQty.value = quantSum;
	} else {
		mainQty.value = 0;
	}
}


//look for deflocflag as an attribute of input
function dupMainInteger(obj,prodid) {
	filterInteger(obj);
	eleListArray = getProdidElements(prodid);

	for (idx = 0; idx < eleListArray.length; idx++) {
		//alert(eleListArray[idx].value);
		if (eleListArray[idx].getAttribute("deflocflag") == "1") {
		eleListArray[idx].value = obj.value;
		}
	}

}

//gets array of elements with tag 'input' and specific prodid
function getProdidElements(prodid) {
	eleList = document.getElementsByTagName('input');
	//pidRegExp = "(" + prodid + ")?";
	//alert(pidRegExp);
	var limitedList = new Array();
	var count = 0;
	for (idx = 0; idx < eleList.length; idx++) {
		var extractedProdID = eleList[idx].id.substr(eleList[idx].id.lastIndexOf("_") + 1,eleList[idx].id.length);
		//alert(extractedProdID);
		//if (eleList[idx].id.match(pidRegExp)) {
		if (extractedProdID == prodid) {
			//alert("we have a match for " + prodid);
			limitedList[count] = eleList[idx];
			count++;
		}
	}
	return limitedList;
}

function disableQty(fieldid) {
	chosenField = document.getElementById(fieldid);
	chosenField.disabled = true;
}
function enableQty(fieldid) {
	chosenField = document.getElementById(fieldid);
	chosenField.disabled = false;
}


