// JavaScript Document
var addproductimagecount = 0;
var addproductpartcount = 1;

// This function will show and hide elements based on the id you pass into the function
function showhide(objid) {
	var obj = document.getElementById(objid);
	var s = obj.style.display;
	if(s == "block") {
		hideobj(objid);
	}
	else {
		showobj(objid);
	}
}

// This function will show an element based on the id you pass in
function showobj(objid) {
	var obj = document.getElementById(objid);
	obj.style.display = "block";
}

// This function will hide an element based on the id you pass in
function hideobj(objid) {
	var obj = document.getElementById(objid);
	obj.style.display = "none";
}

// this function checks the input value and then displays the matching object to that value
function showThisFields(testvalue, fields) {
	var i;
	var k;
	var limit;
	if(fields.constructor != Array) {
		return false;
	}
	else {
		limit = fields.length;
		for(i = 0; i < limit; i=i+2) {
			k = i + 1;
			if(testvalue == fields[i]) {
				showobj(fields[k]);
			}
			else {
				hideobj(fields[k]);
			}
		}
	}
}

// This function will check the box by the name you pass into the function
function checkthisbox(objid) {
	var obj = document.getElementById(objid);
	obj.checked = true;
}

// This function will check/uncheck all checkboxes based on the id you pass into the function
function checkallboxes(objid,count) {
	var i;
	var j=0;
	
	for(i = 0; i <= count; i++) {
		var newobjid = objid + i;
		
		var obj = document.getElementById(newobjid);
		if(obj) {
			if(j == 0) {
				var s = obj.checked;
				j++;
			}
			if(s == true) {
				obj.checked = false;
			}
			else {
				obj.checked = true;
			}
		}
	}
}

// This function will check to see if the value of a form is equal to the condition you supplied
// If it is, it will show the objid you passed in, otherwise it will hide the element
function getSelectedValue(value,condition,objid) {
	if(value == condition) {
		showobj(objid);
	}
	else {
		hideobj(objid);
	}
}

// This function will check to see if the value is equal to the conditino you supplied
// If it is, it will execute the first statement or function you pass in, otherwise it will execute the second statement or function you pass in
function checkThisValue(value, condition, execTrue, execFalse) {
	if(value == condition) {
		//alert(execTrue);
		eval(execTrue);
	}
	else {
		//alert(execFalse);
		eval(execFalse);
	}
}


// This function takes the height in feet and inches and converts to total inches
function calcHeight(hFeet, hInches, objId) {
	if(typeof hFeet == 'undefined') {
		hFeet = 0;
	}
	else {
		hFeet = parseInt(hFeet);
	}
	if(typeof hInches == 'undefined') {
		hInches = 0;
	}
	else {
		hInches = parseInt(hInches);
	}
	
	if(isNaN(hFeet)) {
		hFeet = 0;
	}
	
	if(isNaN(hInches)) {
		hInches = 0;
	}
	
	hTotal = (hFeet * 12) + hInches;
	
	obj = document.getElementById(objId);
	
	obj.value = hTotal;
	
}


function addManufacturersRow(tableobj, formobj) {
	var lastrow = tableobj.rows.length;
	tableobj.insertRow(lastrow);
	var prevrow = tableobj.rows[lastrow - 1];
	var formSize = formobj.length;
	var manuSel = formobj.elements[formSize - 5];
	var disSel = formobj.elements[formSize - 4];
	var perTxt = formobj.elements[formSize - 3];
	var btnSub = formobj.elements[formSize - 2];
	var newManuSel = manuSel.cloneNode(true);
	var newDisSel = disSel.cloneNode(true);
	var newPerTxt = perTxt.cloneNode(true);
	
	//alert(newManuSel.options);
	//alert(formSize);
	//alert(formobj.elements[formSize + 2]);
	//alert(newManuSel.innerHTML);
	//alert(manuSel.options[manuSel.selectedIndex].value);
	//alert(disSel.options[disSel.selectedIndex].value);
	//alert(perTxt.value);
	//alert(newManuSel.innerHTML);
	newManuSel.remove(manuSel.selectedIndex);
	//alert(newManuSel.innerHTML);
	var cell1html = '<select name="selManufacturer[]" onchange="if(this == document.getElementsByName(this.name)[document.getElementsByName(this.name).length - 1]) { checkThisValue(this.options[this.selectedIndex].value, \'\', \'null\', \'addManufacturersRow(document.getElementById(\\\'manufacturersTable\\\'), document.getElementById(\\\'contractForm\\\'))\'); }">' + newManuSel.innerHTML + '</select>';
	var cell2html = '<select name="selCalculation[]">' + newDisSel.innerHTML + '</select>';
	var cell3html = '<input type="text" name="txtPercentage[]" size="3" value="" />%';
	var cell4html = '<input type="checkbox" name="chkRemove[]"  value="true" />';
	var row = tableobj.rows[lastrow];
	row.insertCell(0);
	row.insertCell(1);
	row.insertCell(2);
	row.insertCell(3);
	row.cells[0].innerHTML = cell1html;
	row.cells[1].innerHTML = cell2html;
	row.cells[2].innerHTML = cell3html;
	row.cells[3].innerHTML = cell4html;
}

var Dom = {
	get: function(el) {
		if (typeof el === 'string') {
			return document.getElementById(el);
		} else {
			return el;
		}
	},
	add: function(el, dest) {
		var el = this.get(el);
		var dest = this.get(dest);
		dest.appendChild(el);
	},
	remove: function(el) {
		var el = this.get(el);
		el.parentNode.removeChild(el);
	}
};
var Event = {
	add: function() {
		if (window.addEventListener) {
			return function(el, type, fn) {
				Dom.get(el).addEventListener(type, fn, false);
			};
		} else if (window.attachEvent) {
			return function(el, type, fn) {
				var f = function() {
					fn.call(Dom.get(el), window.event);
				};
				Dom.get(el).attachEvent('on' + type, f);
			};
		}
	}()
};
 
// Initialize global variable
previousTargetValue = new Array();

function populateFields(sourceFields, targetFields, savePrevious, disableTarget) {
	// savePrevious is and optional parameter and defaults to false
	if(typeof savePrevious == 'undefined') {
		savePrevious = false;
	}
	if(typeof disableTarget == 'undefined') {
		disableTarget = false;
	}
	// IF user passed an array of fields
	if(sourceFields.constructor == Array) {
		sourceFieldsCount = sourceFields.length;
		if(targetFields.constructor == Array) {
			targetFieldsCount = targetFields.length;
			if(sourceFieldsCount == targetFieldsCount) {
				for(i in sourceFields) {
					sourceObjID = sourceFields[i];
					sourceObj = document.getElementById(sourceObjID);
					targetObjID = targetFields[i];
					targetObj = document.getElementById(targetObjID);
					if(sourceObj && targetObj) {
						if(sourceObj.type == "text") {
							sourceObjValue = sourceObj.value;
						}
						else if(sourceObj.type == "select-one") {
							sourceObjValue = sourceObj.options[sourceObj.selectedIndex].value;
						}
						else if(sourceObj.type == "radio") {
							alert("Radio buttons are currently not supported for this object.");
						}
						else {
							sourceObjValue = sourceObj.value;
						}
						if(targetObj.type == "text") {
							if(savePrevious) {
								previousTargetValue[i] = targetObj.value;
							}
							targetObj.value = sourceObjValue;
							if(disableTarget) {
								targetObj.disabled = true;
							}
						}
						else if(targetObj.type == "select-one") {
							var targetObjOption = false;
							for(j = 0; j < targetObj.length; j++) {
								if(targetObj.options[j].value == sourceObjValue || targetObj.options[j].text == sourceObjValue) {
									if(savePrevious) {
										previousTargetValue[i] = targetObj.selectedIndex;
									}
									targetObj.selectedIndex = j;
									targetObjOption = true;
								}
							}
							if(!targetObjOption) {
								targetNewOption = document.createElement('option');
								targetNewOption.text = sourceObjValue;
								targetNewOption.value = sourceObjValue;
								try {
									targetObj.add(targetNewOption, null);
								}
								catch(ieExcept) {
									targetObj.add(targetNewOption); // For IE Browser
								}
							}
							if(disableTarget) {
								targetObj.disabled = true;
							}
						}
						else if(targetObj.type == "radio") {
							alert("Radio buttons are currently not supported for this object.");
						}
						else {
							if(savePrevious) {
								previousTargetValue[i] = targetObj.value;
							}
							targetObj.value = sourceObjValue;
							if(disableTarget) {
								targetObj.disabled = true;
							}
						}
					}
				}
			}
			else {
				alert("Source and Target element array mismatch.")
			}
		}
		else {
			alert("Source and Target element arrays do not match.");
		}
	}
	// ELSE IF user passed in a single field
	else if(sourceFields.constructor == String) {
		if(targetFields.constructor == String) {
			alert("Currently you will need to pass an array of source and target elements to this object.");
		}
		else {
			alert("Source and Target elements do not match.");
		}
	}
}

function repopulateFields(targetFields) {
	//alert(previousTargetValue);
	if(targetFields.constructor == Array) {
		targetFieldsCount = targetFields.length;
		for(i in targetFields) {
			targetObjID = targetFields[i];
			targetObj = document.getElementById(targetObjID);
			if(targetObj) {
				if(targetObj.type == "text") {
					if(typeof previousTargetValue[i] != 'undefined') {
						targetObj.value = previousTargetValue[i];
					}
					else {
						targetObj.value = "";
					}
				}
				else if(targetObj.type == "select-one") {
					if(typeof previousTargetValue[i] != 'undefined') {
						targetObj.selectedIndex = previousTargetValue[i];
					}
					else {
						targetObj.selectedIndex = 0;
					}
				}
				else if(targetObj.type == "radio") {
					alert("Radio buttons are currently not supported for this object.");
				}
				else {
					if(typeof previousTargetValue[i] != 'undefined') {
						targetObj.value = previousTargetValue[i];
					}
					else {
						targetObj.value = "";
					}
				}
			}
		}
	}
}


// This function checks whether checkboxes or radio buttons in form are checked, finds their corresponding add price and adjusts all their displayed pricing according to the base price
function calculatePrices(formPriceId,textPriceId,partId,totalRows) {
	if(isNaN(totalRows)) {
		return false;
	}
	var totalPrice = baseprice;
	// Go through the loop once to determine the total
	for(var i = 0; i < totalRows; i++) {
		formPriceObj = document.getElementById(formPriceId + i);
		formPartObj = document.getElementById(partId + i);
		addprice = parseFloat(formPriceObj.value);
		if(formPartObj.checked == true) {
			totalPrice = totalPrice + addprice;
			totalPrice.toFixed(2);
		}
	}
	textPriceObj = document.getElementById(textPriceId);
	textPriceObj.innerHTML = totalPrice.toFixed(2);
	
}


// This function replaces the image src of the image id you pass in with the url you pass in
function changeimagesrc(id,newsrc) {
	var obj = document.getElementById(id);
	obj.src = newsrc;
}

// This function replaces the href location of a link id you pass in with the url you pass in
function changelinkhref(id,newhref) {
	var obj = document.getElementById(id);
	obj.href = newhref;
}

// This function will create a dropdown, based on the value of your input, and put it inside the parent id you pass in
function addpartsubcategory(value,parent) {
	var parent = document.getElementById(parent);
	// If it is a seat
	if(value == 3) {
		parent.innerHTML = "Choose a Seat Type:<br /><select name=\"seattype\"><option value=\"1\">Flat Seat</option><option value=\"2\">Mildly Contoured Seat</option><option value=\"3\">Deeply Countoured Seat</option></select><br />Enter Leg Inseam (inches):<br /><input type=\"int\" name=\"inseam\" />";
	}
	// ELSE if it's a backrest
	else if(value == 7) {
		parent.innerHTML = "Neckroll:<br /><select name=\"neckroll\"><option value=\"0\">No</option><option value=\"1\">Yes</option></select>";
	}
	// ELSE clear area
	else {
		parent.innerHTML = "";
	}
}

// This function will create a child element with the base id you pass in, inside the parent id you pass in
function addproductpart(child,parent) {
	var childid = child + "[" + addproductpartcount + "]";
	var parent = document.getElementById(parent);
	var parenthtml = parent.innerHTML;
	if(addproductpartcount == 0) {
		parent.innerHTML = parenthtml + "<br /><b>New Parts</b>";
		parenthtml = parent.innerHTML;
	}
	parent.innerHTML = parenthtml + "<br /><select name=\"cat" + childid + "\" onchange=\"WA_FilterAndPopulateSubList(rsParts_WAJA,MM_findObj(\'cat" + childid + "\'),MM_findObj(\'" + childid + "\'),0,0,false,\': \');WA_AddSubToSelected(MM_findObj(\'" + childid + "\'),MM_findObj(\'" + childid + "\'),false,false,false,0,0,\'0\',\'\')\">\r\n<option>--Select Category--</option>\r\n<option value=\"1\">Adjustable Arm</option>\r\n<option value=\"2\">Fixed Arm</option>\r\n<option value=\"3\">Seat Pan</option>\r\n<option value=\"4\">Base</option>\r\n<option value=\"5\">Cylinder</option>\r\n<option value=\"6\">Finish</option>\r\n<option value=\"7\">Backrest</option><option value=\"8\">Caster</option><option value=\"9\">Seat Slider</option><option value=\"10\">Seat Options</option><option value=\"11\">Foam Options</option><option value=\"12\">Lumbar Support</option><option value=\"13\">Arm Options</option>\r\n</select>\r\n<select name=\"" + childid + "\">\r\n<option>--Select Part--</option>\r\n</select>";
	
	addproductpartcount++;
}

// This function will show an element, populate a child element and a hidden field with the variables you pass in
function addproductimage(id,name) {
	if(addproductimagecount < 5) {
		var base = "productimageswatch";
		var objid = base + addproductimagecount;
		var obj = document.getElementById(objid);
		var childobjid = base + "name" + addproductimagecount;
		var childobj = document.getElementById(childobjid);
		var formobjid = base + "id" + addproductimagecount;
		var formobj = document.getElementById(formobjid);
		
		formobj.value = id;
		childobj.innerHTML = name;
		obj.style.display = "block";
		
		addproductimagecount++;
	}
	else {
		alert("Sorry, you can only upload 5 images");
	}
}

// This function will ask for delete confirmation of item id
// If they confirm it will send them to url, where if they have the correct permissions, the item will be deleted
function deletefromdb(id,url) {
	input_box=confirm("Are you sure you want to delete this?");
	
	if(input_box) {
		str1 = url.concat("task=delete&id=");
		str2 = str1.concat(id);
		window.location = str2;
	}
}

// This function will ask for delete confirmation of item id
// If they confirm it will send them to url, where if they have the correct permissions, the item will be deleted
function removefromorder(item,url) {
	input_box=confirm("Are you sure you want to remove this item from the order?");
	
	if(input_box) {
		str1 = url.concat("task=remove&item=");
		str2 = str1.concat(item);
		window.location = str2;
	}
}

// This function will ask for delete confirmation of item id
// If they confirm it will send them to url, where if they have the correct permissions, the item will be deleted
function confirmpo(id,url) {
	input_box=prompt("Are you sure you want to confirm this Request for PO? Enter your PO# to confirm.");
	
	if(input_box != null && input_box != "") {
		str1 = url.concat("task=confirm&id=");
		str2 = str1.concat(id);
		str3 = str2.concat("&confirm=");
		str4 = str3.concat(escape(input_box));
		window.location = str4;
	}
}

// This function sets the max length for the textarea object
function ismaxlength(obj){
	var mlength=obj.getAttribute? parseInt(obj.getAttribute("maxlength")) : ""
	if (obj.getAttribute && obj.value.length>mlength)
	obj.value=obj.value.substring(0,mlength)
}

function checkext(upload_field) {     
	// this is just an example of checking      
	// image file extension - jpg/jpeg     
	var re_text = /\.jpeg|\.jpg/i;     
	var filename = upload_field.value;     
	/* Checking file type */     
	if (filename.search(re_text) == -1) {         
		alert("Please select JPEG file");         
		upload_field.value = '';     
	}     
	return true;
}

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_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

function popup(winLink, winName, winWidth, winHeight, winResize, winScroll, winMenu) {
	if(winWidth == undefined || isNaN(winWidth)) {
		winWidth = 400;
	}
	if(winHeight == undefined || isNaN(winHeight)) {
		winHeight = 400;
	}
	if(winResize == undefined || (winResize != "yes" && winResize != "no" && winResize.constructor == NaN && winResize != 1 && winResize != 0 && winResize.constructor != Boolean)) {
		winResize = "yes";
	}
	if(winScroll == undefined || (winScroll != "yes" && winScroll != "no" && winScroll.constructor == NaN && winScroll != 1 && winScroll != 0 && winScroll.constructor != Boolean)) {
		winScroll = "yes";
	}
	if(winMenu == undefined || (winMenu != "yes" && winMenu != "no" && winMenu.constructor == NaN && winMenu != 1 && winMenu != 0 && winMenu.constructor != Boolean)) {
		winMenu = "yes";
	}
	if(!window.focus) {
		return true;
	}
	var winURL;
	if(typeof(winLink) == 'string') {
		winURL=winLink;
	}
	else {
		winURL=winLink.href;
	}
	var winStyle;
	winStyle = 'width=' + winWidth + ',height=' + winHeight + ',scrollbars=' + winScroll + ',menubar=' + winMenu + ',location=' + winMenu + ',toolbar=' + winMenu + ',resizable=' + winResize;
	window.open(winURL, winName, winStyle);
}