/// This file contains the functions used for the dynamic updates to the 
// product display page
// This code depends on three global variables, an array called products,
// a string called activeImage, and a string called activeProductName


var tabIds = new Array('overview', 'specs', 'altpic', 'size', 'reviews', 'friend', 
	'warranty' );
var currentProductId;
var currentSkuId;
var store;
var catId;
var leafCatId;
var maxWidth;
var pRange = "";

/* update the displayed price
 *	This function has become polluted, and needs to be sectioned off
 */
function updatePrice()
{
	var price;
	var productId;
	var skuId;
	var qty;
	var orgPrice;
	var orgPriceTotal;
	var listPrice;
	var salePrice;
	
	productId = document.getElementById("prodOpt")[document
		.getElementById("prodOpt").selectedIndex].value;
	skuId = document.getElementById("skuOpt")[document.getElementById("skuOpt")
		.selectedIndex].value;
	
	qty = document.getElementById("quantity").value;
	if(qty < 1 || isNaN(qty)){  //Protection against Joe Harley
		qty = 1;
		document.getElementById("quantity").value = 1;
	}
	
	listPrice = skus[skuId]["listprice"];
	salePrice = skus[skuId]["saleprice"];
	
	if(listPrice.indexOf(",") != -1){
		var firstSet = "";
		var secondSet = "";
		var remainder = "";
		firstSet = listPrice.substring(listPrice.indexOf("$") + 1, 
			listPrice.indexOf(","));
		remainder = listPrice.substring(listPrice.indexOf(",") + 1,
			listPrice.length - 1);
		if(remainder.indexOf(",") != -1){
			secondSet = remainder.subset(0, remainder.indexOf(",") + 1);
			remainder = remainder.subset(remainder.indexOf(",") + 1, 
				remainder.length - 1);
		}
		firstSet += "";
		secondSet += "";
		remainder += "";
		listPrice = firstSet + secondSet + remainder;
	}
	if(salePrice.indexOf(",") != -1){
		var firstSet = "";
		var secondSet = "";
		var remainder = "";
		firstSet = salePrice.substring(salePrice.indexOf("$") + 1, 
			salePrice.indexOf(","));
		remainder = salePrice.substring(salePrice.indexOf(",") + 1,
			salePrice.length - 1);
		if(remainder.indexOf(",") != -1){
			secondSet = remainder.subset(0, remainder.indexOf(",") + 1);
			remainder = remainder.subset(remainder.indexOf(",") + 1, 
				remainder.length - 1);
		}
		firstSet += "";
		secondSet += "";
		remainder += "";
		salePrice = firstSet + secondSet + remainder;
	}
	//This will remove the formating of a currency to allow for mathmatical operations
	if(skus[skuId]["sale"] != null && skus[skuId]["sale"] != ""){
		if(skus[skuId]["sale"].indexOf("true") != -1){
			orgPrice = parseFloat(listPrice
		    	.substring(listPrice.indexOf("$") + 1,
		    	listPrice.length));
			price = parseFloat(salePrice
	  			.substring(salePrice.indexOf("$") + 1 ,
	  			salePrice.length));
		} else {
			price = parseFloat(listPrice
	  			.substring(listPrice.indexOf("$") + 1 ,
	  			listPrice.length));
		}
	} else {
		price = parseFloat(listPrice
	  		.substring(listPrice.indexOf("$") + 1 ,
	  		listPrice.length));
	}
	qty += "";
	if(qty.indexOf(".") != -1){
		qty = qty.substring(0, qty.indexOf("."));
		document.getElementById("quantity").value = qty;
	}
	//total = price * qty;
	total = price;
	total += "";
	total = doublePercision(total);
	
	//Remove math generated decimal places
	total = total.substring(0 ,total.indexOf(".") + 3); 
	//Add proper number formatting using commas	
	if(total.length >= 7){
		var thousands = total.substring(0,total.indexOf(".") - 3);
		var remainder = total.substring(total.indexOf(".") - 3,total.length);
		total = thousands + "," + remainder;
	}
	if(total.length >= 11){
		var millions = total.substring(0,total.indexOf(",") - 3);
		var remainder = total.substring(total.indexOf(",") - 3,total.length);
		total = millions + "," + remainder;
	}
	if( skus[skuId]["sale"] != null && skus[skuId]["sale"].indexOf("true") != -1){
	  orgPriceTotal = orgPrice;
	  orgPriceTotal += "";
	  
	  orgPriceTotal = doublePercision(orgPriceTotal);
	  
	  //Add proper number formatting using commas	
	  if(orgPriceTotal.length >= 7){
		  var thousands = orgPriceTotal.substring(0,orgPriceTotal.indexOf(".") - 3);
	 	  var remainder = orgPriceTotal.substring(orgPriceTotal.indexOf(".") - 3,orgPriceTotal.length);
		  orgPriceTotal = thousands + "," + remainder;
	  }
	  if(orgPriceTotal.length >= 11){
		  var millions = orgPriceTotal.substring(0,orgPriceTotal.indexOf(",") - 3);
		  var remainder = orgPriceTotal.substring(orgPriceTotal.indexOf(",") - 3,orgPriceTotal.length);
		  orgPriceTotal = millions + "," + remainder;
	  }
	}
	
	//Display original price and closeout price when the sku is on sale
	if( skus[skuId]["sale"] != null && skus[skuId]["sale"].indexOf("true") != -1) {
		document.getElementById("originalprice").innerHTML = 
			"Originally Priced: $" + orgPriceTotal;
		document.getElementById("originalprice").style.display = "block";
		document.getElementById("actualpricelabel").innerHTML = 
			"Closeout Price: ";
	} else {
		document.getElementById("originalprice").innerHTML = "";
		document.getElementById("originalprice").style.display = "none";
		document.getElementById("actualpricelabel").innerHTML = "Your Price: ";
	}
	document.getElementById("dkNew").src = skus[skuId]["new"];
	document.getElementById("price").innerHTML = "$" + total;
	document.getElementById("qtyOnHand").innerHTML = skus[skuId]["qtyOnHand"];
	document.getElementById("dkId").innerHTML = skuId;
	document.getElementById("skudisplayname").innerHTML = skus[skuId]["displayName"];
	
	if(products[currentProductId]["restrictedDisplay"] != ''){
		document.getElementById("skuIdLabel").innerHTML = skus[skuId]["name-type"];
	} else {
		document.getElementById("skuIdLabel").innerHTML = skus[skuId]["name-type"] 
			+ " - (Price)";
	}
	if(skus[skuId]["mfgId"] != null && skus[skuId]["mfgId"] != ""){
		document.getElementById("mfgId").innerHTML = skus[skuId]["mfgId"];
	} else {
		document.getElementById("mfgPartNumber").style.visibility = "hidden";
	}
	if( products[currentProductId]["restrictedDisplay"] == ''){
	  if( skus[skuId]["nla"].indexOf("true") != -1 ){
	    document.getElementById("restrictedDisplayWarning").innerHTML = 
	    "<br/><span style=\"color: #DD0000; font-size: 12px; font-weight: bold;\">\n"+
    	"This Product is No Longer Available</span>\n";
        document.getElementById("cartWishlistButtons").style.display = "none";
        document.getElementById("friend").style.visibility = "hidden";
        document.getElementById("quantityDiv").style.display = "none";
        document.getElementById("productactualprice").style.display = "none";
        document.getElementById("originalprice").style.display = "none";
        document.getElementById("bmlTable").style.display = "none";
        if(document.getElementById("bmlPromoTable") != null)
        	document.getElementById("bmlPromoTable").style.display = "none";
	  } else {
	    document.getElementById("restrictedDisplayWarning").innerHTML = "";
	    document.getElementById("cartWishlistButtons").style.display = "block";
	    document.getElementById("friend").style.visibility = "visible";
        document.getElementById("quantityDiv").style.display = "block";
	    document.getElementById("productactualprice").style.display = "block";
	    if( skus[skuId]["sale"] != null && skus[skuId]["sale"].indexOf("true") != -1)
	    document.getElementById("originalprice").style.display = "block";
	    document.getElementById("bmlTable").style.display = "block";
	  }
	}
	if(skus[skuId]["mmy"] != null && skus[skuId]["mmy"].indexOf("true") != -1){
		document.getElementById("mmyLink").innerHTML = 
			"<img src=\"/denniskirk/b2c/imagecenter/images/bullet_arrow.gif\" height=\"10\" width=\"5\"  border=\"0\" style=\"position:relative; top:2px; float:left; padding-right:3px; padding-bottom:10px;\" \> "+
			"<a href=\"#altImages\" onclick=\"selectTab('fitment')\">" + 
			"See a list of machines <br\> part " + skuId + " fits.</a>";
	} else {
		document.getElementById("mmyLink").innerHTML = "";
	}
	if((skus[skuId]["img"] == "") || (skus[skuId]["img"] == "undefined")
		|| (skus[skuId]["img"] == 0) || (skus[skuId]["img"] == null)) {
		document.largePhoto.src = "/denniskirk/b2c/product_images/i/n/a/150pix/ina150.jpg";
	} else {
		document.largePhoto.src = skus[skuId]["img"];
	}
	
	if(skus[skuId]["nla"].indexOf("true") == -1 
		&& products[currentProductId]["restrictedDisplay"] == ''){
		displayBML(price);
		displayBBB(leafCatId, price);
		
		if(skus[skuId]["qtyOnHand"] == "Expected Soon") {
			updateEmailInStockLink(skuId);
		} else {
			document.getElementById("emailInStock").innerHTML = "";
		}
	} else {
		document.getElementById("emailInStock").innerHTML = "";
	}
	
	updateImageLinks(skuId);
	loadTab(skuId);
	
	//This function should only be called once the skus are loaded
	enableButtons();
}


/**
 * this function updates the link to the email when in stock popup
 **/
function updateEmailInStockLink(skuId) {
	var link = "javascript:DK_openNewWindow('/jsp/email/template/email_in_stock.jsp?skuId=" + skuId + "','emailInStock','width=300,height=150,scrollbars=no');";
	document.getElementById("emailInStock").innerHTML = "<a href=\"" + link + "\">Email me when stock arrives</a>";
}


/**
 * This function updates the image links
 **/
function updateImageLinks(skuId)
{
	var link = "javascript:DK_openNewWindow('/jsp/common/img_pop.jsp?skuId="
 		+ skuId + 
		"&imgId=0','imgBlowup','width=616,height=636,scrollbars=no');";
	var prdImage = document.getElementById("blowupPhoto");
	var altLink = document.getElementById("altImageLink");

	altLink.innerHTML = '<a href="' + link + 
		'">Alternate &amp; Larger Images</a>';
	prdImage.href = link;
}

// update the displayed name based on the selected product
function updateName()
{
	var productId;
	var name;

	productId = document.getElementById("prodOpt").options[document.getElementById("prodOpt").selectedIndex].value;
	name = products[productId]["name"];
	if(name != null)
		document.getElementById("styleName").innerHTML = name;
}

// rebuild the sku drop down (called after loading new data)
// uses the skus global, setting csku to selected if csku is set
function rebuildSkuList(ieSkus)
{
	var isFirst = true;
	var skuText;

	skus = ieSkus;
	document.getElementById("skuOpt").length = 0;
	for(sku in ieSkus) {
		if(ieSkus[sku]["restricted"] == null 
			|| ieSkus[sku]["restricted"].indexOf("true") == -1){
			skuText = ieSkus[sku]["name"] + " - (" + 
				ieSkus[sku]["price"] + ")";
		} else {
			skuText = ieSkus[sku]["name"];
		}
		if(skus[sku]["selected"] == true) {
			isFirst = true;
		}
		document.getElementById("skuOpt")[document.getElementById("skuOpt").length] =
			new Option(skuText, sku, isFirst, isFirst);
		if(isFirst) {
			isFirst = false;
		}
	}
	
	if(document.getElementById("skuOpt").length == 1 
		&& document.getElementById("prodOpt").length == 1){
		document.getElementById("skuDiv").style.display = "none";
	}
	
	updatePrice();
}

var skuListOpen = false;

function skuListFocus()
{
	if(navigator.userAgent.indexOf("MSIE")) {
		if(maxWidth == null){
			var width = determineMaxWidth();
			width = (width * 6) + 4;
			maxWidth = parseInt(width);
			if(maxWidth == "NaN"){
				maxWidth = width;
			}
		}
		if(maxWidth != null && maxWidth < 165){
			document.getElementById("skuOpt").style.width = "165px";
		} else {
			document.getElementById("skuOpt").style.width = "auto";
		}
	}
}

// rebuild the product drop down with prodId selected
function rebuildProductList(prodId, skuId)
{
	 var isSelected;

	 document.getElementById("prodOpt").length = 0; // clear product list
	 
	 for(product in products) {
		 if(product == prodId) {
			 isSelected = true;
		 } else {
			 isSelected = false;
		 }
		 document.getElementById("prodOpt")[document.getElementById("prodOpt").length] =
			 new Option(products[product]["name"], product, 
				isSelected, isSelected);
	 }
	 if(document.getElementById("prodOpt").length == 1){
	 	document.getElementById("productDiv").style.display = "none";
	 } else if (document.getElementById("prodOpt").length < 1) {
	 	emptyPage();
	 }
	 
	 updateName();
	 var page = "/jsp/product_catalog/common/price.jsp?productId=" + prodId +"&skuId=" + skuId + "&store=" + store;
	 loadSkuData(page);
}

// change main image on hover
// if isIn is true, display new image, if isIn is false restore current
function hoverProduct(prodId, isIn)
{
	if(isIn) {
		document.largePhoto.src = products[prodId]["image"];
		document.getElementById("styleName").innerHTML = 
		products[prodId]["name"];
	} else {
		document.largePhoto.src = activeImage;
		document.getElementById("styleName").innerHTML = 
			activeProductName;
	}
}

// change document to reflect prodId is now the active product
function changeProduct(prodId, skuId)
{
	document.getElementById("skuOpt").options[0].text = "Loading...";
	document.getElementById("skuOpt").options[0].selected = "true";
	document.getElementById("productfeaturearea").innerHTML = "Loading...";
	if(!products[prodId]["hasSizeChart"]){
		document.getElementById("size").style.display = "none";
	}
	if(!products[prodId]["hasWarranty"]){
	  document.getElementById("warranty").style.visibility = "hidden";
	} else {
	  document.getElementById("warranty").style.visibility = "visible";
	}

	activeImage = products[prodId]["image"];
	activeProductName = products[prodId]["name"];
	
	disableButtons();
	rebuildProductList(prodId, skuId);
	loadTab(document.getElementById("skuOpt")[document.getElementById("skuOpt").selectedIndex].value);
	currentProductId = prodId;
	priceRange();
	
	document.getElementById("prodIdLabel").innerHTML = products[prodId]["dropDownLabel"];
	document.getElementById("styleLabel").innerHTML = products[prodId]["dropDownLabel"];
	//S&S fix
	if(products[prodId]["restrictedDisplay"] != ''){
	  document.getElementById("productactualprice").style.display = "none";
	  document.getElementById("restrictedDisplayWarning").innerHTML = 
	  "<span style=\"color: #DD0000; font-size: 10px; font-weight: bold;\">\n"+
    	"Due to the Manufacturer's Internet Policy we are unable to \n"+
	   	"show prices or process your order for this product online.<br/>"+
    	"Please call 800-328-9280 for additional information and \n"+
    	"prompt processing of your order.</span>";
      document.getElementById("cartWishlistButtons").style.display = "none";
      document.getElementById("friend").style.visibility = "hidden";
      document.getElementById("bmlTable").style.display = "none";
    }
}

// handle new sku data response from the server
// uses the global variable skus
function loadSkuData(page, cSku)
{
	skuRequest = false;
	if(window.XMLHttpRequest) {
		try {
			skuRequest = new XMLHttpRequest();
		} catch(e) { 
			skuRequest = false;
		}
	} else if(window.ActiveXObject) {
		try {
			skuRequest = new ActiveXObject("Msxml2.XMLHTTP");
		} catch(e) {
			try {
				skuRequest = new ActiveXObject(
					"MicrosoftXMLHTTP");
			} catch (e) {
				skuRequest = false;
			}
		}
	}

	if(skuRequest) {
		skuRequest.onreadystatechange = handleSkuData;
		skuRequest.open("GET", page, true);
		skuRequest.send("");
	}
}

// Change the selected tab
function selectTab(selectedId)
{
	var spanObj;

	for(span in tabIds) {
		spanObj = document.getElementById(tabIds[span]);
		if(tabIds[span] == selectedId) {
			spanObj.className = "selected";
		} else {
			spanObj.className = "";
		}
	}
	loadTab(document.getElementById("skuOpt")[document.getElementById("skuOpt").selectedIndex].value);
	return false;
}

function setStore(nStore){
	store = nStore;
}

function setCatId(nCatId){
	catId = nCatId
}

function setLeafCatId(nLeafCatId){
	leafCatId = nLeafCatId;
}

// load a new document into the tab iframe
function loadTab(skuId)
{
	var spanObj;
	for(span in tabIds) {
		spanObj = document.getElementById(tabIds[span]);
		if(spanObj.className == "selected") {
	 		if(document.getElementById("altpic").className == "selected" ||
	 			document.getElementById("warranty").className == "selected" ){

				currentProdId = document.getElementById("prodOpt")[document.getElementById("prodOpt").selectedIndex].value;
	 			var page = "/jsp/prodpage/data/tab_page.jsp?prod_id=" + currentProdId + 
	 			"&tab=" + tabIds[span] + "&sku=" + skuId;
				loadTabXML(page, handleTabData);
	 		} else if(document.getElementById("friend").className == "selected"){
	 			var page = "/jsp/prodpage/data/tab_page.jsp?sku=" + skuId +
	 			"&tab=" + tabIds[span] + "&store=" + store + "&catId=" + catId
	 			+ "&leafCatId=" + leafCatId;
				loadTabXML(page, handleTabData);
			} else if(document.getElementById("reviews").className == "selected") {
				showReviews();
	 		}else{
	 			var page = "/jsp/prodpage/data/tab_page.jsp?sku=" + skuId + 
	 			"&tab=" + tabIds[span];
				loadTabXML(page, handleTabData);
	 		}
	 		
		}
	}
}

function loadTabXML(page, handler)
{
	tabRequest = false;
	if(window.XMLHttpRequest) {
		try {
			tabRequest = new XMLHttpRequest();
		} catch(e) { 
			tabRequest = false;
		}
	} else if(window.ActiveXObject) {
		try {
			tabRequest = new ActiveXObject("Msxml2.XMLHTTP");
		} catch(e) {
			try {
				tabRequest = new ActiveXObject(
					"MicrosoftXMLHTTP");
			} catch (e) {
				tabRequest = false;
			}
		}
	}

	if(tabRequest) {
		tabRequest.onreadystatechange = handler;
		tabRequest.open("GET", page, true);
		tabRequest.send("");
	}
}

// place the data from the tab iframe into the tab display area.
function loadTabData(doc)
{
	var tabArea = document.getElementById("productfeaturearea");
	var tabContents = doc.getElementById("content");

	tabArea.innerHTML = tabContents.innerHTML;
}

// place the data from the tab iframe into the tab display area.
function handleTabData(doc)
{
	var tabArea = document.getElementById("productfeaturearea");

	if((tabRequest.readyState == 4) && (tabRequest.status == 200)) {
		tabArea.innerHTML = tabRequest.responseText
	} else {
		tabArea.innerHTML = "Loading...";
	}
}

// load the price range into the document
function priceRange(){
	if(pRange == null || pRange == ""){
		var pmin, pmax;
		pmin = 0;
		pmax = 0;
		
		for(prod in products){
			if(pmin == 0)
				pmin = products[prod]["effectiveMinPrice"];
			else if(pmin > products[prod]["effectiveMinPrice"])
				pmin = products[prod]["effectiveMinPrice"];
						
			if(pmax < products[prod]["effectiveMaxPrice"])
				pmax = products[prod]["effectiveMaxPrice"];	
		}
		//Ensure that the prices have two decimal places
		pmin += "";
		if(pmin.indexOf(".") == -1)
			pmin += ".00";
		else if(pmin.indexOf(".") == pmin.length - 1)
			pmin += "00";
		else if(pmin.indexOf(".") == pmin.length - 2)
			pmin += "0";
		pmax += "";
		if(pmax.indexOf(".") == -1)
			pmax += ".00";
		else if(pmax.indexOf(".") == pmax.length - 1)
			pmin += "00";
		else if(pmax.indexOf(".") == pmax.length - 2)
			pmax += "0";
			
		var range = "$" + pmin + "-$" + pmax;
		if(document.getElementById("prodOpt").length > 1 && pmin != pmax){
			document.getElementById("range").innerHTML = range;
		} else {	
			document.getElementById("productpricerange").style.visibility = "hidden";
		}
	} else {
		if(document.getElementById("prodOpt").length > 1){
			document.getElementById("range").innerHTML = pRange;
		} else {	
			document.getElementById("productpricerange").style.visibility = "hidden";
		}
	}
}

// load the thumbnail Images
function loadThumbnails() {
	var parentIds = new Array();
	var equals;
	var thumbnailHTML = "";
	var length = 0;
	
	//I have no idea why this is necessary, but products.length was not working
	for( id in products){
		length ++;
	}
	
	if(length <= 1){
	  document.getElementById("productstylescolors").style.visibility = "hidden";
  	  document.getElementById("productswatch").style.visibility = "hidden";
	  return;
	}
	
	for( id in products){
		equals = false;
		for( i = 0; i < parentIds.length; i++ ) {
			if(products[id]["parentProductName"] == parentIds[i]){
				equals = true;
			} 
		}
		if(!equals) {
			parentIds[parentIds.length] = products[id]["parentProductName"]; 	
		}
	}
	
	for(n = 0; n < parentIds.length; n++) {
		thumbnailHTML += " " + parentIds[n] + "<div id=\"set" + n + "\">\n";
		for(id in products){
			if(parentIds[n] == products[id]["parentProductName"]) {
				if(products[id]["thumbnail"] != null && 
					products[id]["thumbnail"] != ""){
					thumbnailHTML += "<a href=\"javascript:changeProduct('" + id + "');\"" + 
					"class=\"viewLinks\"><img id=\"sw" + n + 
					"\"src=\"" + products[id]["thumbnail"] + "\"" + 
					"alt=\"Thumbnail for " + products[id]["name"] + "\"" + 
					"title=\"Click for an Alternate Product: " + products[id]["name"] + 
					"\"onclick=\"changeProduct('" + id + "',null);displayLoadingInSkus();\" /></a>\n";
				} else {
					thumbnailHTML += "<a href=\"javascript:changeProduct('" + id + "');\"" + 
					"class=\"viewLinks\"><img id=\"sw" + n + 
					"\"src=\"/denniskirk/b2c/product_images/i/n/a/50pix/ina50.jpg\"" + 
					"alt=\"Thumbnail for " + products[id]["name"] + "\"" + 
					"title=\"Click for an Alternate Product: " + products[id]["name"] + 
					"\"onclick=\"changeProduct('" + id + "',null);displayLoadingInSkus();\" /></a>\n";
				
				}
			}
		}
		thumbnailHTML += "</div>\n";
	}
	
	document.getElementById("productswatch").innerHTML = thumbnailHTML;

}

function updateMMYLink(){
	var linkMsg = "";
	
	linkMsg = "<a href=\"#topSpecsTab\" onClick=\"selectNext();\""
		+ ">Click here to view part " 
		+ ((document.getElementById("skuOpt").selectedIndex + 1) % document.getElementById("skuOpt").length + 1) + " of " 
		+ document.getElementById("skuOpt").length + "</a>";
	 	
	document.getElementById("mmyLinkBottom").innerHTML = linkMsg;
}

//This function is designed to select the next sku from the drop-down list
function selectNext(){
	document.getElementById("skuOpt").selectedIndex = 
	(document.getElementById("skuOpt").selectedIndex + 1) % document.getElementById("skuOpt").length;
	updatePrice();
}

function setPRange(range){
	pRange = range;
}
