$(function(){
	$('li[class^=productColor]').click(function(){
		switchColor(this);//Color Button has been clicked		
	});
	$('li.sizeText24x24,li.productSize24x24').click(function(){
		setSize24(this);//Size Button has been clicked
	});
	$('li.sizeText24x48,li.productSize24x48').click(function(){
		setSize48(this);//Size Button has been clicked
	});
	$('input.quantityInput').keyup(function(event){
		updateQuantity(this);//Quantity Input has been changed
	});
	$('div#pricingLink').click(function(){
		//console.log('pricing link clicked');
		switchPricing();
	});
	
	//Add a trim function to all String objects - Doug
	String.prototype.trim = function() {
        return this.replace(/^\s+|\s+$/g,"");
}
});
var mi = "#mainImage";
var productD = "#productDescription";
var pNum = "#partNumber";
var mii = "#mainImageImg";
var mifl = "#mainImageFloatLeft";
var qiv = parseInt($(qi).attr('value'));
var qi2v = 0;
var pct = "#productColorTitle";
var pct2 = "#productColorTitle2";
var pt = "#productTitle";
var bpt = "#breadcrumbProductTitle";
var mvl = "#moreViewsLink";
var mvl2 = "#moreViewsLink2";
var totalp = "#totalPrice";
var totalpr = "#totalPriceRetail";
//var totalps = "#totalPriceSavings";
var totalp2 = "#totalPrice2";
var tileppt = "#tilePricePerText";
var tilep = "#tilePrice";
var tilepr = "#tilePriceRetail";
var atcb = "#addToCartButton";
var colorandSizeIndex = 0;
var pst = "#productSizeTitle";
var pst2 = "#productSizeTitle2";
var pst24 = "#productSizeTitle24x24";
var pst48 = "#productSizeTitle24x48";
var pst1and2 = '#productSizeTitle, #productSizeTitle2';
var qi = "#quantityInput";
var qi2 = "#quantityInput2";
var qm = "#quantityMin";
var qmv = "#quantityMinVal";
var qat = "#qtyAppendText";	
//hidden input value that sends the quantity of tiles selected by the user
var atcq = "#addtoCartQuantity";
//hidden input value that sends the productid of the tile selected by the user
var atcpid = "#addtoCartProductID";
var sid = "#sampleID";
var mp = "#minimumPrice";
var productID = 0;
var tileProductID = 35;
var link = "";
var linkMVL = "/moreViews/index.cfm?height=520&width=650";
var tilePrice = 0; 
var dollars = 0; 
var miiSRC = "";
var miiMIFLH = "";
var miiNextSRC = ""; 
var miiNextMIFLH = "";
//Update prices when quantity is changed(keyup)
function updateQuantity(input){
	//console.log("quantity");
	//Set the array index for the current color
	colorandSizeIndex = getColorIndex(pct,pst);
	//alert('colorandSizeIndex: '+colorandSizeIndex);
	//Set the productID based on the color array index. 
	tileProductID = ListGetAt(productDetails.productid,colorandSizeIndex);
	
	i = $(input);
	if ( i.attr('value') == undefined || parseInt(i.attr('value')) == NaN ) {
		qiv = 0;
		$('#totalPriceAndPriceSavings').hide();
		$(i).attr("value","");
		$(qi2).empty().append('0');	
	}
	else {
		qiv = $(i).attr("value");
		qminval = $(qmv).val();
		if(qiv -qminval< 0) $('#totalPriceAndPriceSavings').hide();
		else $('#totalPriceAndPriceSavings').show();
		qatv = $(qat).text();
		$(qi2).empty().append(qiv);
		if(qiv == 1 && (qatv == " Cases")) {
			$(qat).empty().append(" Case");
		}
		else if(qiv > 1 && (qatv == " Case")) {
			$(qat).empty().append(" Cases");			
		}	
	}
	//qiv = $(qi2).text();
	//alert('q2'+qi2v);
	/*if ( $(pst).text() == '24" x 48"' ) {
		colorandSizeIndex++;	
	}*/
	
	//Set the price based on the quantity, size and color array index
	qivPlusTotalTileCount = parseInt(totalTileCountNonSamples) + parseInt(qiv);
	if (tileProductID == undefined) {
		tileProductID = productDetails.productid;
		tilePrice = productDetails.pricelevels[0];
	}
	else {
		tilePrice = setTilePrice(qivPlusTotalTileCount,colorandSizeIndex);	
	}
	//alert('updateQuantity tile price: '+tilePrice);

	//Update text in spans with new price
	dollarsTotal = CurrencyFormatted(qiv*tilePrice);
	//alert('d'+dollars);
	
	updateTilePricing(tilePrice,colorandSizeIndex);
	
	link = "&selectedTilePrice="+tilePrice+"&productID="+tileProductID+"&quantity="+qivPlusTotalTileCount+"&color="+$(pct).text()+"&size="+URLEncodedFormat($(pst).text())+"&title="+URLEncodedFormat($(pt).text())+"&TB_iframe=true&KeepThis=true";

	$(mvl).attr("href",linkMVL+link);	
	$(mvl2).attr("href",linkMVL+link);
	$(atcq).attr("value",qiv);		
	//$(atcpid).attr("value",tileProductID);
	reloadPricingGrid(qiv,tileProductID,tilePrice);
}

//When a customer lands on an accessory, fix the height/width, picture, etc.
function correctAccessories(isBtt){
   if (isBtt) {
   	$(mi).css("height", "250px");
   	$(mi).css("width", "250px");
   	$(mi).css("margin-bottom", "10px");
   	$(mii).css("height", "250px");
   }
   reloadPricingGrid(qiv,tileProductID,tilePrice);
}


//Updates prices when a color is clicked
function switchColor(li){
	//console.log('switchColor li: '+li);
	l = $(li);
	//Set the quantity 
	qiv = $(qi2).text();

	$('#colorSelect').val( l.attr('productColorName'), pst );
	colorandSizeIndex = getColorIndex(l.attr('productColorName'),pst);
	//console.log('color name: '+l.attr('productColorName'));
	//console.log('colorandSizeIndex: '+colorandSizeIndex);

	var highestPriceBreak = ListGetAt(productDetails.pricebreaks[colorandSizeIndex], ListLen(productDetails.pricebreaks[colorandSizeIndex]));
	
	//Set the "as low as" price based on the size and color selected.
	$(mp).empty().append('$'+setTilePrice(highestPriceBreak,colorandSizeIndex));
	tileProductID = ListGetAt(productDetails.productid,colorandSizeIndex);
	
	// Load new product title
	prodTitle = ListGetAt(productDetails.title,colorandSizeIndex);
	$(pt).empty().append(prodTitle);	// Main product title
	$(bpt).empty().append(prodTitle);	// Breadcrumb product title
	document.title = prodTitle;			// Page title (<head><title/></head>)

	// Load new product partnumber
	partnum = ListGetAt(productDetails.partnumber,colorandSizeIndex);
	
	// Show stock warning if applicable
	/*
	//if (partnum.substr(1,1) == '1' && partnum.substr(partnum.length-3,3) == 'BBR') {
	if (partnum == 'V1-DECOTAPE-WTO') {
		$('#stockWarning').removeClass('hidden');
	}
	else {
		$('#stockWarning').addClass('hidden');
	}*/
	
	// Load new product description
	//alert('load description from switchcolor() with id: '+tileProductID);
	getProductDescription(tileProductID);

	//Set the tile price for the color and quantity that has been chosen by the user 
	//+ the quantity of tiles already in the cart
	qivPlusTotalTileCount = parseInt(totalTileCountNonSamples) + parseInt(qiv);
	tilePrice = setTilePrice(qivPlusTotalTileCount,colorandSizeIndex);
	
	//Empty and update prices based on the price breaks  	
	if (isNaN(tilePrice)) {	
		tilePrice = ListGetAt(productDetails.pricelevels[colorandSizeIndex]);
	}
	
	updateTilePricing(tilePrice,colorandSizeIndex);
	
	
	// FeatherLight
	var csl = "ul.colorSelectList li";
	$(csl).css("border","3px solid #393837");
	$(csl).css("cursor","pointer");	
	
	// Signature
	var cslSig = "ul.colorSelectListSig li";
	$(cslSig).css("border","3px solid #393837");
	$(cslSig).css("cursor","pointer");	
	
	// BTT
	var cslBTT = "ul.colorSelectListBTT li";
	$(cslBTT).css("border","3px solid #7BA294");
	$(cslBTT).css("cursor","pointer");	

	// L&W Border Clear (all options)
	var lwsAllButtons = "ul#colorSelectListLWS_BTT_SUS_TRN li";
	$(lwsAllButtons).css("border","0px");
	lwsAllButtons = "ul#colorSelectListLWS_BTT_SUS li";
	$(lwsAllButtons).css("border","0px");
	lwsAllButtons = "ul#colorSelectListLWS_BTT_TRN li";
	$(lwsAllButtons).css("border","0px");
	lwsAllButtons = "ul#colorSelectListLWS_BTT li";
	$(lwsAllButtons).css("border","0px");
	lwsAllButtons = "ul#colorSelectListLWS_SUS_TRN li";
	$(lwsAllButtons).css("border","0px");
	
	// FeatherLight
	var liAllButtons = "ul#colorSelectList li";
	$(liAllButtons).css("border","0px");
	
	// Signature
	var liAllButtonsSig = "ul#colorSelectListSig li";
	$(liAllButtonsSig).css("border","0px");
	
	// BTT
	var liAllButtonsBTT = "ul#colorSelectListBTT li";
	$(liAllButtonsBTT).css("border","0px");
	
	if ($(liAllButtonsBTT).length == 0) {
		$(l).css("border", "2px solid #3FBBEF");
	}
	else {
		$(l).css("border", "2px solid #7BA294");
	}
	
	$(l).css("width", "19px");
	$(l).css("height", "19px");
		
	/* Update the Product Color Name Spans */
	$('#productColorTitle, #productColorTitle2').empty().append(l.attr('productColorName'));
	//Update the thickbox window links	
	link = "&selectedTilePrice="+tilePrice+"&productID="+tileProductID+"&quantity="+qivPlusTotalTileCount+"&color="+$(pct).text()+"&size="+URLEncodedFormat($(pst).text())+"&title="+URLEncodedFormat($(pt).text())+"&TB_iframe=true&KeepThis=true";

	$(mvl).attr("href",linkMVL+link);
	$(mvl2).attr("href",linkMVL+link);
	$(atcq).attr("value",qiv);
	$(atcpid).attr("value",tileProductID);
	$(sid).attr("value",tileProductID);
	
	var cif = ListGetAt(productDetails.filename,colorandSizeIndex);	
	
	var isBttOnCeilume = checkBttOnCeilume();
	
	if (!cif.match('thumb')) {
		if ($('#hostNameHolder').html() != 'btt' && !isBttOnCeilume) {
			cif = cif.replace('.jpg', '_thumb250.jpg');
		}
		else {
			cif = cif.replace('.jpg', '_thumbBTT.jpg');
		}
		if ($('#hostNameHolder').html() != 'btt' && !isBttOnCeilume) {
			$(mii).attr("src", cdnProductImageURL + cif);
		}
		else {
			cif = cif.replace('_thumb250.jpg', '_thumbBTT.jpg');
		    $(mii).attr("src", cdnProductImageURL + cif);
		}
	}
	else {
		$(mii).attr("src",cdnProductImageURL+cif);
	}

	h = 250;

	if( (($('#hostNameHolder').html().trim() == 'btt') || isBttOnCeilume) && $(pst).text() != "2' x 4'") {

	   $(mi).css("height", "250px");
	   $(mi).css("width", "250px");
	   $(mi).css("margin-bottom","10px");
	   $(mii).css("height","250px");
	}
	else if(($('#hostNameHolder').html().trim() == 'btt') || isBttOnCeilume) {;
		$(mi).css("height","500px");
		$(mi).css("width", "250px");
		$(mi).css("margin-bottom","10px");
		$(mii).css("height", "500px");
	}
	else if ( (isBTTColor($(pct).text()) || $(pct).text() == 'White' || ( $(pt).text().substr(0,9) == 'Cambridge'))  && ($(pst).text() == '24" x 48"' || $(pst).text() == "2' x 4'") ) {
		$(mi).css("height","500px");
		$(mii).css("height","500px");
		$(mifl).css("height","485px");
	}
	else if ( ($(pst).text() == '24" x 24"' || $(pst).text() == "2' x 2'") || ($(pst).text() == '23 3/4" x 23 3/4"' || ($(pst).text() == '24" Length') || ($(pst).text() == '1in. x 2ft.') || ($(pst).text() == '1in. x 100ft.'))) {
		$(mii).css("height",h+"px");
		$(mifl).css("height",h+25+"px");
		$('#mainImage').css("height",h+"px");
		$('.fadeHelp').css("display","none");
	}
	else {
		$(mii).css("height","500px");
		$(mifl).css("height","485px");
	}			

   reloadPricingGrid(qiv,tileProductID,tilePrice);
}

function setSize24(li){
	var isBttOnCeilume = checkBttOnCeilume();
	s = $('li.productSize24x24');	
	//Set the height 
	$(mifl).css("height",'200px');
	if (($('#hostNameHolder').html() != 'btt') && !isBttOnCeilume) {
		$(mii).css("height", "250px");
		$(mii).css("width", "250px");
	}
	else {
		$(mii).css("width", "250px");
		$(mii).css("height", "250px");
	}
//	miiMIFLH = s.attr('heightPixels')+'px';
//	$(mi).css("height",miiMIFLH);
	$(pst).empty().append("2' x 2'"); 
	$(pst2).empty().append("2' x 2'"); 	
	qiv = $(qi2).text();
	if( ($('#hostNameHolder').html() != 'btt') && !isBttOnCeilume)
	   $('#mainImage').css("height","250px");
	else
	   $('#mainImage').css("height","250px");
	//Set the array index for the color that was chosen by the user
	colorandSizeIndex = getColorIndex(pct,"2' x 2'");
	if (colorandSizeIndex == undefined) {
		// Failed matching [2' x 4'], try matching [24" x 48"]
		colorandSizeIndex =  getColorIndex(pct,'24" x 24"');
	}
	//console.log('sS24 colorandSizeIndex: '+colorandSizeIndex);
	prodTitle = ListGetAt(productDetails.title,colorandSizeIndex);
	$(pt).empty().append(prodTitle);	// Main product title
	$(bpt).empty().append(prodTitle);	// Breadcrumb product title
	document.title = prodTitle;			// Page title (<head><title/></head>)
	var highestPriceBreak = ListGetAt(productDetails.pricebreaks[colorandSizeIndex], ListLen(productDetails.pricebreaks[colorandSizeIndex]));
	//Set the "as low as" price based on the size and color selected.	
	$(mp).empty().append('$'+setTilePrice(highestPriceBreak,colorandSizeIndex));
	tileProductID = ListGetAt(productDetails.productid,colorandSizeIndex);
	//alert('load description from setsize24()');
	getProductDescription(tileProductID);

	//Set the tile price for the color and quantity that has been chosen by the user
	qivPlusTotalTileCount = parseInt(totalTileCountNonSamples) + parseInt(qiv);
	
	//Empty and update prices based on the price breaks  	
	tilePrice = setTilePrice(qivPlusTotalTileCount,colorandSizeIndex);
	//console.log(qiv);
	//console.log(tilePrice);	
	
	updateTilePricing(tilePrice,colorandSizeIndex);
	
	link = "&selectedTilePrice="+tilePrice+"&productID="+tileProductID+"&quantity="+qivPlusTotalTileCount+"&color="+$(pct).text()+"&size="+URLEncodedFormat($(pst).text())+"&title="+URLEncodedFormat($(pt).text())+"&TB_iframe=true&KeepThis=true";
	$(mvl).attr("href",linkMVL+link);		
	$(mvl2).attr("href",linkMVL+link);		
	$(atcq).attr("value",qiv);
	$(atcpid).attr("value",tileProductID);		
	$(sid).attr("value",tileProductID);
	$(pst48).css("text-decoration","underline");
	$(pst48).css("cursor","pointer");
	$(pst24).css("cursor","default");
	$(pst24).css("text-decoration","none");
	boldBorder24x24();
	//Get the 2by2 color image filename that is stored in the color li element with classname .productColor____
	var productColorClassName = ".productColor"+$(pct).text();
	//console.log(productColorClassName);
	productColorClassName = Replace(productColorClassName," ","");
	//alert('about to load cif from setSize24');
	var cif = ListGetAt(productDetails.filename,colorandSizeIndex);	
					
    if (!cif.matcumb) {
        if ($('#hostNameHolder').html() != 'btt' && !isBttOnCeilume) {
            cif = cif.replace('.jpg', '_thumb250.jpg');
        }
        else {
            cif = cif.replace('.jpg', '_thumbBTT.jpg');
        }
        if ($('#hostNameHolder').html() != 'btt' && !isBttOnCeilume) {
            $(mii).attr("src", cdnProductImageURL + cif);
        }
        else {
            cif = cif.replace('_thumb250.jpg', '_thumbBTT.jpg');
            $(mii).attr("src", cdnProductImageURL + cif);
        }
    }
    else {
        $(mii).attr("src",cdnProductImageURL+cif);
    }


	var temp = $(mii).attr("src");
	//console.log(temp);

	// 8/5/09: I'M NOT SURE WHY WE'RE REPLACING WHITE IMAGES WITH 2X4 PICS, SO I'M COMMENTING IT OUT FOR NOW
/*	if ($(pct).text() == 'White') {
		$(mii).attr("src",cdnProductImageURL+img24);
		//console.log('white');
	}*/	
	if ($(mii).attr("src") == '/CeilingTiles/') {
		$(mii).attr("src","/CeilingTiles/imageNotAvailable24X24.jpg");
	}
		
	var linkPDF24 = "/productPDFS/"+filenamePDF24;
	$('.productPDFLink').attr("href",linkPDF24);
	var galleryLink = ListGetAt(productDetails.gallerylink,colorandSizeIndex);
	if (galleryLink != "") {
		$('p.custinstallButton').html('<img src="/images/custinstall_button.jpg" align="center">');	
		$('.galleryLink').attr('href',galleryLink);
	}
	else {
		$('p.custinstallButton').html("");	
	}
   reloadPricingGrid(qiv,tileProductID,tilePrice);
	$('#addsampletocartbutton').css('display','inline');
}

function setSize48(li){
	$('#sizeSelect').val("2ft. x 4ft.");
	//console.log("setSize48");
	s = $('li.productSize24x48');
	//colorIndex =  getColorIndex(pct,'24" x 48"');
	//console.log(colorIndex);
	//console.log('pct: '+pct);
	//console.log('pctText: '+$(pct).text());	
	colorIndex =  getColorIndex(pct,"2' x 4'");
	if (colorIndex == undefined) {
		// Failed matching [2' x 4'], try matching [24" x 48"]
		colorIndex =  getColorIndex(pct,'24" x 48"');
	}
	//console.log(colorIndex);
	colorandSizeIndex = colorIndex;
	//console.log('colorandSizeIndex: '+colorandSizeIndex);
	prodTitle = ListGetAt(productDetails.title,colorandSizeIndex);
	$(pt).empty().append(prodTitle);	// Main product title
	$(bpt).empty().append(prodTitle);	// Breadcrumb product title
	document.title = prodTitle;			// Page title (<head><title/></head>)
	//Add one because this is size 24" x 48"
	//colorandSizeIndex = colorIndex+1;
	$('#mainImage').css("height","500px");
	//alert('about to load cif from setSize48');
	//console.log('filename: '+productDetails.filename);
	//console.log('CSI: '+colorandSizeIndex);
	var cif = ListGetAt(productDetails.filename,colorandSizeIndex);
	//console.log('cif: '+cif);
	//var productDescription = productDetails.description[colorandSizeIndex];
	//$(productD).empty().append(productDescription); 
				
	var isBttOnCeilume = checkBttOnCeilume();
		
	//w = productDetails.DATA['WIDTH'][colorandSizeIndex];	
	h = 250;
	//alert('pct: '+ $(pct).text() + ', pt.text: '+ $(pt).text());
	//alert('not white and not cambridge: ' + $(pct).text() != 'White' && ($(pt).text().substr(0,9) != 'Cambridge'));
	if( ($('#hostNameHolder').html().trim() == 'btt')  || isBttOnCeilume) {
       $(mi).css("height", "500px");
       $(mi).css("width", "250px");
       $(mi).css("margin-bottom","10px");
       $(mii).css("height","500px");    
    }
	/*else if (($('#hostNameHolder').html() != 'btt') && !isBTTColor($(pct).text()) && $(pct).text() != 'White' && $(pct).text() != 'White Gloss' && ($(pt).text().substr(0,9) != 'Cambridge')) {
		$(mii).css("height",h+"px");
		$(mifl).css("height",h+25+"px");
		$('#mainImage').css("height",h+"px");
	} */
	else {
		$(mii).css("height","500px");
		$(mifl).css("height","485px");			
		$(mifl).css("padding-bottom","35px");	
					
	}			
	//var cif = ListGetAt(productDetails.filename,1);
	//alert(colorandSizeIndex + " " + cif);
	
    if (!cif.match('thumb')) {
        if ($('#hostNameHolder').html() != 'btt' && !isBttOnCeilume) {
            cif = cif.replace('.jpg', '_thumb250.jpg');
        }
        else {
            cif = cif.replace('.jpg', '_thumbBTT.jpg');
        }
        if ($('#hostNameHolder').html() != 'btt' && !isBttOnCeilume) {
            $(mii).attr("src", cdnProductImageURL + cif);
        }
        else {
            cif = cif.replace('_thumb250.jpg', '_thumbBTT.jpg');
            $(mii).attr("src", cdnProductImageURL + cif);
        }
    }
    else {
        $(mii).attr("src",cdnProductImageURL+cif);
    }
	
	if( ($('#hostNameHolder').html().trim() != 'btt')  && !isBttOnCeilume)
	   $(mii).css("width","250px");
	else
	   $(mii).css("width", "250px");
	//$('li[@class^=productColor]').css("display","none"); //hide the colors that are available in the other size
	//$('li[@class^=productColor2by4]').css("display","inline");  //show the colors that are available in this size
	miiNextMIFLH = $(mifl).css("height");		
	miiMIFLH = s.attr('heightPixels')+'px';
	//console.log("sS48 productSizeName: "+s.attr('productSizeName'));
	$(pst).empty().append("2' x 4'"); 
	$(pst2).empty().append("2' x 4'"); 
	qiv = $(qi2).text();
	//Set the tile price for the color and quantity that has been chosen by the user
	qivPlusTotalTileCount = parseInt(totalTileCountNonSamples) + parseInt(qiv);

	var highestPriceBreak = ListGetAt(productDetails.pricebreaks[colorandSizeIndex], ListLen(productDetails.pricebreaks[colorandSizeIndex]));
	//Set the "as low as" price based on the size and color selected.
	$(mp).empty().append('$'+setTilePrice(highestPriceBreak,colorandSizeIndex));
	//Based on the quantity (qiv), the size, and the color set the tile price and set the productID 
	tileProductID = ListGetAt(productDetails.productid,colorandSizeIndex);
	//alert('load description from setsize48()');	
	getProductDescription(tileProductID);
	//console.log(ListGetAt(priceLevelsAll,1+((colorandSizeIndex)*7)));
	//console.log(qiv);
	tilePrice = setTilePrice(qivPlusTotalTileCount,colorandSizeIndex);	
	dollarsTotal = CurrencyFormatted(qiv*tilePrice);
	//console.log(qiv);console.log(tilePrice);console.log(dollars);
	
	updateTilePricing(tilePrice,colorandSizeIndex);
	
	link = "&selectedTilePrice="+tilePrice+"&productID="+tileProductID+"&quantity="+qivPlusTotalTileCount+"&color="+$(pct).text()+"&size="+URLEncodedFormat($(pst).text())+"&title="+URLEncodedFormat($(pt).text())+"&TB_iframe=true&KeepThis=true";
	var linkMVL = "/moreViews/index.cfm?height=520&width=700";

	$(mvl).attr("href",linkMVL+link);		
	$(mvl2).attr("href",linkMVL+link);
	$(atcpid).attr("value",tileProductID);		
	$(sid).attr("value",tileProductID);
	$(atcq).attr("value",qiv);
	$(pst24).css("text-decoration","underline");
	$(pst24).css("cursor","pointer");
	$(pst48).css("cursor","default");
	$(pst48).css("text-decoration","none");
	boldBorder24x48();
	var linkPDF48 = "/productPDFS/"+filenamePDF48;
	$('.productPDFLink').attr("href",linkPDF48);		
	
	
	
	var galleryLink = ListGetAt(productDetails.gallerylink,colorandSizeIndex);
	if (galleryLink != "") {
		$('p.custinstallButton').html('<img src="/images/custinstall_button.jpg" align="center">');	
		$('.galleryLink').attr('href',galleryLink);
	}
	else {
		$('p.custinstallButton').html("");	
	}

	reloadPricingGrid(qiv,tileProductID,tilePrice);

}

function reloadPricingGrid(qiv,tileProductID,tilePrice) {
	//console.log(qiv);
	if (qiv == '' || isNaN(qiv)) {
		qiv = 0;
	}
	//console.log(qiv);
// priceListLink
  if ($('#hostNameHolder').html() != 'btt' && $('#hostNameHolder').html() != 'lws') {
  	if (qiv != 0) {
  		// Only need to reload price grid for non-zero quantities
				$.ajax({
					type: "GET",
					url: "/getVolumeDiscountGrid.cfm?productID=" + tileProductID + "&quantity=" + qiv + "&selectedTilePrice=" + tilePrice,
					cache: false,
					success: function(data){
						if (data.error) {
						//console.log(data.error);
						}
						else {
							$('#containerVolumePricing').html(data);
						//console.log(tileProductID);
						}
					}
				});
			}
		}
		
	   var buildUrl = "/getVolumeDiscountGrid.cfm?productID=" + tileProductID + "&quantity=" + qiv + "&selectedTilePrice=" + tilePrice + "&templated=false";
	   $('.priceListLink').attr("href", buildUrl);
}

function getProductDescription(tileProductID) {
	
	$.ajax({
					type: "GET",
					url: "/getProductDescription.cfm?productID="+tileProductID,
					cache:false,
					success: function(data){
						if(data.error){
							//console.log(data.error);
						}
	               		else{
							$('#productDescription').html(data);
							//console.log(tileProductID);
						}
					}
	});
}
	
function setTilePrice(qiv,colorandSizeIndex) {
	var result = 0;
	var priceLevelsList = productDetails.pricelevels[colorandSizeIndex-1];
	
	var priceBreaksList = productDetails.pricebreaks[colorandSizeIndex-1];
	var pl = new Array();
	var pb = new Array();
	for (i = 0; i < ListLen(priceLevelsList); i++) {
		pl[i]=parseFloat(ListGetAt(priceLevelsList, i+1));	
	}
	for (i = 0; i < ListLen(priceBreaksList); i++) {
		pb[i]=parseInt(ListGetAt(priceBreaksList, i+1));	
	}
	for (i=pb.length;i>=1;i--) {
		if (qiv >= pb[i]) {
			result = pl[i];
			break;
		} 
	}
	if (result == 0) {
		result = pl[0];
	}
	return result;
}

function updateTilePricing(tilePrice,colorandSizeIndex) {
	qiv = $(qi2).text();

	//Show the customer what they have saved from the base ceiling tile price
	retailPrice = ListGetAt(productDetails.retailprice,colorandSizeIndex);
	retailTotalDollars = CurrencyFormatted(qiv*retailPrice);
	discountedTotalDollars = CurrencyFormatted(qiv*retailPrice - qiv*tilePrice);

	
	// Also update minimum order quantity
	minQty = ListGetAt(productDetails.pricebreaks[colorandSizeIndex-1],1);
	if (minQty == 'undefined') {
		if  (!isNaN(productDetails.pricebreaks)) {
			minQty = productDetails.pricebreaks;
		}
		else {
			minQty = 1;
		}
	}

	$(qmv).attr("value",minQty);
	// Only print min qty message when > 1
	if (minQty == 1) {
		//$(qm).empty().append('(No Minimum Order Quantity)');
		$(qm).empty();
		$(qm).addClass('hidden');
	}
	else {
		$(qm).removeClass('hidden');
		$(qm).empty().append('(Minimum Order of '+minQty+')');
	}
	
	dollarsTotalPrice = CurrencyFormatted(qiv*tilePrice);
	perText = ListGetAt(productDetails.pertext,colorandSizeIndex);
	if (perText == undefined) {
		perText = productDetails.pertext;
	}
	$(tileppt).empty().append(perText);
	$(tilep).empty().append(DollarFormat(tilePrice));
	if ((retailPrice != undefined) && (tilePrice != retailPrice)) {
		$(tilepr).empty().append('('+DollarFormat(retailPrice)+' Retail)');
	}
	else {
		$(tilepr).empty();
	}
	
	if(retailTotalDollars != 0) {
		$(totalpr).empty().append(DollarFormat(retailTotalDollars));
	}
	else {
		$(totalpr).empty();
	}
	$(totalp).empty().append(DollarFormat(dollarsTotalPrice));
	$(totalp2).empty().append(DollarFormat(dollarsTotalPrice));
}

//Set the array index for the current color and size
function getColorIndex(pct,pst) {
	//alert('getColorIndex invoked');
	var pctText = '';
	//alert(pct);
	if (pct.search(/product/i) != -1) {
		pctText = $(pct).text();
	}
	else {
		pctText = pct;	
	}
	//alert(pctText);
	var pstText = '';
	if (pst.search(/product/i) != -1) {
		pstText = $(pst).text();
	}
	else {
		pstText = pst;	
	}
	//alert('pctText: '+pctText);
	//alert('pstText: '+pstText);
	for(var index=0;index<ListLen(productDetails.productid)+1; index++) { 
		if ((pctText == ListGetAt(productDetails.color,index)) && (pstText == ListGetAt(productDetails.size,index)))
		{
			//alert(pct + " matched: "+$(pct).text() + "\n" + pst + " matched: "+pst + "\nat " + index + "\n" + productDetails.DATA['FILENAME'][index]);
		 //console.log(index);
		
		 return index;
		}
	}
}

function isBTTColor(c) {
	bttColor = false;
	if (c == 'Paintable White' || c == 'Bronze' || c == 'Copper' || c == 'Tin') {
		bttColor = true;	
	}
	//console.log(bttColor);
	return bttColor;
}

function checkBttOnCeilume () {
	bttOnCeil = false;
	if (($('#hostNameHolder').html() == 'lws' || $('#hostNameHolder').html() == 'ceilume') && isBTTColor($(pct).text()) == true) {
		bttOnCeil = true;
	}
	//console.log('site: '+$(pct).text()+', host: '+$('#hostNameHolder').html()+', bttOnCeil='+bttOnCeil);
	return bttOnCeil;
}


function Replace(s,sb1,sb2,sc) {
	s += "";
	if(!sc || sc.toUpperCase() != "ALL"){
		sc = "";
	} else {
		sc ="g";
	} 	
	var re = new RegExp(sb1,sc);
	return s.replace(re,sb2);
}
function URLDecode(s) {
	return unescape(s);
}
function URLEncodedFormat(s) {
	return encodeURI(s);
}
function ListGetAt(l, p, d) {
	l += ""; // cheap way to convert to a string
	if(!d){d = ",";}
	return l.split(d)[p - 1];
}
function ListLen(l,d) {
	l += ""; // cheap way to convert to a string
	if(!d){d = ",";}
	if(l.length){return l.split(d).length;}
	return 0;
}
function ListFind(l,v,d){
		l += ""; // cheap way to convert to a string
		if(!d){d = ",";}
		var r = 0;
		var listToArray = l.split(d);
		for (var i=0; i < listToArray.length; i++){
			if (listToArray[i] == v){
				r = i + 1;
				break;
			}
		}
		return r;
}
function boldBorder24x24() {
	$('.productSize24x24').css("border","2px solid #3FBBEF");
	$('.productSize24x24').css("height","20px");
	$('.productSize24x24').css("width","20px");
	$('.productSize24x48').css("border","1px solid #393837");
	$('.productSize24x48').css("height","20px");
	$('.productSize24x48').css("width","40px");
	$('.productSize24x48').css("cursor","pointer");
	$('.productSize24x24').css("cursor","default");		
}
function boldBorder24x48() {
	$('.productSize24x24').css("border","1px solid #393837");
	$('.productSize24x24').css("height","20px");
	$('.productSize24x24').css("width","20px");
	$('.productSize24x48').css("border","2px solid #3FBBEF");
	$('.productSize24x48').css("height","20px");
	$('.productSize24x48').css("width","40px");
	$('.productSize24x24').css("cursor","pointer");
	$('.productSize24x48').css("cursor","default");	
}
function CurrencyFormatted(amount) {
	var i = parseFloat(amount);
	if(isNaN(i)) { i = 0.00; }
	var minus = '';
	if(i < 0) { minus = '-'; }
	i = Math.abs(i);
	i = parseInt((i + 0.005) * 100);
	i = i / 100;
	s = new String(i);
	if(s.indexOf('.') < 0) { s += '.00'; }
	if(s.indexOf('.') == (s.length - 2)) { s += '0'; }
	s = minus + s;
	return s;
}
function	DollarFormat(n) {
	var _n = n.toString().replace(/\$|\,/g,'');
	_n = _n.toString().replace('(','-');
	_n = _n.toString().replace(')','');
	if(isNaN(_n)){
		_n = 0;
	}
	var	sign = (_n == (_n = Math.abs(n)));
		_n = Math.floor(_n*100+0.50000000001);
	var	cents = _n%100;
		_n = Math.floor(_n/100).toString();		
	if(cents < 10){
		cents = "0" + cents;
	}
	_n += "." + cents;
	return (((sign)?'':'(') + '$' + _n + ((sign)?'':')'));
}
