//--------------------      GLOBAL VARS  ----------------------

//--------------------      HELPERS      ----------------------

/**
 * Encodes text for transmission via HTTP.
 *
 * @param string text to encode
 * @return string encoded text
 */
function urlEncode(text)
{
    /* Force JavaScript to always treat 'text' as a string. */
    text += '';

    /* encodeURIComponent() doesn't handle the ' character. */
    text = text.replace(/\'/g, '%27');
    
    /* Don't use escape(), as it doesn't properly handle UTF-8. */
    text = encodeURIComponent(text);

    return text;
}

/**
 * Acts the same as PHP's urldecode.
 *
 * @param string text to unescape
 * @return string escaped text
 */
function urlDecode(text)
{
	while (text.indexOf('+') != -1)
	{
    	text = text.replace('+', '%20');
	}
	
    /* Don't use unescape(), as it doesn't properly handle UTF-8. */
	text = decodeURIComponent(text);

    return text;
}

/**
 * Replaces HTML special characters in text to be output-safe.
 *
 * @param string text to escape
 * @return string escaped text
 */
function escapeHTML(text)
{
    text = text.replace('&', '&amp;');
    text = text.replace('<', '&lt;');
    text = text.replace('>', '&gt;');
    text = text.replace('"', '&quot;');
    text = text.replace("'", '&apos;');

    return text;
}


//---------------------      CORE FUNCTIONS      -----------------------

//------      CATALOG.THTML       -------
// Called from catalog.thtml to refresh the measurments, image and pricing based on seal type, product number, and shaft diamater
jq(function() { 
	var imageExpandedJq = jq('#product_image_expanded')[0]; 
	jq('#showExpandedLink').click(function() {
		jq.blockUI(imageExpandedJq, { width: '365px' });
	});
	
	if (jq.browser.msie && jq.browser.version < 7)
	{
		// Fix some IE6 Transparency issues with obsolete gif format
		jq("#navStart").removeClass('start').addClass('startIE6');
		jq("#navEnd").removeClass('end').addClass('endIE6');
	}
});

function populateProductDetails() {
	//TODO: GET PRODUCT ID from seal type
	var productIDSplit = jq('#sealTypeSelect').val().split('|', 4);
	var productID = productIDSplit[1];
	var subProductID = productIDSplit[2];
	var seal = productIDSplit[3];
	
	jq("div[id^='productDimensions']").each(function(i) {jq("#"+this.id).hide(); });
	jq("div[id^='productDetails']").each(function(i) {jq("#"+this.id).hide(); });
	jq("span[id^='subproductUnitNumber']").each(function(i) {jq("#"+this.id).hide(); });
	jq("span[id^='subproductWeight']").each(function(i) {jq("#"+this.id).hide(); });
	jq("span[id^='subproductExtraFields']").each(function(i) {jq("#"+this.id).hide(); });
	jq("span[id^='subproductBearing']").each(function(i) {jq("#"+this.id).hide(); });
	jq("span[id^='subproductElThree']").each(function(i) {jq("#"+this.id).hide(); });
	jq("div[id^='subproductCADLink']").each(function(i) {jq("#"+this.id).hide(); });

	jq("#productDimensions"+productID).show();
	jq("#productDetails"+productID).show();
	jq("#subproductUnitNumber"+subProductID).show();
	jq("#subproductExtraFields"+subProductID).show();
	jq("#subproductWeight"+subProductID).show();
	jq("#subproductBearing"+subProductID).show();
	jq("#subproductCADLink"+subProductID).show();

	jq("#dynamicProdNumber").html(jq("#subproductUnitNumber" + subProductID).html());
	
	if (seal == 'L3') {
		jq("#subproductElThree"+subProductID).show(); 
	}

	getPriceByItem(productID, subProductID, jq("#priceQuantity").val());
}

function catalogInInches(productID) {
	jq("div[id^='dimensionsInches']").each(function(i) {jq("#"+this.id).show();});
	jq("div[id^='dimensionsMillimeters']").each(function(i) {jq("#"+this.id).hide();});
	jq("a[id^='inchesLink']").each(function(i) {document.getElementById(this.id).className = 'measurementLinkPicked';});
	jq("a[id^='mmLink']").each(function(i) {document.getElementById(this.id).className = '';});
	
	// TODO: Call ajax function to save the fact that the user prefers inches for this session
	jq.post("../../setMeasurementPreference", {measurementInInches: 1}, function(xml) {});
}

function catalogInMillimeters(productID) {
	jq("div[id^='dimensionsInches']").each(function(i) {jq("#"+this.id).hide();});
	jq("div[id^='dimensionsMillimeters']").each(function(i) {jq("#"+this.id).show();});
	jq("a[id^='inchesLink']").each(function(i) {document.getElementById(this.id).className = '';});
	jq("a[id^='mmLink']").each(function(i) {document.getElementById(this.id).className = 'measurementLinkPicked';});

	// TODO: Hide ALL of the elements matching this name
	
	// TODO: Call ajax function to save the fact that the user prefers inches for this session
	jq.post("../../setMeasurementPreference", {measurementInInches: 0}, function(xml) {});
}

var loadingPriceDataTemp = '';
var loggedInIPTCI = false;

function getPriceByItem(productID, subproductID, quantity) {
	if (!loggedInIPTCI) return;
	
	var priceSpan = jq('#priceSpan');
	var availSpan = jq('#availSpan');
	
	// Set loading image indicators
	if (loadingPriceDataTemp == '') {
		loadingPriceDataTemp = priceSpan.html();
	} else {
		priceSpan.html(loadingPriceDataTemp);
		availSpan.html(loadingPriceDataTemp);
	}
	
	jq.post("../../getProductPrice", {productID: productID, subproductID: subproductID, quantity:quantity}, function(xml) {
		available = '';
		if (window.ActiveXObject) {
			var xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
			xmlDoc.loadXML(xml);
			if (xmlDoc.parseError.errorCode != 0) {
			   var myErr = xmlDoc.parseError;
			   //alert("You have error " + myErr.reason);
			   //alert(xml);
			} else {
			   priceSpan.html(xmlDoc.getElementsByTagName("price")[0].childNodes[0].nodeValue);
			   available = xmlDoc.getElementsByTagName("available")[0].childNodes[0].nodeValue;
			}
			
		} else {
			priceSpan.html(jq("price",xml).text());
			available = jq("available",xml).text();
		}
		
		if(available == "")
		      available = "Please call for availability";
		      
		availSpan.html(available);
	});

}

function toggleSealType(prefix, shaftDiam, iscatalogview, defaultValue)
{
	if (iscatalogview) {
		jq('#sealTypeSelect').load("/Store/ajaxToggleSealType/", {prefix:prefix, shaftDiam:shaftDiam, iscatalogview:(iscatalogview?1:0)}, function(xml) {
			if (defaultValue != '') {
				for(i = 0; i < document.getElementById('sealTypeSelect').length; i++) {
					if(document.getElementById('sealTypeSelect').options[i].innerHTML == defaultValue+'-Type Seal') {
						document.getElementById('sealTypeSelect').value = document.getElementById('sealTypeSelect').options[i].value;
					}
				}
			}
			if (document.getElementById('sealTypeSelect').style.display=='none') {
				document.getElementById('sealTypeSelect').style.display = '';
			}
			populateProductDetails();
		});
	} else {
		jq('#sealType' + prefix).load("/Store/ajaxToggleSealType/", {prefix:prefix, shaftDiam:shaftDiam}, function(xml) {
			// If count of <option> is less than 2 hide this area...
			if(xml.split('</option>').length -1 < 2) {
				document.getElementById('sealTypeArea' + prefix).style.display='none';
				document.getElementById('sealTypeGo' + prefix).className="two";
			} else {
				document.getElementById('sealTypeArea' + prefix).style.display='';
				document.getElementById('sealTypeGo' + prefix).className="three";
			}
		});
	}
}