// display cart and checkout
var ptUserDiscount = (top.ptUserTypeId==6) ? true : false; // || top.ptUserAccounts.indexOf("6")!=-1
	
function changeSpaces(tstring) {
    nstring=tstring.replace(/( |#)/g," ");
    return nstring.replace(/"/g," inch");
}

//Function looks for {fieldname} tags inside [aterm], and when it finds them, it looks for form variables that are named [fieldname].  It then substitutes form variables' selected values (or text, if mode=text) back into [aterm].  If it can't find field, no substitution takes place.
function ptSearchReplace(aform,aterm,mode,arow) {
	//search for {...} in term.
	var re = /(\{([^}]+)})/gi;
	return aterm.replace(re,
		function (str,p1,p2,offset,s) {
			//alert(str + ":" + p1  + ":" + p2  + ":" + offset  + ":" + s);
			if (!aform) {alert ("Programming Error: no form defined!"); return "";}
			if (!aform.elements[p2+arow]) {
				if (!aform.elements[p2+"1"]) {
					alert ("Programming Error: no form field [" +p2 + "1] defined!"); return "";
				}
				else var afield=aform.elements[p2+"1"]; 
			}
			else var afield=aform.elements[p2+arow]; 
			if (mode=="text") {
				//select option text is available:
				if (afield.options)	return afield.options[afield.selectedIndex].text;
				//regular text input is available:
				if (afield.value) return afield.value;
				else return "";
			}
			else return afield.options[afield.selectedIndex].value;
		}
	)
}
//buyItem([buynow field],[
function buyItem(afield,row,tally,itemFlag) {
	var aform=afield.form;
	var ptData= eval('(' + aform.elements["data"].value + ')');
	var price=0;
	var basic_price=0;
	var shipping=0;
	var quantity=1;
	var shipping_info="";
	var productCount=0;
	var winName = "";
	
	var radios = aform.elements["product_radio"];
	var products = aform.elements["product"];
			
	//Here buyNow button triggers Net1 order form for this product only.  triggered when control="a" OR there are no radio or checkbox items on form.
	if (ptData.control[row]=="a" || (!radios && !products) || (ptData.control[row]=="" && row >1)) {
		productCount++;
		basic_price = ptData.price[row];
		price=basic_price;
		shipping=ptData.shipping[row];
		shipping_info=ptData.shipping_info[row];
		winName = buyItem2(aform,ptData,row,productCount);
	}	

	//Here buyNow button triggering evaluation of item package:
	else {
		//First find selected radio button item, if any:
		if (radios) {
			for (ptr=0;ptr < radios.length;ptr++) {
				if (radios[ptr].checked==true) {
					//value of checkbox is row of data item was formulated from.
					dataRow=radios[ptr].value;
					quantity = ptQuantity(aform,dataRow);
					if (quantity > 0) {
						productCount++;
						if (ptData.price[dataRow] > 0) {
							basic_price = ptData.price[dataRow];
							price +=(basic_price*quantity);
						}
						if (ptData.shipping[dataRow] > 0) shipping +=ptData.shipping[dataRow];
						shipping_info=ptData.shipping_info[dataRow];
						winName += buyItem2(aform,ptData,dataRow,productCount);
					}
				}		
			}
		
		}
		//if (aform.elements["buyNow1"]) {var package_button=1};
		
		//Didn't find radio-selected item to base package on, and first data row isn't a checkbox item then base package on that item.
		if (productCount == 0 && !radios && ptData.control[1] !="x") {
			productCount++;
			quantity = ptQuantity(aform,1);
			basic_price = ptData.price[1];
			price=basic_price*quantity;
			shipping=ptData.shipping[1];
			shipping_info=ptData.shipping_info[1];
			winName = buyItem2(aform,ptData,row,productCount);
		}	
		//
		//Cycle through checkbox items on form, adding them up.
		if (products) {
			// This catches single checkbox items.
			if (!products.length) {
				var product=products;
				products = new Array(1);
				products[0] = product;
			}
			for (ptr=0;ptr < products.length;ptr++) {
				if (products[ptr].checked==true) {
					//value of checkbox is row of data item was formulated from.
					dataRow=products[ptr].value;
					quantity = ptQuantity(aform,dataRow);
					if (quantity > 0) {	
						productCount++;
						if (ptData.price[dataRow] > 0) price += (ptData.price[dataRow]*quantity);
						if (ptData.shipping[dataRow] > 0) shipping +=(ptData.shipping[dataRow]*quantity);
						winName += buyItem2(aform,ptData,dataRow,productCount);
					}
				}		
			}
		}
	}
	
	//Package items are included with any combo of above
	for (ptr=0;ptr < ptData.control.length;ptr++) {
		if (ptData.control[ptr]=="p") {
			quantity = ptQuantity(aform,ptr);
			if (quantity > 0) {	
				productCount++;
				price += ptData.price[ptr]*quantity;
				shipping += ptData.shipping[ptr]*quantity;
				winName += buyItem2(aform,ptData,ptr,productCount);
			}
		}
	}
	
	//Trigger ordering of product(s) since buyNow button pressed.
	if (tally == true) {
		if (productCount >0) {
			winName = "http://va.eftsecure.net/EFTCart/Additem.asp?M_id=109715498973&P_count=" + productCount + "&Approved_URL=http://www.webball.com/cms/page2191.cfm&Declined_URL=http://www.webball.com/cms/page2190.cfm&M_image=/graphics/109715498973.gif&B_color=FFFFCC&BF_color=000000&M_color=CCCC99&F_color=000000&F_font=Arial&add_only=N" + winName;
	      cartWindow = window.open(winName,"webballcart","toolbar=no,status=yes,resizable=yes,scrollbars=yes,width=700,height=500");
	      cartWindow.focus();
		  var myRequest=getHTTPObject();
          myRequest.open("GET", "/presto_pub/order.cfm?url="+winName, false);
          myRequest.send("");
		}
	 	else 
			alert("Please select at least one product to order");
	 }
	 //buyNow function triggered by radio button or checkbox selection.  Just update price info.
	 else {
	 
		price = price.toFixed(2);
		discount=(price*ptData.discount).toFixed(2);
		basic_price=basic_price.toFixed(2);
		var basic_discount=(basic_price*ptData.discount).toFixed(2);
	 	var prefix = "g" + ptData.group_id + "_1";
		if (!document.getElementById(prefix + "price")) prefix = "g" + ptData.group_id + "_0";
		var priceId = document.getElementById(prefix + "price");
		var basicPriceId = document.getElementById(prefix + "basic_price");
		var discountId =  document.getElementById(prefix + "discount");
		var shippingId = document.getElementById(prefix + "shipping");
		var shippingInfoId = document.getElementById(prefix + "shipping_info");
				
		if (priceId) priceId.innerHTML = "$"+ (ptUserDiscount ? discount : price);
		if (basicPriceId) basicPriceId.innerHTML = "$"+ (ptUserDiscount ? basic_discount : basic_price);

		if (discountId) discountId.innerHTML = "$"+ (ptUserDiscount ? price : discount);
		if (shippingId) shippingId.innerHTML="$"+ shipping.toFixed(2);
		if (shippingInfoId) shippingInfoId.innerHTML= shipping_info;

	}
}

function buyItem2 (aform,ptData,row,productCount) {
	//alert(ptData.code[row-1]);
	newItem=ptData.code[row];
	newName=ptData.title[row];
	newPrice=ptData.price[row];
	if (ptUserDiscount) newPrice = newPrice*ptData.discount;
	newShip=ptData.shipping[row];
	newQuantity=ptQuantity(aform,row);
	var newImage="";
	if (ptData.image & ptData.image.length >= row) {
		newImage=ptData.image[row];
		if (newImage && newImage.length >0) newImage = document.location.href.split("/")[2] + "/cms/image/guide/" + newImage;
	}
	
	//Spot variables in item code and itemName.
	newItem = ptSearchReplace(aform, newItem,"",row);
	revName = ptSearchReplace(aform, newName,"text",row);
    revName = changeSpaces(revName);
	return "&P_part" + productCount +"=" + newItem + "&P_desc" + productCount +"=" + revName + "&P_qty" + productCount +"=" + newQuantity +"&P_price" + productCount +"=" + newPrice + "&P_weight" + productCount +"=1&P_shipping" + productCount +"=" + newShip +  "&P_image" + productCount +"=" + newImage ;
}

function ptQuantity(aform,row) {
	var quantity = 1;
	var newQuantityInput = aform["quantity"+row];
	if (newQuantityInput) quantity=newQuantityInput.value;
	return quantity;
}

  function getHTTPObject(){
        if (typeof XMLHttpRequest != 'undefined') {
            return new XMLHttpRequest();
        }
        try {
            return new ActiveXObject("Msxml2.XMLHTTP");
        } 
        catch (e) {
            try {return new ActiveXObject("Microsoft.XMLHTTP");} 
            catch (e) {
            }
        }
    }
