// JavaScript Document

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_preloadImages2(images) { //v3.0
	var d=document; 
	if(d.images) { 
		if(!d.MM_p) { 
			d.MM_p=new Array(); 
		}
    	var i,j = d.MM_p.length;
		var a = images;
		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_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_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 MM_jumpMenu(targ,selObj,restore){ //v3.0
  eval(targ+".location='"+selObj.options[selObj.selectedIndex].value+"'");
  if (restore) selObj.selectedIndex=0;
}

function MM_openBrWindow(theURL,winName,features) { //v2.0
  window.open(theURL,winName,features);
}

function isZip(s, country) {
	// Check for correct zip code
    reZip = new RegExp(/(^\d{5}$)|(^\d{5}-\d{4}$)/);

    if (!reZip.test(s) && country == "United States") {
    	return false;
    } 
	return true;
}

var request;
var disclaimer = 0;

function getUrlParms (name) {  
	name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");  
	var regexS = "[\\?&]"+name+"=([^&#]*)";  
	var regex = new RegExp( regexS );  
	var results = regex.exec( window.location.href );  
	
	if( results == null ) {   
		return "";
	}  else {
		return results[1];
	}
}   

function changeCountry() {
	var shipCountry = document.detailsForm.shipcountryid[document.detailsForm.shipcountryid.selectedIndex].text;
	var shipDiv = document.getElementById("shipstateid");
	var shipDiv2 = document.getElementById("shipstateid2");
	
	var billCountry = document.detailsForm.billcountryid[document.detailsForm.billcountryid.selectedIndex].text;
	var billDiv = document.getElementById("billstateid");
	var billDiv2 = document.getElementById("billstateid2");
	
	if (billCountry == 'United States' || billCountry == 'Canada') {
		billDiv.style.display = "block";
		billDiv2.style.display = "none";
	} else {
		billDiv.style.display = "none";
		billDiv2.style.display = "block";
		if (!disclaimer) {
			alert("DISCLAIMER:  When ordering products from outside of the United States, you are responsible for any taxes, duty, or brokerage fees that may be involved.  Please check with your local authorities/agencies for more information about these additional fees.");
			disclaimer = 1;
		}
	}
	
	if (shipCountry == 'United States' || shipCountry == 'Canada') {
		shipDiv.style.display = "block";
		shipDiv2.style.display = "none";
	} else {
		if (!disclaimer) {
			alert("DISCLAIMER:  When ordering products from outside of the United States, you are responsible for any taxes, duty, or brokerage fees that may be involved.  Please check with your local authorities/agencies for more information about these additional fees.");
			disclaimer = 1;
		}
		shipDiv.style.display = "none";
		shipDiv2.style.display = "block";
	}
}


function getShippingOptions () {
	var zip;
	var state;
	var country;
	var weight = parseFloat(document.detailsForm.weight.value);
	var subtotal = document.getElementById('subtotal').innerHTML;
	var subtotalbeforeshipping = document.getElementById('subtotalbeforeshipping').value;
	subtotal = subtotal.replace(/\$/,"");
	subtotal = parseFloat(subtotal);

	if (document.detailsForm.sameAsBilling.checked) {
		country = document.detailsForm.billcountryid[document.detailsForm.billcountryid.selectedIndex].text;
		city = document.detailsForm.billcity.value;
		zip = document.detailsForm.billzip.value;
		state = document.detailsForm.billstateid[document.detailsForm.billstateid.selectedIndex].text;
		
	} else {
		country = document.detailsForm.shipcountryid[document.detailsForm.shipcountryid.selectedIndex].text;
		city = document.detailsForm.shipcity.value;
		zip = document.detailsForm.shipzip.value;
		state = document.detailsForm.shipstateid[document.detailsForm.shipstateid.selectedIndex].text;
	}
	if (!isZip(zip, country)) {
		document.getElementById('shipOptions').innerHTML =
			"<button onclick='getShippingOptions()'>Show Shipping Options</button>";
		document.getElementById('shipError1').innerHTML = "You must specify a valid shipping";
		document.getElementById('shipError2').innerHTML = "Postal Code";
		return false;
	} else {
		document.getElementById('shipOptions').innerHTML = "Rates are being calculated...";
		document.getElementById('shipError1').innerHTML = "Shipping to Postal Code: " + zip;
		document.getElementById('shipError2').innerHTML = "";
	}
	request = new createXMLHttpRequest();
	var parameters = 'zip=' + zip + '&weight=' + weight + '&state=' + state +'&subtotal=' + subtotalbeforeshipping + '&country=' + country + '&city=' + city;
	request.open('GET', '/cart/includes/ups.php' + '?' + parameters, true);
	request.onreadystatechange = parseResponse;
	request.send(null);
}

function parseResponse() { 
	if (request.readyState == 4) {
		if (request.status == 200) {
			var xmlString = request.responseText;
			re = new RegExp(/^Error/);
			if (re.test(xmlString)) {
				document.getElementById('shipOptions').innerHTML = 
					"<button onclick='getShippingOptions()'>Show Shipping Options</button>";
				document.getElementById('shipError1').innerHTML = xmlString;
				document.getElementById('shipError2').innerHTML = "Please correct";
			} else {
				document.getElementById('shipOptions').innerHTML = xmlString;
				updateTotals();
			}
		} 
		request = null;
	}
}

function updateTotals () {
	var total = 0;
	var state;
	var tax = 0;
	var shipping = 0;
	var giftcard = 0;
	var balance = 0;
	
	var subtotal = document.getElementById('subtotal').innerHTML;
	subtotal = subtotal.replace(/\$/,"");
	subtotal = parseFloat(subtotal);

	var shippingChoice = document.detailsForm.shipSelect[document.detailsForm.shipSelect.selectedIndex].text;
	shippingChoice = shippingChoice.split(' - ');
	shipping = shippingChoice[1];
	if (shipping) {
		shipping = shipping.replace(/\$/,"");
	} else {
		shipping = 0;
	}

	if (document.detailsForm.sameAsBilling.checked) {
		state = document.detailsForm.billstateid[document.detailsForm.billstateid.selectedIndex].text;
	} else {
		state = document.detailsForm.shipstateid[document.detailsForm.shipstateid.selectedIndex].text;
	}
	if (state == "Arizona") {
		tax = subtotal * .0795;		 
	} 
	tax = tax.toFixed(2);
	total = parseFloat(subtotal) + parseFloat(shipping) + parseFloat(tax);
	total = total.toFixed(2);
	shipping = parseFloat(shipping);
	shipping = shipping.toFixed(2);
	
	document.getElementById('shipping').innerHTML = "$" + shipping;
	document.getElementById('tax').innerHTML = "$" + tax;
	document.getElementById('total').innerHTML = "$" + total;
	document.detailsForm.subtotal.value = subtotal;
	document.detailsForm.taxtotal.value = tax;
	document.detailsForm.shiptotal.value = shipping;
	document.detailsForm.ordertotal.value = total;
	
	request = new createXMLHttpRequest();
	var parameters = 'balance=' + total;
	request.open('GET', '/cart/cart/giftcard.php' + '?' + parameters, false);
	request.send(null);
	var xhtmlString = request.responseText;
		
	balance = parseFloat(xhtmlString);

    balance = balance.toFixed(2);
	giftcard = total - balance;
	giftcard = giftcard.toFixed(2);
		
	document.detailsForm.giftcard.value = giftcard;
	document.detailsForm.amountdue.value = balance;
	document.getElementById('giftcard').innerHTML = "$" + giftcard;
	document.getElementById('amountdue').innerHTML = "$" + balance;
	
	return true;
}

function newCard() {
	var radioObj = document.detailsForm.paymentmethod;
	var radioLength = radioObj.length;
	
	for(var i = 0; i < radioLength; i++) {
		radioObj[i].checked = false;
		if(radioObj[i].value == "newmethod") {
			radioObj[i].checked = true;
		}
	}
}

function showLogin () {
	request = new createXMLHttpRequest();
	request.open('GET', '/cart/includes/showlogin.php', false);
	request.send(null);
	var xhtml = request.responseText;
	document.getElementById('loginStatus').innerHTML = xhtml;
}

function showRetailerLogin () {
	request = new createXMLHttpRequest();
	request.open('GET', '/cart/includes/showretailerlogin.php', false);
	request.send(null);
	var xhtml = request.responseText;
	document.getElementById('loginStatus').innerHTML = xhtml;
}

function clearTotalsOrderForm() {
	document.getElementById('total').innerHTML = "$" + "0.00";
	document.getElementById(name + 'total').innerHTML = "$" + "0.00";
	return true;
}

function unlockTotalField (element) {
	var id = element.id;
	var id2 = id.replace(/unlock/, "total");
	var id3 = id.replace(/unlock/, "cpsize");

	if(document.getElementById(id).checked) {
		document.getElementById(id2).readOnly = false;
		document.getElementById(id3).readOnly = false;
	} else {
		document.getElementById(id2).readOnly = true;
		document.getElementById(id3).readOnly = true;
	}
}

function manualTotalChange () {
	var table = document.getElementById('orderform');
	var total = 0;
	
	for(var i = 0; i < table.rows.length; i++) {
		if (table.rows[i].cells.length == 12) {
			var rowname = table.rows[i].cells[2].innerHTML;
			if (rowname != "Style #") {
				var rowtotal = document.getElementById('product_' + rowname + 'total').value;
				if (rowtotal != "") {
					total += parseFloat(rowtotal.replace(/\$/,""));
					document.getElementById('product_' + rowname + 'total').value = "$" + parseFloat(rowtotal.replace(/\$/,"")).toFixed(2);
				} else {
					if (document.getElementById('product_' + rowname).value != "") {
						document.getElementById('product_' + rowname + 'total').value = "$0.00";
					}
				}
			}
		}
	}
	total = total.toFixed(2);
	document.getElementById('total').innerHTML = "$" + total;
}

function updateCasePackCost (element) {
	
	var name = element.name;
	
	name = name.replace(/cpsize/, "");
	
	var unitcost = document.getElementById(name + "unitcost").innerHTML;
	unitcost = parseFloat(unitcost.replace(/\$/,""));
	
	var cost = unitcost * element.value;
	
	cost = cost.toFixed(2);
	
	document.getElementById(name + "cost").innerHTML = "$" + cost;
	
	element = document.getElementById(name);
	updateTotalsOrderForm2(element);
}

function updateTotalsOrderForm2(element) {
	var name = element.name;
	var quantity = element.value;
	if (isNaN(quantity)) {
		alert("Value must be numeric");
		element.value = '';
		return;
	}
	if (!(/^\d*$/.test(quantity))) {
		alert("Value cannot contain a decimal");
		element.value = '';
		return;
	}
	var cost = document.getElementById(name + 'cost').innerHTML;

	var subtotal = 0;
	
	cost = parseFloat(cost.replace(/\$/,""));
	
	var subtotal = cost * quantity;

	document.getElementById(name + 'total').value = "$" + subtotal;
	manualTotalChange ();
}

function recalculateTotal() {
	var table = document.getElementById('orderformid');
	var total = 0;

	for(var i = 0; i < table.rows.length; i++) {
		if (table.rows[i].cells.length == 11) {
			var rowname = table.rows[i].cells[2].innerHTML;
			if (rowname != "Style #") {
				var rowtotal = document.getElementById(rowname + 'total').innerHTML;
				if (rowtotal != "") {
					total += parseFloat(rowtotal.replace(/\$/,""));
				}
			}
		}
	}
	total = total.toFixed(2);
	document.getElementById('total').innerHTML = "$" + total;
}

function updateTotalsOrderForm(element) {
	var name = element.name;
	var quantity = element.value;
	if (isNaN(quantity)) {
		alert("Value must be numeric");
		element.value = '';
		return;
	}
	if (!(/^\d*$/.test(quantity))) {
		alert("Value cannot contain a decimal");
		element.value = '';
		return;
	}
	var cost = document.getElementById(name + 'cost').innerHTML;
	var subtotal = 0;
	
	cost = parseFloat(cost.replace(/\$/,""));
	var subtotal = cost * quantity;

	subtotal = subtotal.toFixed(2);
	
	document.getElementById(name + 'totalid').value = subtotal;
	document.getElementById(name + 'total').innerHTML = "$" + subtotal;
	recalculateTotal ();
}

function updateTotalsProcessPayment(checkboxid, totalid) {
	var i = 0;
	var total = 0;
	var amount = 0;
	
	for (i=0; document.getElementById(checkboxid + i) != null; i++) {
		if (document.getElementById(checkboxid + i).checked) {
			amount = parseFloat(document.getElementById(checkboxid + i).value.replace(/\,/g, ""));
    		total = total + amount;
		}
	}
	total = parseFloat(total);
	total = total.toFixed(2);
	
	document.getElementById(totalid).value = total;
}


function getRetailerShippingOptions () {
	var zip;
	var state;
	var country;
	var weight = parseFloat(document.detailsForm.weight.value);
	var subtotal = document.getElementById('subtotal').innerHTML;
	subtotal = subtotal.replace(/\$/,"");
	subtotal = parseFloat(subtotal);

	zip = document.detailsForm.shipzip.value;
	state = document.detailsForm.shipstatename.value;
	country = document.detailsForm.shipcountryname.value;

	if (!isZip(zip, country)) {
		document.getElementById('shipOptions').innerHTML =
			"<button onclick='getShippingOptions()'>Show Shipping Options</button>";
		document.getElementById('shipError1').innerHTML = "You must specify a valid shipping";
		document.getElementById('shipError2').innerHTML = "Zip Code";
		return false;
	} else {
		document.getElementById('shipOptions').innerHTML = "Rates are being calculated...";
		document.getElementById('shipError1').innerHTML = "Shipping to Zip Code: " + zip;
		document.getElementById('shipError2').innerHTML = "";
	}
	request = new createXMLHttpRequest();
	var parameters = 'zip=' + zip + '&weight=' + weight + '&state=' + state +'&subtotal=-1' + '&country=' + country;
	request.open('GET', '/cart/includes/ups.php' + '?' + parameters, true);
	request.onreadystatechange = displayShippingOptions;
	request.send(null);
}

function displayShippingOptions() { 
	if (request.readyState == 4) {
		if (request.status == 200) {
			var xmlString = request.responseText;
			re = new RegExp(/^Error/);
			if (re.test(xmlString)) {
				document.getElementById('shipOptions').innerHTML = 
					"<button onclick='getShippingOptions()'>Show Shipping Options</button>";
				document.getElementById('shipError1').innerHTML = xmlString;
				document.getElementById('shipError2').innerHTML = "Please correct";
			} else {
				document.getElementById('shipOptions').innerHTML = xmlString;
				updateRetailerTotals();
			}
		} 
		request = null;
	}
}

function updateRetailerTotals () {
	var total = 0;
	var state;
	var tax = 0;
	var shipping = 0;
	
	var subtotal = document.getElementById('subtotal').innerHTML;
	subtotal = subtotal.replace(/\$/,"");
	subtotal = parseFloat(subtotal);

	var shippingChoice = document.detailsForm.shipSelect[document.detailsForm.shipSelect.selectedIndex].text;
	shippingChoice = shippingChoice.split(' - ');
	shipping = shippingChoice[1];
	if (shipping) {
		shipping = shipping.replace(/\$/,"");
	} else {
		shipping = 0;
	}
	tax = 0;
	tax = tax.toFixed(2);
	total = parseFloat(subtotal) + parseFloat(shipping) + parseFloat(tax);
	total = total.toFixed(2);
	shipping = parseFloat(shipping);
	shipping = shipping.toFixed(2);
	
	document.getElementById('shipping').innerHTML = "$" + shipping;
	document.getElementById('tax').innerHTML = "$" + tax;
	document.getElementById('total').innerHTML = "$" + total;
	document.detailsForm.subtotal.value = subtotal;
	document.detailsForm.taxtotal.value = tax;
	document.detailsForm.shiptotal.value = shipping;
	document.detailsForm.ordertotal.value = total;
	
	return true;
}

function createXMLHttpRequest () {
	var xmlHttp=null;
	if (window.XMLHttpRequest && (typeof XMLHttpRequest != 'undefined')) {
		try	{
			// Firefox, Opera 8.0+, Safari
 			xmlHttp = new XMLHttpRequest();
 		} catch (e) {
 			xmlHttp = false;
		}
	} else {
		try	{
  			xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
  		} catch (e) {
  			xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
  		}
 	}
	return xmlHttp;
}

function requestData (request, url, data, func, method, async) {
	if (request) {
		if (method == 'GET') {
			request.open('GET', url + '?' + data, async);
			if (async) {
				request.onreadystatechange = func;
			}
			request.send();
		} else {
			request.open('POST', url, async);
			request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
			request.setRequestHeader("Content-length", data.length);
			request.setRequestHeader("Connection", "close");
			if (async) {
				request.onreadystatechange = func;
			}
			request.send(data);
		}
	}
}

function limitText(limitField, limitCount, limitNum) {
	if (limitField.value.length > limitNum) {
		limitField.value = limitField.value.substring(0, limitNum);
	} else {
		limitCount.value = limitNum - limitField.value.length;
	}
}

function removeSubmitButton() {
	document.getElementById('removeButton').innerHTML = "Your order is being processed, please wait...";
	return true;
}

function confirmDelete(document, newurl) {
	if (!confirm("You are about to permanently delete this item.  Continue?")) {
			return false;
	}
	location.href=newurl;
}

function generatePieChart(array, id) {
	var i;
	var p = new pie();
	for (i=0; i<array.length; i+=2) {
		p.add(array[i],array[i+1]);
	} 
	p.render(id, "Pie Graph");
}
/*
function generateLineChart(thismonth, lastmonth, labels, id) {
	var dataset = {};
	var i;
	
	dataset.
	
	var options = {
		// Define a padding for the canvas node
		padding: {
			left: 30, 
			right: 0, 
			top: 10, 
			bottom: 30
		},
		
		// Background color to render.
		background: {
			color: '#f2f2f2'
		},
		
		colorScheme: new Hash({
					'Current Month': '#1c4a7e',
					'Last Month': '#bb5b3d'
				}),

		// Use the predefined blue colorscheme.
		colorScheme: 'blue',
		
		axis: {
			// The fontcolor of the labels is black.
			labelColor: '#000000',
			// Add the ticks. Keep in mind, x and y axis are swapped
			// when the BarOrientation is horizontal.
			x: {
				ticks: [
					{v:0, label:''} 
				]
			}	
		},
		// Set the legend position.
		legend: {
			position:{
				left: '420px'	
			}	
		}
	};
	
}*/


function saveAttachmentName (element) {
	var filename = document.getElementById(element).value;
	document.getElementById(element + 'hidden').value = filename;
}

function hide_div (name) {
	if (document.getElementById(name + '_widget').style.display == "none") {
		document.getElementById(name + '_widget').style.display="block";
		document.getElementById(name + '_collapse').innerHTML = "-";
		
	} else {
		document.getElementById(name + '_widget').style.display="none";
		document.getElementById(name + '_collapse').innerHTML = "+";
	}
}

function displaySearch () {
	document.getElementById('searchbox').style.display = "block";
	document.getElementById('searchboxheader').style.display = "block";
	document.getElementById('accountSearchBox').focus();
}

function closeSearch () {
	document.getElementById('searchbox').style.display = "none";
	document.getElementById('searchboxheader').style.display = "none";
}

function accountSearch (searchTerms, submitform) {
	request = new createXMLHttpRequest();
	var parameters = 'search_terms=' + searchTerms;
	request.open('GET', '/cart/main/search_accounts.php' + '?' + parameters, true);
	request.onreadystatechange = searchResponse;
	request.send(null);
}

function searchResponse () { 
	if (request.readyState == 4) {
		if (request.status == 200) {
			var xmlString = request.responseText;
			if (!xmlString) {
				document.getElementById('accountSearchResults').innerHTML = "<div style='float:left; text-align:left'><br/><br/>No search results found</div>";
			} else {
				var xmlhttp = new XMLHttpRequest();   
				xmlhttp.open("GET", "/cart/main/views/search_results.xsl", false);   
				xmlhttp.send('');   
				var processor = new XSLTProcessor();
				processor.importStylesheet(xmlhttp.responseXML);
				var newDoc = processor.transformToDocument(request.responseXML);
				var newList = new XMLSerializer().serializeToString(newDoc);
				document.getElementById('accountSearchResults').innerHTML = newList;
			}
		} 
		request = null;
	}
}

function insertSearchResult(name, locationid) {
	document.getElementById("account").value = name;
	document.getElementById("locationid").value = locationid;
	closeSearch();
	ajaxsubmit('/cart/ajax/search/searchresults.php');
}

function reminderWindow() {
	window.name = "main";
	window.open("https://www.whishbody.com/cart/main/reminder1.php", "reminder", "status=1,width=450,height=250");
}

function setAllChecks() {
	document.getElementById('allcheckbox').checked = true;
	checkAllReminders();
}
	
function checkAllReminders() {
	var checkboxes = document.reminderform.elements['remindercheckbox[]'];
	if(document.getElementById('allcheckbox').checked == true) {
		if (checkboxes.length == undefined) {
			checkboxes.checked = true;
		} else {
			for (i = 0; i < checkboxes.length; i++) {
				checkboxes[i].checked = true;
			}
		}
	} else {
		if (checkboxes.length == undefined) {
			checkboxes.checked = false;
		} else {
			for (i = 0; i < checkboxes.length; i++) {
				checkboxes[i].checked = false;
			}
		}
	}
	registerReminderCheck();
}

function registerReminderCheck() {
	var checkboxes = document.reminderform.elements['remindercheckbox[]'];
	var onechecked = false;
	if (checkboxes.length == undefined) {
		if(checkboxes.checked == true) {
			document.reminderform.dismiss.disabled = false;
			document.reminderform.snooze.disabled = false;
		} else {
			document.reminderform.dismiss.disabled = true;
			document.reminderform.snooze.disabled = true;
			document.getElementById('allcheckbox').checked = false;
		}
	} else {
		for (i = 0; i < checkboxes.length; i++) {
			if (checkboxes[i].checked == true) {
				onechecked = true;
			}
		}
		if (onechecked = true) {
			document.reminderform.dismiss.disabled = false;
			document.reminderform.snooze.disabled = false;
		} else {
			document.reminderform.dismiss.disabled = true;
			document.reminderform.snooze.disabled = true;
			document.getElementById('allcheckbox').checked = false;
		}
	}
}

function transferCSV(table) {
	var r  = 0;
	var gTable = document.getElementById(table);
	csvout = window;
	numofRows = gTable.rows.length-1;
	numofCells =  gTable.rows[0].cells.length-1    
	var rowcsv = [numofRows];
	var csvdata = "";
	var cntrows = 0;
	for ( r == 0; r <= numofRows; r++) {
		var c =0;
		tempdata = "";
		for (c == 0; c<=numofCells; c++) {
			if (c != numofCells) {
				if(document.all) {
					tempdata+= "\"" + gTable.rows[r].cells[c].innerText + "\"" + ",";
				} else{
    				tempdata+= "\"" + gTable.rows[r].cells[c].textContent + "\"" + ",";
				}
			} else {
				if(document.all) {
					tempdata+= "\"" + gTable.rows[r].cells[c].innerText + "\"" + "\n";
				} else {
					tempdata+= "\"" + gTable.rows[r].cells[c].textContent + "\"" + "\n";
				}
			}
		}
		csvdata += tempdata;
	}
	var data = "data=" + escape(csvdata);
	request = createXMLHttpRequest();
	requestData (request, '/cart/reports/savecsv.php', data, processSaveCSVResults, 'POST', true);
}

function processSaveCSVResults () {
	if (request.readyState == 4) {
		if (request.status == 200) {
			var xmlString = request.responseText;
			location.href = '/cart/reports/downloadcsv.php?id=' + xmlString;
		} 
		request = null;
	}
}

function couponPopup () {
	var couponcode;
	var width;
	var height;
	var top;
	var left;
	
	couponcode = document.getElementById('couponcode').value;
	var storenumber = document.getElementById('storenumber').value;
	if (couponcode == 'nordstrom25' && storenumber == '') {
		
		
		document.getElementById('couponsupplement').style.display = "block";
		document.getElementById('couponsupplementheader').style.display = "block";
		
		
		return false;
	} else {
		return true;
	}
}
	
function couponPopupClose () {
	document.getElementById('couponsupplement').style.display = "none";
	document.getElementById('couponsupplementheader').style.display = "none";
}

function createMarker(point, name, address, type) {  
	var marker = new GMarker(point, customIcons[type]);  
	var html = "<b>" + name + "</b> <br/>" + address;  
	GEvent.addListener(marker, 'click', function() {    
		marker.openInfoWindowHtml(html);  
	});  
	return marker;
}

function createSidebarEntry(marker, name, address, distance) {
  var div = document.createElement('div');
  var html = '<b>' + name + '</b> (' + distance.toFixed(1) + ')<br/>' + address;
  div.innerHTML = html;
  div.style.cursor = 'pointer';
  div.style.marginBottom = '5px';
  GEvent.addDomListener(div, 'click', function() {
    GEvent.trigger(marker, 'click');
  });
  GEvent.addDomListener(div, 'mouseover', function() {
    div.style.backgroundColor = '#eee';
  });
  GEvent.addDomListener(div, 'mouseout', function() {
    div.style.backgroundColor = '#fff';
  });
  return div;
}

function searchLocations() {
	var address = document.getElementById('search_terms2').value;
	geocoder.getLatLng(address, function(latlng) {
    	if (!latlng) {
			alert(address + ' not found');
       } else {
		   googleSearch(latlng);
       }
	});
}


function googleSearch (center) {
	var radius = document.getElementById('radiusSelect').value;
	request = new createXMLHttpRequest();
	var parameters = 'lat=' + center.lat() + '&lng=' + center.lng() + '&radius=' + radius;
	request.open('GET', '/cart/main/searchmap2.php' + '?' + parameters, true);
	request.onreadystatechange = googleSearchCallback;
	request.send(null);
}

function googleSearchCallback () {
	if (request.readyState == 4) {
		if (request.status == 200) {
			var xmlString = request.responseText;
	
			var xml = GXml.parse(xmlString);  
			var markers = xml.documentElement.getElementsByTagName("marker");  
			
			var sidebar = document.getElementById('searchresults');
    		sidebar.innerHTML = '';
			map.clearOverlays();
			if (markers.length == 0) {
			  sidebar.innerHTML = 'No results found.';
			  map.setCenter(new GLatLng(40, -100), 4);
			  return;
			}
			var bounds = new GLatLngBounds();
			for (var i = 0; i < markers.length; i++) {    
				var name = markers[i].getAttribute("name");    
				var address = markers[i].getAttribute("address");    
				var type = markers[i].getAttribute("type");    
				var point = new GLatLng(parseFloat(markers[i].getAttribute("lat")), 
										parseFloat(markers[i].getAttribute("lng")));
				
				var marker = createMarker(point, name, address, type);    
				var distance = parseFloat(markers[i].getAttribute('distance'));

				map.addOverlay(marker);  
				var sidebarEntry = createSidebarEntry(marker, name, address, distance);
      			sidebar.appendChild(sidebarEntry);
      			bounds.extend(point);
			}
			map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
		}
		request = null;
	}
}

function copyFields(from, to) {
	document.getElementById(to + 'name').value = document.getElementById(from + 'name').value;
	document.getElementById(to + 'address1').value = document.getElementById(from + 'address1').value;
	document.getElementById(to + 'address2').value = document.getElementById(from + 'address2').value;
	document.getElementById(to + 'city').value = document.getElementById(from + 'city').value;
	document.getElementById(to + 'stateidID').value = document.getElementById(from + 'stateidID').value;
	document.getElementById(to + 'zip').value = document.getElementById(from + 'zip').value;
	document.getElementById(to + 'countryidid').value = document.getElementById(from + 'countryidid').value;
}

function autoFillUserForm () {
	var account = document.detailsForm.accountSelect[document.detailsForm.accountSelect.selectedIndex].text;
	account = account.replace(/ /g,"");
	account = account.replace(/\'/g,"");
	account = account.toLowerCase();
	if (account.length > 8) {
		account = account.substr(0,8);
	}	
	for(var i = 0; i < 8 - account.length; i++) {
		account += "0";
	}
	account += "01";
	document.getElementById('username').value = account;
	
	var password = "";

    // define possible characters
    var possible = "0123456789bcdfghjkmnpqrstvwxyz"; 
    // set up a counter
    var i = 0; 
    var char = "";
    // add random characters to $password until $length is reached
    while (i < 8) { 

    	// pick a random character from the possible ones
    	char = possible.substr(mt_rand(0, possible.length-1), 1);
        
    	// we don't want this character if it's already in the password
    	if (!strstr(password, char)) { 
      		password += char;
      		i++;
    	}
	}
	document.getElementById('newPassword1').value = password;
	document.getElementById('newPassword2').value = password;
	document.getElementById('name').value = document.detailsForm.accountSelect[document.detailsForm.accountSelect.selectedIndex].text;
}

function mt_rand( min, max ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Onno Marsman
    // *     example 1: mt_rand(1, 1);
    // *     returns 1: 1
    var argc = arguments.length;
    if (argc === 0) {
        min = 0;
        max = 2147483647;
    } else if (argc === 1) {
        throw new Error('Warning: mt_rand() expects exactly 2 parameters, 1 given');
    }
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

function strstr( haystack, needle, bool ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Onno Marsman
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // *     example 1: strstr('Kevin van Zonneveld', 'van');
    // *     returns 1: 'van Zonneveld'
    // *     example 2: strstr('Kevin van Zonneveld', 'van', true);
    // *     returns 2: 'Kevin '
    // *     example 3: strstr('name@example.com', '@');
    // *     returns 3: '@example.com'
    // *     example 4: strstr('name@example.com', '@', true);
    // *     returns 4: 'name'
 
    var pos = 0;
    
    haystack += '';
    pos = haystack.indexOf( needle );
    if (pos == -1) {
        return false;
    } else{
        if( bool ){
            return haystack.substr( 0, pos );
        } else{
            return haystack.slice( pos );
        }
    }
}

function updateProductCode () {
	var product = document.getElementById("product").value;
	var flavor = document.getElementById("flavor").value;
	var formfactor = document.getElementById("formfactor").value;
	var component = document.getElementById("component").value;
	
	var partnum = parseInt(product) + parseInt(flavor) + parseInt(formfactor);
	
	partnum = partnum + component;
	document.getElementById("partnum").innerHTML = partnum;
}

function showallaccounts () {
	var cb = document.getElementById("showall");
	var view = document.getElementById('accountViewList').value;
	
	if (cb.checked == true) {
		var url = "/cart/main/account_home.php?showall=1&view=" + view;
	} else {
		var url = "/cart/main/account_home.php?view=" + view;
		
	}
	var id = 'accounts_home';
	var title = 'Accounts Home'
	loadPageInTab (url, id, title);
}

function showallopportunities () {
	var cb = document.getElementById("showall");
	var view = document.getElementById('opportunityViewList').value;
	
	if (cb.checked == true) {
		var url = "/cart/main/opportunity_home.php?showall=1&view=" + view;
	} else {
		var url = "/cart/main/opportunity_home.php?view=" + view;
		
	}
	var id = 'opportunities_home';
	var title = 'Opportunities Home'
	loadPageInTab (url, id, title);
}

function checkall () {
	var c = new Array();
	c = document.getElementsByTagName('input');
  	for (var i = 0; i < c.length; i++) {
    	if (c[i].type == 'checkbox') {
			c[i].checked = true;
    	}
  	}
}

function uncheckall () {
	var c = new Array();
	c = document.getElementsByTagName('input');
  	for (var i = 0; i < c.length; i++) {
    	if (c[i].type == 'checkbox') {
			c[i].checked = false;
    	}
  	}
}

function markbutton (button) {
	button.name = "post_this_form";
}