//THIS JAVASCRIPT PROGRAM IS PROTECTED BY COPYRIGHT LAW AND INTERNATIONAL TREATIES.
//UNAUTHORIZED REPRODUCTION OR DISTRIBUTION OF THIS PROGRAM, OR ANY PORTION OF IT,
//MAY RESULT IN SEVERE CIVIL AND CRIMINAL PENALTIES, AND WILL BE PROSECUTED TO THE
//MAXIMUM EXTENT POSSIBLE UNDER THE LAW.
//
//COPYRIGHT 2006 BY PRICEFLOOR.COM. ALL RIGHTS RESERVED.
//
var g_strBaseUrl            = document.location.protocol + '//' + location.hostname;// + '/pricefloor';
var g_blnShippingUpdated    = false;
var g_blnCouponDiscUpdated  = false;
var SHIPPING_DISCOUNT       = 1;
var ORDINARY_DISCOUNT       = 2;
var qform					= null;
var cform					= null;
var requestPriceForm		= null;

//PLEASE PAY ATTENTION THAT IF YOU MODIFY THE FOLLOWING VARIABLE
//YOU WILL ALSO NEED TO MODIFY THE SAME VARIABLE IN THE FOLLOWING
//FILES TOO:
//
//	COMMERCE/CART.ASP
//	ADIMN/ORDERDETAILS.ASP
//
var CALIFORNIA_TAX          = 8.25;

function getAbsoluteUrl(url) {return g_strBaseUrl + url;}
function isIE() {return (navigator.appName == "Microsoft Internet Explorer") ? true: false;}
function setInnerHtml(id, html) {document.getElementById(id).innerHTML = html;}
function setVisibility(id, status) {document.getElementById(id).style.visibility = status;}
function getInnerHtml(id) {return document.getElementById(id).innerHTML;}
function fix(number) {return (number < 0 ? -1 : 1) * parseInt(Math.abs(number));}
function getValue(currency) {return parseFloat(currency.toString().replace('\$', '').replace(',', ''));}
function isTaxObjectDefined() {return document.getElementById('objTax') != null ? true : false;}
function int(number) {return number > 0 ? Math.ceil(number) : Math.floor(number);}
function getNumericValue(number) {return isNaN(getValue(number)) ? 0 : getValue(number);}
function applyCoupon2() {applyCoupon();}
function calculateShipping2() {calculateShipping();}

function init()
{
	requestPriceForm = document.requestPrice;
	if(requestPriceForm)
	    requestPriceForm.elements['btnRequestPrice'].onclick = function(){ btnRequestPrice_onclick();};

	qform = document.qf;
	cform = document.cf;
	if(!qform || !cform)
		return;

    if(!isPurchaseListEmpty())
        checkForm();

    qform.elements['ApplyCoupon'].onclick = function(){ applyCoupon_onclick();};
    qform.elements['CalculateShipping'].onclick = function(){ calculateShipping_onclick();};
    cform.elements['ProceedToCheckout'].onclick = function(){ ProceedToCheckout_onclick();};

    //Since the area rug products doesn't have any components attached,
    //we need to make sure if there's already any button named CalculateSuggestedComponents
    //on screen, before adding the event listerner for the mentioned item.
    var elm = qform.elements['CalculateSuggestedComponents'];
    if(elm != null)
        elm.onclick = function(){ calculateSuggestedComponents_onclick();};
}

function getPrice(node, qty, pn)
{
	var root = document.getElementById('prmitm');
	if(!root.hasChildNodes())
		return null;

	var i, items = root.childNodes[0].getElementsByTagName('Item');
	for(i = 0; i < items.length; i++)
	{
		if(items[i].nodeType != 1 || items[i].getAttribute('ID') != pn)
			continue;

		var itemNode = items[i], prices = itemNode.childNodes[0];
		if(prices == null)
			throw new Error('Invalid Operation Exception!');

		var ourPrices = prices.getElementsByTagName('OurPrices');
		if(ourPrices.length != 1) 
			throw new Error('Invalid Operation Exception!');

		var price = 0, nodes = ourPrices[0].getElementsByTagName('OurPrice');
		for(i = 0; i < nodes.length; i++)
		{
			var sqft = nodes[i].getAttribute('sqft');
			price = nodes[i].firstChild.nodeValue;

			if(qty <= sqft)
				return nodes[i == 0 || qty == sqft ? i : i - 1].firstChild.nodeValue;
		}

		return price;
	}

	throw new Error('Invalid Operation Exception!');
}

function getXmlHttpRequestObject()
{
    var http_request = null;
    if(window.XMLHttpRequest)
    {
        http_request = new XMLHttpRequest();
        if(http_request.overrideMimeType)
            http_request.overrideMimeType('text/xml');
    }
    else if(window.ActiveXObject)
    {
        try
        {
            http_request = new ActiveXObject('Msxml2.XMLHTTP');
        }
        catch(e)
        {
            try
            {
                http_request = new ActiveXObject('Microsoft.XMLHTTP');
            }
            catch(e)
            {
            }
        }
    }

    return http_request;
}

function getXmlHttpRespSync(action, url, req)
{
    var http_request = getXmlHttpRequestObject();
    if(!http_request)
        return null;

    http_request.open(action, url, false);
    http_request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    http_request.send(req);
    if(http_request.readyState != 4 || http_request.status != 200 ||
        !http_request.responseXML || !http_request.responseXML.hasChildNodes())
        return null;

    return http_request.responseXML;
}

function isPurchaseListEmpty()
{
	var i;
	for(i = 0; i < qform.elements.length; i++)
	{
		if(qform.elements[i].type == 'checkbox' &&
			qform['add_' + qform.elements[i].id].checked)
			return false;
	}

	return true;
}

function getSelectedItemCount()
{
	var i, cbTotal = 0;
	for(i = 0; i < qform.elements.length; i++)
	{
		if(qform.elements[i].type == 'checkbox' &&
			qform['add_' + qform.elements[i].id].checked)
			cbTotal++;
	}

	return cbTotal;
}

function getPrimaryItemXmlNode(id)
{
	var i= 0, root = document.getElementById('prmitm');
	if(!root.hasChildNodes())
		return null;

	var nodes = root.childNodes[0].getElementsByTagName('Item');
	for(i = 0; i < nodes.length; i++)
		if(nodes[i].nodeType == 1 && nodes[i].getAttribute('ID') == id)
			return nodes[i];

	return null;
}

function formatCurrency(str)
{
	str = Math.round(str * 100) / 100;
	if(str == parseInt(str))
		str = '$' + str + '.00';
	else if(str * 10 % 1)
		str = '$' + str;
	else
		str = '$' + str + '0';

	if(str.length > 7)
		str = str.substring(0, str.length - 6) + ',' + str.substring(str.length - 6);

	return str;
}

function isNumeric(str)
{
	var strValidChars = "0123456789.-";
	var strChar, blnResult = true;
	if(str == null || str.length == 0)
		return false;

	for(i = 0; i < str.length && blnResult == true; i++)
	{
		strChar = str.charAt(i);
		if(strValidChars.indexOf(strChar) == -1)
			blnResult = false;
	}

	return blnResult;
}

function selectedInGroup(itype)
{
	var i;
	for(i = 0; i < qform.elements.length; i++)
	{
		if(qform.elements[i].type != "checkbox")
			continue;

		var id = 'add_' + qform.elements[i].id;
		if(qform[id].getAttribute('itype') == itype && qform[id].checked)
			return true;
	}

	return false;
}

function checkForm()
{
	if(!qform)
		return;

	var pn, i, type = -1, bPrimaryItem = true, fSum = 0;
	for(i = 0; i < qform.elements.length; i++)
	{
		if(qform.elements[i].type != "checkbox")
			continue;

		var strPartNo = qform.elements[i].id;

		//Make sure that every value entered either in quantity or coverage
		//edit boxes are numeric and greater than 0. If not, we'll blank the fields,
		//and also uncheck the item.
		var j, arr = new Array('qty_', 'cov_');
		for(j = 0; j < arr.length; j++)
		{
			if(qform[arr[j] + strPartNo].value == '0')
				qform['add_' + strPartNo].checked = false

			if(qform[arr[j] + strPartNo].value != '')
			{
				if(isNaN(qform[arr[j] + strPartNo].value))
					qform[arr[j] + strPartNo].value = '';
				else
				{
					if(parseInt(qform[arr[j] + strPartNo].value) <= 0)
						qform[arr[j] + strPartNo].value = '';
				}
			}
		}
		
		//Make sure that the primary item is one of those items
		//already selected. If not, we'll select it automatically.
		if((qform.id == 'Laminate' || qform.id == 'Hardwood') &&  bPrimaryItem)
		{
			if(!isPurchaseListEmpty())
				qform['add_' + strPartNo].checked = true;
			pn = strPartNo;
			bPrimaryItem = false;
		}

		var node = getPrimaryItemXmlNode(strPartNo);
		if(node == null)
			continue;

		var ratio = node.getAttribute('Ratio');
		if(!qform['add_' + strPartNo].checked)
		{
			//Replace the current coverage value with an edit box
			if(ratio != 1)
			{
				if(isIE())
					setInnerHtml('covtxt_' + strPartNo, "<input size='5' onblur='checkForm()' value='" + qform['cov_' + strPartNo].value + "' name='cov_" + strPartNo + "'>");
				else
					qform['cov_' + strPartNo].disabled = false;
			}

			var st = getInnerHtml('subtotal_' + strPartNo);
			if(st != null && st.length > 0)
			{
				if(!selectedInGroup(qform['add_' + strPartNo].getAttribute('itype')))
					setInnerHtml('subtotal_' + qform['add_' + strPartNo].getAttribute('itype'), formatCurrency(0));

				setInnerHtml('subtotal_' + strPartNo, '');
				qform['cov_' + strPartNo].value = '';
				qform['qty_' + strPartNo].value = '';
				continue;
			}

			setInnerHtml('subtotal_' + strPartNo, '');
			if((qform['cov_' + strPartNo].value != '') || (qform['qty_' + strPartNo].value != ''))
				qform['add_' + strPartNo].checked = true;
			else
				continue;
		}
		else if((qform['qty_' + strPartNo].value == '') && (qform['cov_' + strPartNo].value == ''))
			qform['qty_' + strPartNo].value = 1;

		var qty, cov;
		if(isNumeric(qform['qty_' + strPartNo].value))
		{
			qty = int(qform['qty_' + strPartNo].value);
			cov = Math.round(ratio * qform['qty_' + strPartNo].value * 100) / 100;
		}
		else if(isNumeric(qform['cov_' + strPartNo].value))
		{
			var lngQuantity = -int(-qform['cov_' + strPartNo].value / ratio);
			qty = int(lngQuantity);
			cov = Math.round(lngQuantity * node.getAttribute("Ratio") * 100) / 100;
		}
		else
		{
			cov = ratio;
			qty = 1;
		}
		
		qform['cov_' + strPartNo].value = cov;
		qform['qty_' + strPartNo].value = qty;

		if(ratio == 1)
		{
			if(isIE())
				setInnerHtml('covtxt_' + strPartNo, "<input type='hidden' size='5' name='cov_" + strPartNo + "'>");
			else
				qform['cov_' + strPartNo].disabled = true;
		}
		else
		{
			if(isIE())
				setInnerHtml('covtxt_' + strPartNo, "<input type='hidden' size='5' name='cov_" + strPartNo + "'>" + cov);
			else
				qform['cov_' + strPartNo].disabled = true;
		}

		//calculate subtotal of each row...
		var dblSubtotal = 0;
		if(qform.id == 'Laminate' || qform.id == 'Hardwood')
		{
			var unitPrice = (node.getAttribute('ID') != pn) ? node.getAttribute('Price') : getPrice(node, cov, pn);
			
			var price = fix(unitPrice * ratio * 100) / 100.0;
			dblSubtotal = price * qty;
		}
		else if(qform.id == 'Area rug')
			dblSubtotal = node.getAttribute('OurPrice') * qty;

		//calculate the subtotal of items in the same group...
		var itype = qform['add_' + strPartNo].getAttribute('itype');
		if(type == -1 || type != itype)
		{
			type = itype;
			setInnerHtml('subtotal_' + itype, formatCurrency(0));
		}

		setInnerHtml('subtotal_' + itype, formatCurrency(getValue(getInnerHtml('subtotal_' + itype)) + dblSubtotal));
		setInnerHtml('subtotal_' + strPartNo, formatCurrency(dblSubtotal));
		fSum += getValue(formatCurrency(dblSubtotal));
	}

	//Display the subtotal of selected products
	setInnerHtml('subtotal', formatCurrency(fSum));

	updateGrandTotal();
	g_blnShippingUpdated = g_blnCouponDiscUpdated = false;

	//Make sure that the primary item is already selected
	//for laminate and hardwood products, only.
	if((qform.id == 'Laminate' || qform.id == 'Hardwood') &&
		(getSelectedItemCount() > 0 && !qform['add_' + qform.sku.value].checked))
	{
		qform['qty_' + qform.sku.value].value = 1;
		checkForm();
	}
	else
	{
		var dblDiscount = 0;
		if(!isPurchaseListEmpty())
		{
			var disc = new Object();
			if(getDiscount(disc))
				dblDiscount = disc.value;
		}
		else
		{
			reassignCoupon();
			reassignZipcode();
		}

		setInnerHtml('objDiscount', formatCurrency(dblDiscount));
		updateGrandTotal();
	}
}

function getAutoOrdinaryDiscount(dblDiscount)
{
	var root = document.getElementById('discounts'); dblDiscount.value = 0;
	if(!root.hasChildNodes())
		return false;

	//Is this eligible for automatic ordinary discount?
	var nodes = root.childNodes[0].getElementsByTagName('Item');
	if(nodes.length == 0)
		return false;

	//Search for the best match in ordinary discounts collection
	var i, node = null, dblSubTotal = getValue((getInnerHtml('subtotal')));
	for(i = 0; i < nodes.length; i++)
	{
		var dblMinOrder = parseFloat(nodes[i].getAttribute('MinOrderLimit'));
		if(dblSubTotal >= dblMinOrder)
			node = nodes[i];
	}

	if(node == null || node.getAttribute('ODT') == null)
		return false;

	//Ordinary Discount Type
	switch(node.getAttribute('ODT').toLowerCase())
	{
		case 'usd':
			dblDiscount.value = formatCurrency(getValue(node.getAttribute('ODP')));
			break;

		case 'percent':
			dblDiscount.value = formatCurrency(dblSubTotal * getValue(node.getAttribute('ODP')) / 100);
			break;

		default:
			return false;
	}

	dblDiscount.value = getValue(dblDiscount.value);
	return true;
}

function getAutoShippingDiscount(dblPrice)
{
	var root = document.getElementById('discounts'); dblPrice.value = 0;
	if(!root.hasChildNodes())
		return false;

	//Is this eligible for automatic ordinary discount?
	var nodes = root.childNodes[0].getElementsByTagName('Item');
	if(nodes.length == 0)
		return false;
		
	//Search for the best match in ordinary discounts collection
	var i, node = null, dblSubTotal = getValue((getInnerHtml('subtotal')));
	for(i = 0; i < nodes.length; i++)
	{
		var dblMinOrder = parseFloat(nodes[i].getAttribute('MinOrderLimit'));
		if(dblSubTotal >= dblMinOrder)
			node = nodes[i];
	}
	
	if(node == null || node.getAttribute('ShippingPrice') == null)
		return false;
		
    dblPrice.value = getValue(node.getAttribute('ShippingPrice'));
	return true;
}

function CouponInfo(intDiscountType, dblDiscount, dblShippingPrice, dblMinOrderLimit)
{
    this.intDiscountType    = intDiscountType;
	this.dblDiscount        = dblDiscount;
	this.dblShippingPrice   = dblShippingPrice;
	this.dblMinOrderLimit   = dblMinOrderLimit;
}

function getCouponInfo(info, errmsg)
{
	errmsg.value = "Sorry for your inconvenience!<br>We're unable to process your request at the moment because of a catastrophic failure that's already occured.";
	if(qform.coupon_code.value == null ||
	    qform.coupon_code.length == 0)
	    return false;

    var req = "<Request Code='" + qform.coupon_code.value + "' SubID='" + qform.subid.value + "'></Request>";
    var xml = getXmlHttpRespSync('POST', getAbsoluteUrl('/include/svcs/coupon.asp'), req);
    if(!xml)
        return false;

    var root = xml.childNodes[0];
    var nodes = root.getElementsByTagName('CouponSpec');
    if(!nodes || nodes.length == 0)
        return false;

    var node = nodes[0];
	if(node.getAttribute('ErrStatus') != '0')
	{
		errmsg.value = node.getAttribute('ErrDesc');
		return false;
	}
	
	info.dblMinOrderLimit = getValue(node.getAttribute('MinimumOrderLimit'));

	var dblSubtotal = getValue(getInnerHtml('subtotal'));
	if(dblSubtotal < info.dblMinOrderLimit)
	{
		errmsg.value = "You can take advantage of our discount if you shop at least <b>" + formatCurrency(info.dblMinOrderLimit) + "</b> of above products.";
	    return false;
    }

	info.intDiscountType = 0;
	var od = node.getAttribute('OrdinaryDiscount');
	if(od != null && !isNaN(od))
	{
		if(int(node.getAttribute('OrdinaryDiscountType')) == 0)
			info.dblDiscount = (dblSubtotal * node.getAttribute('OrdinaryDiscount')) / 100;
		else
			info.dblDiscount = getValue(node.getAttribute('OrdinaryDiscount'));
		info.intDiscountType |= ORDINARY_DISCOUNT;
	}

	var price = node.getAttribute('ShippingPrice');
	if(price != null && !isNaN(getValue(price)))
	{
		info.dblShippingPrice = getValue(price);
		info.intDiscountType |= SHIPPING_DISCOUNT;
	}

	return true;
}

function getTotalWeights()
{
	var i= 0, root = document.getElementById('prmitm');
	if(!root.hasChildNodes())
		return 0;

	var nodes = root.childNodes[0].getElementsByTagName('Item');
	if(nodes.length == 0)
	    return 0;

    var node = nodes[0], weight = 0;
    var pn = node.getAttribute('ID');
    var qty = qform['qty_' + pn].value;
    if(qty != null && qty.length > 0)
    {
        if(!isNumeric(qty))
        {
		    checkForm();
            if(isNumeric(qform['qty_' + pn].value))
		        qty = qform['qty_' + pn].value;
        }
    }
    else
        qty = 0;

    weight = fix(getValue(node.getAttribute('Weight')) * getValue(qty));
    return (weight <= 1) ? 2 : weight;
}

function getShippingDiscount(dblShippingPrice)
{
	//Automatic discount over shipping?
	var bAutoDisc = false, bRet = false;
	if(getAutoShippingDiscount(dblShippingPrice))
		bAutoDisc = bRet = true;

	//Coupon discount over shipping?
	if(qform.coupon_code.value != null && qform.coupon_code.value.length > 0)
	{
	    var ci = new Object(), errmsg = new Object();
	    if(getCouponInfo(ci, errmsg))
	    {
			if((ci.intDiscountType & SHIPPING_DISCOUNT) != 0)
	    	{
			    if(!bAutoDisc || (bAutoDisc && (ci.dblShippingPrice < dblShippingPrice.value)))
			    {
				    dblShippingPrice.value = ci.dblShippingPrice;
				    bRet = true;
			    }
			}
		}
    }

    return bRet;
}

function calculateShipping_onclick()
{
	if(qform.zipcode.value == null || qform.zipcode.value.length == 0)
	    setInnerHtml('objShippingStatus', "<font color='red'>Please enter your zip code to proceed!</font>");
	else if(isPurchaseListEmpty())
	    setInnerHtml('objShippingStatus', "<font color='red'>Would you please mark your required items above before calculating their shipping prices?!</font>");
	else
	{
		qform.CalculateShipping.disabled = true;
		setInnerHtml('objShippingStatus', "<font color='red'>Please wait... We're calculating your shipping cost.</font>");
		window.setTimeout("calculateShipping();", 200, 'javascript');
	}
}

function calculateShipping()
{
    var lngTotalWeight = getTotalWeights(), si = new ShippingInfo(), errmsg = new Object();
    if(!getShippingInfo(lngTotalWeight, qform.zipcode.value, si, errmsg))
    {
        setInnerHtml('objShpOptionSec1', errmsg.value + "<p><span id='objShippingStatus'></span></p>");
		qform.CalculateShipping.disabled = false;
		return false;
    }

	//Does any discount apply to this package?
	var dblDiscPrice = new Object(), dblPrice = si.dblPrice;
	if(getShippingDiscount(dblDiscPrice))
	{
		//Make sure that the discounted price is lower than the actual price
		if(dblDiscPrice.value < si.dblPrice)
		    dblPrice = dblDiscPrice.value;
	}
	
	//Does the discount over shipping by state apply to this package?
	var dblSubTotal = getValue(getInnerHtml('subtotal'));
	var dblDiscountByStatePercentage = getDiscountOverShippingByState(qform.subid.value, si.strDestRegion, dblSubTotal);
	if(dblDiscountByStatePercentage > 0)
	{
		dblPrice -= ((dblDiscountByStatePercentage * dblSubTotal) / 100.0);
		if(dblPrice < 0)
		    dblPrice = 0;
    }
    
    var strRes = "<span class='content' style='font-size:8pt;'>Shipping Dest.: " + qform.zipcode.value + ", " + si.strDestRegion + "<br>Total Weight: " + lngTotalWeight + "&nbsp;lbs<br><a style='font-size:8pt;' class='content' href=\"javascript:void('')\" onclick='javascript:reassignZipcode()'>[Change zipcode]</a> - <a style='font-size:8pt;' class='content' href=\"javascript:void('')\" onclick='javascript:calculateShipping2()'>[Update Shipping Price]</a><p>The shipping price has been successfully calculated. You may change any neccessary modifications to the zipcode above or update the shipping price on demand.</p></span>";
    setInnerHtml('objShippingPrice', formatCurrency(dblPrice));
    setVisibility('objShpOptionSec2', 'hidden');
    setInnerHtml('objShpOptionSec1', strRes + "<p><span id='objShippingStatus'></span></p>");
	qform.CalculateShipping.disabled = false;

    if(isTaxObjectDefined())
    {
        var lngTax = 0;
        if(si.strDestRegion.toUpperCase() == 'CA')
        {
		    var lngSubtotal = getValue(getInnerHtml('subtotal'));
		    lngTax = parseFloat(CALIFORNIA_TAX) * lngSubtotal / 100.0;
	    }

        setInnerHtml('objTax', formatCurrency(lngTax));
    }

	updateGrandTotal();
	g_blnShippingUpdated = true;
	return true;
}

function ShippingInfo(dblPrice, strDestRegion)
{
    this.dblPrice = dblPrice;
    this.strDestRegion = strDestRegion;
}

function getShippingInfo(weight, zipcode, si, errmsg)
{
	errmsg.value = "Sorry for your inconvenience!<br>We're unable to process your request at the moment because of a catastrophic failure that's already occured.";
    if(zipcode == null || zipcode.length == 0 || weight <= 1)
        return false;

    var req = "<Request Zipcode='" + zipcode + "' " + "Weight='" + weight + "'></Request>";
    var xml = getXmlHttpRespSync('POST', getAbsoluteUrl('/include/svcs/shipping.asp'), req);
    if(!xml)
        return false;

    var root = xml.childNodes[0];
    var nodes = root.getElementsByTagName('ShippingInfo');
    if(!nodes || nodes.length == 0)
        return false;

    var node = nodes[0];
	if(node.getAttribute('ErrStatus') != '0')
	{
		errmsg.value = node.getAttribute('ErrDesc');
		return false;
	}

	si.dblPrice	= node.getAttribute('StandardGroundTotal');
	si.strDestRegion = node.getAttribute('Region');
	return true;
}

function updateGrandTotal()
{
    var lngSubtotal	= getNumericValue(getInnerHtml('subtotal'));
    var lngShipping	= getNumericValue(getInnerHtml('objShippingPrice'));
	var lngDiscount	= getNumericValue(getInnerHtml('objDiscount'));
    var lngTax = isTaxObjectDefined() ? getValue(getInnerHtml('objTax')) : 0;
	setInnerHtml('objGrandTotal', formatCurrency(lngTax + lngSubtotal + lngShipping - lngDiscount));
}

function reassignZipcode()
{
    setInnerHtml('objShpOptionSec1', "Enter your shipping postal/zip code so we can calculate your shipping options.<p><span id='objShippingStatus'></span></p>");
    setVisibility('objShpOptionSec2', 'visible');
    setInnerHtml('objShippingPrice', formatCurrency(0));
	updateGrandTotal();
	qform.CalculateShipping.disabled = false;
	//qform.zipcode.focus();
}

function reassignCoupon()
{
    setInnerHtml('objCouponSec1', "Enter your Membership Number so that you can take advantage of our discounts.<p><span id='objCouponStatus'></span></p>");
    setVisibility('objCouponSec2', 'visible');
	qform.ApplyCoupon.disabled = false;
	//qform.coupon_code.focus();

    qform.coupon_code.value = '';
    var dblDiscount = new Object();
    if(!getDiscount(dblDiscount))
        dblDiscount.value = 0;

    setInnerHtml('objDiscount', formatCurrency(dblDiscount.value));
	if(qform.zipcode.value != null && qform.zipcode.value.length > 0)
	    calculateShipping();

	updateGrandTotal();
}

function applyCoupon_onclick()
{
    if(qform.coupon_code.value == null || qform.coupon_code.value.length == 0)
        setInnerHtml('objCouponStatus', "<font color='red'>Please enter your Contractor Membership Number to proceed!</font>");
    else if(isPurchaseListEmpty())
        setInnerHtml('objCouponStatus', "<font color='red'>Would you please mark your required items above before entering your Contractor Membership Number?!</font>");
	else
	{
		qform.ApplyCoupon.disabled = true;
		setInnerHtml('objCouponStatus', "<font color='red'>Validating your Membership Number, please wait...</font>");
		window.setTimeout('applyCoupon();', 200, 'javascript');
	}
}

function getDiscount(dblDiscount)
{
	//Automatic discount?
	var bAutoDisc = false, bRet = false;
	if(getAutoOrdinaryDiscount(dblDiscount))
		bAutoDisc = bRet = true;
		
	//Coupon discount?
	if(qform.coupon_code.value != null && qform.coupon_code.value.length > 0)
	{
	    var ci = new Object(), errmsg = new Object();
	    if(getCouponInfo(ci, errmsg) && ((ci.intDiscountType & ORDINARY_DISCOUNT) != 0))
		    if(!bAutoDisc || (bAutoDisc && (ci.dblDiscount < dblDiscount.value)))
		    {
			    dblDiscount.value = ci.dblDiscount;
			    bRet = true;
		    }
    }

    return bRet;
}

function applyCoupon()
{
	g_blnCouponDiscUpdated = true;
	var ci = new Object(), errmsg = new Object();
	if(!getCouponInfo(ci, errmsg))
	{
	    setInnerHtml('objCouponSec1', "<span class='content' style='font-size:8pt;'>" + errmsg.value + "<p><span id='objCouponStatus'></span></p></span>");
		qform.ApplyCoupon.disabled = false;
		return false;
	}

	var dblDiscount = new Object(); dblDiscount.value = 0;
	if((ci.intDiscountType & ORDINARY_DISCOUNT) != 0)
	{
	    if(getAutoOrdinaryDiscount(dblDiscount))
	    {
			if(dblDiscount.value < ci.dblDiscount)
				dblDiscount.value = ci.dblDiscount;
	    }
	    else
	        dblDiscount.value = ci.dblDiscount;
	}
	
	if((ci.intDiscountType & SHIPPING_DISCOUNT) != 0 && 
	    qform.zipcode.value != null && qform.zipcode.value.length > 0)
	{
		calculateShipping();
	}

	var strRes = "Coupon code successfully applied.<br>" + "<a class='content' style='font-size:8pt;' href=\"javascript:void('')\" onclick='javascript:reassignCoupon();'>[Change Coupon Code]</a> - <a style='font-size:8pt;' class='content' href=\"javascript:void('')\" onclick='javascript:applyCoupon2();'>[Update Discounts]</a><p></p>";
	setInnerHtml('objCouponSec1', "<span class='content' style='font-size:8pt;'>" + strRes + "<p><span id='objCouponStatus'></span></p></span>");
	setVisibility('objCouponSec2', 'hidden');
	setInnerHtml('objDiscount', formatCurrency(dblDiscount.value));
	qform.ApplyCoupon.disabled = false;
	updateGrandTotal();
	return true;
}

function getDiscountOverShippingByState(lngSubID, strState, dblSubtotal)
{
    var req = "<Request SubTotal='" + dblSubtotal + "' SubID='" + lngSubID + "' State='" + strState + "'></Request>";
    var xml = getXmlHttpRespSync('POST', getAbsoluteUrl('/include/svcs/discountbystate.asp'), req);
    if(!xml)
        return 0;
        
    var root = xml.childNodes[0];
    var nodes = root.getElementsByTagName('DiscountOverShippingByState');
    if(!nodes || nodes.length == 0)
        return false;

    var node = nodes[0];
	if(node.getAttribute('ErrStatus') != '0')
		return 0;

	return getNumericValue(node.getAttribute('DiscountPercentage'));
}

function calculateSuggestedComponents_onclick()
{
	//Area rug products do not have any components attached
	if(qform.id != 'Laminate' && qform.id != 'Hardwood')
	    return;

	if(isPurchaseListEmpty())
	    return;

	//Update the form since user might forget to press the calculate
	//button before calculating the suggested components
	checkForm();

    var i, lngQuantity = 0, bCheckForm = false;
    for(i = 0; i < qform.elements.length; i++)
    {
		if(qform.elements[i].type != "checkbox")
		    continue;
		    
		var strPartNo = qform.elements[i].id;
		var node = getPrimaryItemXmlNode(strPartNo);
		if(node == null)
			continue;

		var dblRecommendedValue = node.getAttribute('RecommendedValue');
		if(dblRecommendedValue == null)
		{
			lngQuantity = qform['qty_' + strPartNo].value;
			if(lngQuantity == '')
			    break;
		}
		else if(dblRecommendedValue != 0 && lngQuantity != 0)
		{
		    qform['qty_' + strPartNo].value = -int(-lngQuantity * dblRecommendedValue);
            bCheckForm = true;
        }
    }

	if(bCheckForm)
	    checkForm();
}

function createHiddenField(strName, strValue)
{
	var elm = document.createElement('input');
	elm.name = strName;
	elm.type = 'hidden';
	elm.value = strValue;
	document.getElementById('oCheckoutForm').appendChild(elm);
}

function btnRequestPrice_onclick()
{
	var sqft = requestPriceForm['requiredSqft'].value;
	if(sqft == null || sqft.length == 0 || isNaN(sqft))
	{
		alert('Please enter the required sq.ft in the provided text box.');
		return;
	}

	var zipCode = requestPriceForm['requestedShippingZipCode'].value;
	if(zipCode == null || zipCode.length == 0)
	{
		alert('Please enter your zip code in the space provided.');
		return;
	}

	var email = requestPriceForm['requestedEmail'].value, filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	if (!filter.test(email)) 
	{
		alert('Please enter your email address in the space provided.');
		return;
	}

	requestPriceForm.submit();
}

function ProceedToCheckout_onclick()
{
	if(isPurchaseListEmpty())
	    return;

	if(qform.zipcode.value == null || qform.zipcode.value.length == 0)
	{
		alert("Please calculate your shipping prices before going on. Enter your zipcode in the space provided and press the \"Calculate Shipping\" button to continue.\r\n\r\nThis will also apply any \"Shipping Discount\" you might get on this product.");
		return;
	}
	
	if(!g_blnShippingUpdated)
	{
		if(!confirm("The shipping price is not still updated! You need to calculate shipping prices\r\nbefore going on. Would you like to do this now?"))
		    return;

		if(!calculateShipping())
		{
			alert("Sorry for your inconvenience!\r\n\r\nWe are unable to calculate your shipping prices at the moment!\r\nPlease contact our support staff to let you know how to place your order.");
			return;
		}
		
	    if(!confirm("The shipping price of the total products you already selected on this page is " + getInnerHtml('objShippingPrice') + ". Would you like to proceed to checkout now?"))
	        return;
    }
    
	if(qform.coupon_code.value != null && qform.coupon_code.value.length > 0 && !g_blnCouponDiscUpdated)
	{
	    if(!confirm("You need to update items' discounts before going on. Would you like to do so now?"))
	        return;

        var msg;
		if(applyCoupon())
		    msg = "We've successfully applied your coupon code. Would you like to proceed to checkout now?";
		else
		    msg = "Sorry for your inconvenience!\r\n\r\nWe are unable to apply the coupon code at the moment! However, you could still continue shopping without applying the coupon code. Would you like to do so?";

        if(!confirm(msg))
            return;
	}

	var url = document.location.href.toString();
	if(url.indexOf("page=name_your_own_price") > 0)
	{
		var nyop = parseInt(document.getElementById('nyop').value, 10);
		if(isNaN(nyop))
		{
			alert('Your offer does not seem to be a valid numeric value! Please name your own price\r\nin the space provided before proceeding to checkout!');
			return false;
		}
		
		var grandTotal = getValue(getInnerHtml('objGrandTotal'));
		var validPrice = grandTotal - getValue(formatCurrency(grandTotal * 25 / 100.0));
		if(nyop <= 0 || nyop <= validPrice)
		{
			alert('Please increase your offer, your offer seems to be so low!');
			return false;
		}
	}

	//Create hidden fields to be submitted to the cart.
	var i; setInnerHtml('oCheckoutForm', '');
	for(i = 0; i < qform.elements.length; i++)
		if(qform.elements[i].type == "checkbox")
		{
			var strPartNo = qform.elements[i].id;
			if(qform['add_' + strPartNo].checked)
			{
				createHiddenField('pn', strPartNo);
				createHiddenField('qty_' + strPartNo, qform['qty_' + strPartNo].value);
			}
		}

	createHiddenField('sku', qform.sku.value);
	createHiddenField('cat', qform.id.toLowerCase());
	createHiddenField('zipcode', qform.zipcode.value.toLowerCase());
	createHiddenField('coupon', qform.coupon_code.value == null ? '' : qform.coupon_code.value.toLowerCase());
	cform.submit();
}
