var MAXSWATCHES;

function reSortCtgProd(theForm, sortField, theContainer, theUrl)
{
	var page = "";
	if (theUrl.length > 0)
	{
		if (theUrl.toUpperCase().indexOf("FEATURE") > 0)
			page = "Featured"
		if (theUrl.toUpperCase().indexOf("BRAND") > 0)
			page = "Brand"
			
	/*	the is for SBProduct.asp	
		if (theUrl.toUpperCase().indexOf("SBPRODUCT") > 0)
		{
			if (theForm.pagetype.value.toLowerCase() == "shopbyfeature" )
				page = "Featured";
			if (theForm.pagetype.value.toLowerCase() == "shopbybrand")
				page = "Brand";
		}
	*/
	}
	var params = getCtgSortParams(theForm, sortField, page);
	ajaxPostFunction( theUrl, params, theContainer );
}


function getCtgSortParams(theForm, sortField, page)
{
//	alert(page);
	var params = "";
	theForm.sort_order.value = sortField;
	if (theForm.sort_brand != undefined || page != "Featured")
		params += "sort_brand=" + theForm.sort_brand.value;
	
	if (theForm.sortStyle != undefined) {
		if (params != "" )
			params += "&";
		params += "sortStyle=" + theForm.sortStyle.value;
	}
		
	if (theForm.sortStyle2 != undefined)
		params += "&sortStyle2=" + theForm.sortStyle2.value;
	if (theForm.sortStyle3 != undefined)
		params += "&sortStyle3=" + theForm.sortStyle3.value;
	
	if (params != "")
		params += "&";
	params += "sort_order=" + theForm.sort_order.value;
	
	if (page=="Brand" || page=="Featured")
	{
	//	params += "&pagetype=" + theForm.pagetype.value;   // this is for sort by SBProduct.asp
		params += "&sort_product=" + theForm.sort_product.value;
		if (theForm.featurename != undefined)
			params += "&featurename=" + theForm.featurename.value;
		if (theForm.featureid != undefined)
			params += "&featureid=" + theForm.featureid.value;
	}
	if (theForm.productSelect != undefined)
		params += "&productSelect=" + theForm.productSelect.value;
	if (theForm.dept_id != undefined) 
		params += "&dept_id=" + theForm.dept_id.value;
	if (theForm.feature != undefined)
		params += "&feature=" + theForm.feature.value;
	if (theForm.isProperty != undefined)
		params += "&isProperty=" + theForm.isProperty.value;
	params += "&pw=" + theForm.pw.value;
	params += "&pwf=" + theForm.pwf.value;
	params += "&ph=" + theForm.ph.value;
	params += "&phf=" + theForm.phf.value;
	if (theForm.date != undefined)
		params += "&date=" + theForm.date.value;
	return params;
}


function ajaxPostFunction( url, parameters, elementId )
{
	var xmlHttp = getXmlHttpObj();

	if ( xmlHttp == null ) {
		return false;

	} else {
		xmlHttp.onreadystatechange = function()
	    {
			if ( xmlHttp.readyState == 4 || xmlHttp.readyState == 'complete' ) {
				handleReturn( xmlHttp.responseText, url, elementId );
				// DEBUG	alert( xmlHttp.responseText );
			}
		}
	    xmlHttp.open( "POST", url, true );
		xmlHttp.setRequestHeader( "Content-type", "application/x-www-form-urlencoded" );
	    xmlHttp.setRequestHeader( "Content-length", parameters.length );
    	xmlHttp.setRequestHeader( "Connection", "close" );
	    xmlHttp.send( parameters );
	}
	// DEBUG	prompt( 'AJAX Post for "'+ elementId +'"', url +'?'+ parameters );
}


function handleReturn( response, url, id )
{
	if ( url.toLowerCase().indexOf("addswatchtocart") >= 0 ) {
		returnToSwatchPopup( response, id );

	} else if ( url.toLowerCase().indexOf("windowproduct") >= 0 ) {
		wpAJAX( response, id );

	} else {
		document.getElementById(id).innerHTML = response;
	}
}


function ajaxGetSEOData(url)
{
	var xmlHttp = getXmlHttpObj();
	if (xmlHttp == null)
		return false;
	xmlHttp.onreadystatechange=function()
	{
		if (xmlHttp.readyState==4 || xmlHttp.readyState == 'complete')
		{
			var tmpUrl = url.toUpperCase();
			if (tmpUrl.indexOf("SECTION") >= 0 )
				dispalySectionData(xmlHttp.responseText);
			else if (tmpUrl.indexOf("SHOPBYBRAND") >= 0 )
				displayBrandData(xmlHttp.responseText);
			else if (tmpUrl.indexOf("BRANDCATEGORY") >= 0 )
				displayBrandProdListData(xmlHttp.responseText);
			else
				displayData(xmlHttp.responseText);
		}
	}

	xmlHttp.open('GET', url, true);
	xmlHttp.send(null);
}


function getXmlHttpObj()
{
	var xmlHttp;

	try {																			// FireFox
		xmlHttp = new XMLHttpRequest();
	}
	catch (e) {																		// Internet Explorer
		try {
			xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
		}
		catch (e) {  
			try {
				xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
			}
			catch (e) {
				//	alert("Your browser does not support AJAX HTTP");
				return null;
			}
		}
	}
	return xmlHttp;
}


function loadXml( text )
{
	if ( !text || text == '' ) {
		return false;

	} else {
		try {																		// FireFox
			var xmlParser = new DOMParser();
			return xmlParser.parseFromString( text, 'text/xml' );
		}
		catch (e) {																	// Internet Explorer
			try {
				var xmlDom;
				xmlDom = new ActiveXObject("Microsoft.XMLDOM");
				xmlDom.async = false;
				xmlDom.loadXML( text );
				return xmlDom;
			}
			catch (e) {
				//	alert("Your browser does not support AJAX DOM");
				return false;
			}
		}
	}
}


function ajaxGetTaxShipping(url, whichOne)
{
	var xmlHttp = getXmlHttpObj();
	if (xmlHttp == null)
		return false;	
	var val;
	xmlHttp.onreadystatechange=function()
    {
      if(xmlHttp.readyState==4 || xmlHttp.readyState == 'complete')
	  {
		//  	document.getElementById('shipcost').innerHTML = xmlHttp.responseText;
		    var responseStr =  xmlHttp.responseText;
			updateTaxShippingCost(responseStr, whichOne);
		}
	}
	xmlHttp.open('GET', url, true);
	xmlHttp.send(null);
}


function ajaxReCalculatePrices(url)
{
	var xmlHttp = getXmlHttpObj();
	if (xmlHttp == null)
		return false;	
	var val;
	xmlHttp.onreadystatechange=function()
    {
      if(xmlHttp.readyState==4 || xmlHttp.readyState == 'complete')
	  {
		//  	document.getElementById('shipcost').innerHTML = xmlHttp.responseText;
		    var responseStr =  xmlHttp.responseText;
			updatePrices(responseStr);
		}
	}
	xmlHttp.open('GET', url, true);
	xmlHttp.send(null);
}

function updatePrices(responseStr)
{
	var priceArr = responseStr.split("|");
	var priceTax = document.getElementsByName("priceTax");
	priceTax[0].value = priceArr[0];
	
	var priceShipping = document.getElementsByName("priceShipping");
	priceShipping[0].value = priceArr[1];
	
	var priceTotal = document.getElementsByName("priceTotalTotal");
	priceTotal[0].value = priceArr[2];
}


function updateTaxShippingCost(responseStr, whichOne)
{
	var priceSubtotal = document.getElementsByName("priceSubtotal");
	var subTotal = priceSubtotal[0].value;
	
	var priceTax = document.getElementsByName("priceTax");
	var tax =  priceTax[0].value;

	if (whichOne == "tax")
	{
		 priceTax[0].value = responseStr;
		 tax = responseStr;
	}
	
	var priceShipping = document.getElementsByName("priceShipping");
	var shipping = priceShipping[0].value;
	if (whichOne == "shipping")
	{
		 priceShipping[0].value = responseStr;
		 shipping = responseStr;
	}
		
	var priceHandling = document.getElementsByName("priceHandling");
	var handling = priceHandling[0].value;
	
	var priceTotal = document.getElementsByName("priceTotalTotal");
	var total = priceTotal[0].value;
	
	total= parseFloat(subTotal.replace("$", "")) +  parseFloat(tax.replace("$", "")) +  parseFloat(shipping.replace("$", "")) + parseFloat(handling.replace("$", ""));

	priceTotal[0].value = parseFloat(total);
}

function returnToSwatchPopup(returnMsg, elmId)
{
//alert(returnMsg);
	var msgs = returnMsg.split("|");
	var additionalMsg;
	document.getElementById(elmId).style.display = "block";
		document.domain = "blindsgalore.com";						// force the domain same as the parent	
	if (msgs.length == 4) {													// case of swatch_popup
		if (msgs[2] > 1)
				additionalMsg = " (" + msgs[2] + " swatches in cart)";
			else
				additionalMsg = " (" + msgs[2] + " swatch in cart)";
				
		if (msgs[1] == "success") {
			document.getElementById(elmId).style.display = "block";
			document.getElementById(elmId).className = "successmsg";
			document.getElementById(elmId).innerHTML = msgs[0] + additionalMsg;
			updateParentWindow("success", msgs[2], msgs[3], elmId, msgs[0]);
		}
		else if (msgs[1] == "warning") {
			document.getElementById(elmId).style.display = "block";
			document.getElementById(elmId).className = "warningmsg";
			document.getElementById(elmId).innerHTML = msgs[0];
			if (msgs[2] == MAXSWATCHES) {
				document.getElementById("addcartbtn").className = "btndisable";
				maxSwatch = true;
				updateParentWindow("warning", msgs[2], msgs[3], elmId, msgs[0]);
			}
			else {
				document.getElementById("addcartbtn").className = "btnenable";
				maxSwatch = false;
			}
		}
		else  {
			document.getElementById(elmId).className = "errormsg";
			document.getElementById(elmId).innerHTML = msgs[0];
		}
	}
	else if ( msgs.length == 5) {								// case of product_detail
		var	swatchSku = msgs[4];		
		var lnkid = "lnkaddcart_" + swatchSku;
		var imgid = "imgaddcart_" + swatchSku;
		var txtid = "txtaddcart_" + swatchSku;				
		if (msgs[1] == "success")
			showOrderedAlready(lnkid, imgid, txtid, msgs[3])
		else if (msgs[1] == "warning" && msgs[2] == MAXSWATCHES )
			showOrderedMaximum(elmId, msgs[0]);
		else
		{
			// showOrderedAlready(lnkid, imgid, txtid, msgs[3]);
			// do nothing
			;
		}
	}
	else
		document.getElementById(elmId).innerHTML = msgs[0];
}

function updateParentWindow(status, swatchInCart, numInCart, elmid, msg)
{
	lnkid = "lnkaddcart_" + ssku;                               // sku is a globale var in product_detail.js
	imgid = "imgaddcart_" + ssku;
	txtid = "txtaddcart_" + ssku;
	if (swatchInCart < MAXSWATCHES || (swatchInCart == MAXSWATCHES && status == "success"))
	{
		window.opener.showOrderedAlready(lnkid, imgid, txtid, numInCart);
	}
	else if (swatchInCart == MAXSWATCHES || status == "warning")
	{
		window.opener.showOrderedMaximum(elmid, msg);        
	}    //update the count in the shopping cart in the header file
//	window.opener.document.getElementById("swatchcnt").innerHTML = numInCart;
}
