$(document).ready(function() {
    $("li.qtyScrollerRow").click(function(event) {
        selectQtyRdo(this, true);
    });

    $("li.materialScrollerRow").click(function(event) {
        selectMaterialRdo(this);
    });
});

function ValidateProduct() {

    var productName = GetSelectedProduct();
    var qty = GetSelectedQty();

    if (productName == '0') {
        alert('Please select a material from the list.');
        return false;
    }
    else if (qty == '0') {
        alert('Please select the number of sheets required.');
        return false;
    }
    else if (qty == '-1') {
        var txtQuantity = document.getElementById('txtCustomQty');
        var quantity = txtQuantity.value.replace(/\,/g, ''); //removes all commas in the qty
        if (quantity > 0) {
            if (isInteger(quantity) == false) {
                alert("Invalid number of sheets.");
                return false;
            }
        }
        else {
            alert("Invalid number of sheets.");
            return false;
        }
    }

    return true;
}

function openDetail(page){		
	window.open(page,"thisName", "directories=0,height=300,width=325");
}


var js;

function MaterialChanged() {
    var productName = GetSelectedProduct();
	
	SetShippingCalcMaterial();
	
	if (productName == '0')
	    return;

	var imagesGenerated = document.getElementById('ctrlImagesGenerated').value;
	var bIsCustom = imagesGenerated == 1 ? 0 : 1;
	
	js = document.createElement('script');
	js.type = 'text/javascript';
	js.src = '/Products/GetPricingJS5.aspx?ProductName=' + productName + '&IsCustom=' + bIsCustom;
	
	var head = document.getElementsByTagName('head')[0];
	head.appendChild(js);
}

function SetShippingCalcMaterial() {
    var productName = GetSelectedProduct();
	var shippingCalcProduct = (productName != '0') ? productName : document.getElementById('ctrlProductCategory').value;
   
    var lnkShippingCalculator = document.getElementById('lnkShippingCalculator')
    var url = lnkShippingCalculator.href;
    
	var startIndex = url.indexOf('Product=');
	var endIndex = url.indexOf('&', startIndex);
	
    url = url.substring(0, startIndex) + 
            'Product=' + shippingCalcProduct + 
            url.substring(endIndex, url.length);
            
    lnkShippingCalculator.href = url;
}

function SetShippingCalcQty() {
	var quantity = GetSelectedQty();
	
    var lnkShippingCalculator = document.getElementById('lnkShippingCalculator')
    var url = lnkShippingCalculator.href;
    
    var startIndex = url.indexOf('Qty=');
	var endIndex = url.indexOf('\'', startIndex);
	
    url = url.substring(0, startIndex) + 
            'Qty=' + quantity + 
            url.substring(endIndex, url.length);
            
    lnkShippingCalculator.href = url;
}

function UpdatePricing(bIsCustom) {
    var rdoBtns = document.getElementsByTagName("input");
    for (var i = 0; i < rdoBtns.length; i++) {
        if (rdoBtns[i].name == "qtySelect" && parseInt(rdoBtns[i].value) > 0) {
            var qty = rdoBtns[i].value;
            var price = prices[qty];
            var savePct = prices['savePct' + qty];

            var qtySelectName = rdoBtns[i].id.replace('qtySelect', 'qtySelectPrice');
            document.getElementById(qtySelectName).innerHTML = price;

            var qtySelectSavingsName = rdoBtns[i].id.replace('qtySelect', 'qtySelectSavings');

            if (savePct > 0) {
                document.getElementById(qtySelectSavingsName).innerHTML = 'Save ' + savePct + '%';
            }
            else {
                document.getElementById(qtySelectSavingsName).innerHTML = '';
            }
        }
    }

	setTimeout('RemovePricingJS();', 0);
	
	if (bIsCustom == '0')
		document.getElementById('ctrlOrderBox_ProductImage').src = '/images/products/' + productCategory + '/' + productImage;
	else
		document.getElementById('ctrlOrderBox_ProductImage').src = '/images/products/nophoto.gif'

    var productName = GetSelectedProduct();
	
	var h1 = document.getElementById('ctrlOrderBox_h1');
	var startIndex = h1.innerHTML.indexOf('OL');
	var endIndex = h1.innerHTML.indexOf(' ', startIndex);
	h1.innerHTML = h1.innerHTML.substring(0, startIndex) + productName + h1.innerHTML.substring(endIndex, h1.innerHTML.length);
}

function RemovePricingJS() {
	delete prices;
	
	var head = js.parentNode;
	
	if (head)
	    head.removeChild(js);
	    
	delete js;
}

function SelectMaterialQty(product, qty) {
    var rdoMaterial;
    var rdoQty;
    var rdoBtns = document.getElementsByTagName("input");
    for (var i = 0; i < rdoBtns.length; i++) {
        if (rdoBtns[i].name == "rdoMaterial" && rdoBtns[i].value.toUpperCase() == product.toUpperCase()) {
            rdoMaterial = rdoBtns[i];
        }
        else if (rdoBtns[i].name == "qtySelect" && rdoBtns[i].value == qty) {
            rdoQty = rdoBtns[i];
        }
    }

    // scroll to correct qty, set this before materail
    if (rdoQty) {
        var f = function() {
            selectQtyRdo(rdoQty.parentNode.parentNode, false);

            var obj = rdoQty.offsetParent;
            var y = 0;

            while (obj.offsetParent && obj.offsetParent.id != 'qtySelectBoxContent') {
                y += obj.offsetTop;
                obj = obj.offsetParent;
            }

            document.getElementById('qtySelectBoxContent').scrollTop = y;   
        }

        // using setTimeout fixes issue with AJAX not always working
        setTimeout(f, 0);
    }

    // scroll to correct material
    if (rdoMaterial) {
        var obj = rdoMaterial.offsetParent;
        var y = 0;

        while (obj.offsetParent && obj.offsetParent.id != 'materialScrollerBox') {
            y += obj.offsetTop;
            obj = obj.offsetParent;
        }

        document.getElementById('materialScrollerBox').scrollTop = y;

        // using setTimeout fixes issue with AJAX not always working
        setTimeout(function() {selectMaterialRdo(rdoMaterial.parentNode);}, 0);
    }
	
	window.location.href = "#";
}

function SelectCustomQty() {
    var li = $(".qtyScrollerRow")[0];
    selectQtyRdo(li, true);
    document.getElementById('qtySelectBoxContent').scrollTop = 0;
}


var isIE6 = false;
if (typeof document.addEventListener != 'function') isIE6 = true;

function showPromise() {
	if (isIE6 == true) {
		document.getElementById('ourPromiseIframe').style.top = getScrollY() + 70 +'px';
		document.getElementById('ourPromiseIframe').style.display = 'block';
	}
	document.getElementById('ourPromisePopup').style.top = getScrollY() + 50 +'px';
    document.getElementById('ourPromisePopup').style.display = 'block';
    document.getElementById('ourPromiseShadow').style.top = getScrollY() + 35 +'px';
    document.getElementById('ourPromiseShadow').style.display = 'block';  
}

function hidePromise() {
	if (isIE6 = true) {
		document.getElementById('ourPromiseIframe').style.display = 'none';
	}
		document.getElementById('ourPromisePopup').style.display = 'none';	
	     document.getElementById('ourPromiseShadow').style.display = 'none';  
}			

function getScrollY()
{
	var scrOfY = 0;
	if( typeof( window.pageYOffset ) == 'number' ) {
		//NS
		scrOfY = window.pageYOffset;
	} 
	else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
		//DOM compliant
		scrOfY = document.body.scrollTop;
	} 
	else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
		//IE6 standards compliant mode
		scrOfY = document.documentElement.scrollTop;
	}
	return scrOfY;
}

function toggleToChart(e) {
	if (e == 'high') {
	    if (document.getElementById('tblSmallQty')) {
	        document.getElementById('tblSmallQty').style.display = 'none';
	    }
	    
	    document.getElementById('tblLowQty').style.display = 'none';
	    document.getElementById('tblHighQty').style.display = 'block';
	}
	else if (e == 'low') {
	    if (document.getElementById('tblSmallQty')) {
	        document.getElementById('tblSmallQty').style.display = 'none';
	    }
	    
	    document.getElementById('tblLowQty').style.display = 'block';
		document.getElementById('tblHighQty').style.display = 'none';
	}
	else if (e == 'small') {
	    if (document.getElementById('tblSmallQty')) {
	        document.getElementById('tblSmallQty').style.display = 'block';
	    }
	    
		document.getElementById('tblLowQty').style.display = 'none';
		document.getElementById('tblHighQty').style.display = 'none';
	}
}


var timeoutID;

var stateOn = "on";
var stateOff = "off";

function materialHover (mat, state, lnk) {
    clearTimeout(timeoutID);

    if (typeof (matInfo) == 'undefined') {
        return;
    }

	var div = document.getElementById('materialInfoHover');
	var	divContainer = document.getElementById('materialScrollerBox');
	var text = document.getElementById('materialInfoTxt');

	if (state == 'off') { 
		if (isIE6 == true) document.getElementById('materialInfoIframe').style.display = 'none';
		div.style.display = 'none';
        text.innerHTML = '';
	}
	if (state == 'on') {
		var f = function() {
			if (isIE6 == true) document.getElementById('materialInfoIframe').style.display = 'block';
			
			div.style.top = FindPosY(lnk) - divContainer.scrollTop + 25 + 'px';		
			div.style.left = FindPosX(lnk) - 0 + 'px';
			text.innerHTML = matInfo[mat].desc;
			div.style.display = 'block';
		}
		timeoutID = setTimeout(f, 500);		
	}
}

function selectMaterialRdo(li) {
	var rdoName = li.id.replace('li', 'rdo');
	var rdo = document.getElementById(rdoName);
	rdo.checked = true;

	//background color on li
	
	var liArray = document.getElementsByTagName("li");
	for (var i=0; i<liArray.length; i++) {
		if (liArray[i].className.indexOf("materialScrollerRow") == 0) liArray[i].style.background = "#f9f9f9"; 
	}
	li.style.background = '#fff2be';

	// using setTimeout fixes issue with AJAX not always working
	setTimeout('MaterialChanged();', 0);
	setTimeout('Availability();', 0);
}

var currentQty = '';

function selectQtyRdo(li, checkAvailability) {
    
    var rdo = $(".qtySelectRdo > input", li)[0];
    if (rdo.value == currentQty) return;
    currentQty = rdo.value;
    rdo.checked = true;
    $(".qtyScrollerRow").removeClass("selectedHeight");
    $(".qtyScrollerRow").removeClass("selectedRow");
    $("#custQtyExpanded").parent()[0].style.height = '';
    HideCustomQtyPrice();
    
    
    $(li).addClass("selectedRow");
    
    
    $('.qtySelectRTA').hide();

    if (rdo.value == '-1') { // Custom qty
        $("#custQtyCollapsed").hide();
        $("#custQtyExpanded").show();
        //$("#custQtyExpanded").parent().addClass("customExpandedHeight");
    }
    else {
        $("#custQtyExpanded").hide();
        $("#custQtyCollapsed").show();
    }

    if (checkAvailability) {
        // using setTimeout fixes issue with AJAX not always working
        setTimeout('Availability();', 0);
    }
}


function FindPosY(obj)
{
	var curtop = 0;  
	if (obj.offsetParent) {
		while(true) {
			curtop += obj.offsetTop;
			if (!obj.offsetParent)
				break;
			obj = obj.offsetParent;
		}
	}
	else if(obj.y) {
		curtop += obj.y;
	}		   
	return curtop;
}

function FindPosX(obj)
{
    var curleft = 0; 
    if (obj.offsetParent) {
        while(true) {
            curleft += obj.offsetLeft;
            if(!obj.offsetParent)
                break;
            obj = obj.offsetParent;
        }
    }
    else if(obj.x) {
        curleft += obj.x;
    }
    return curleft;
}

function showMaterialSort(){
	document.getElementById('materialSorter').style.display = 'block';
}

function hideMaterialSort(){
	document.getElementById('materialSorter').style.display = 'none';
}

function GetSelectedProduct() {
    var rdoBtns = document.getElementsByTagName("input");
    for (var i = 0; i < rdoBtns.length; i++)
        if (rdoBtns[i].name == "rdoMaterial" && rdoBtns[i].checked)
            return rdoBtns[i].value;

    return '0';
}

function GetSelectedQty() {
    var rdo = GetSelectedQtyRdo();

    if (rdo)
        return rdo.value;
    else
        return '0';
}

function GetSelectedQtyRdo() {
    var rdoBtns = document.getElementsByTagName("input");
    for (var i = 0; i < rdoBtns.length; i++)
        if (rdoBtns[i].name == "qtySelect" && rdoBtns[i].checked)
            return rdoBtns[i];

    return null;
}

// Availability
var jsAvail;

function Availability() {
    var productName = GetSelectedProduct();
    var quantity = GetSelectedQty();

    SetShippingCalcQty();

    $('.qtySelectRTA').hide();

    var customQty = document.getElementById('customQty');

    if (productName == '0')
        return;

    if (quantity == '-1') {

        var txtQuantity = document.getElementById('txtCustomQty');
        var sheetquantity = txtQuantity.value.replace(/\,/g, ''); //removes all commas in the qty

        if (sheetquantity > 0)
            CustomQty();
    }

    if (quantity <= '0') {
        return;
    }

    jsAvail = document.createElement('script');
    jsAvail.type = 'text/javascript';
    jsAvail.src = '/Products/GetAvailabilityJS.aspx?ProductName=' + productName + '&Qty=' + quantity;

    var headAvail = document.getElementsByTagName('head')[0];
    headAvail.appendChild(jsAvail);
}

function UpdateAvailability() {
    var rdo = GetSelectedQtyRdo();
    if (!rdo) return;

    var divInStock = $("#divInStock", rdo.parentNode.parentNode)[0];
    var divInProduction = $("#divInProduction", rdo.parentNode.parentNode)[0];

    if (available == true) {
        divInStock.style.display = 'block';
        divInProduction.style.display = 'none';
    }
    else {
        divInStock.style.display = 'none';
        divInProduction.style.display = 'block';
    }
    
    $("li.selectedRow").addClass("selectedHeight") //add height to qty row once RTA comes back
    $("li.selectedRow > .qtySelectRTA").show("fast");
    
    
    setTimeout('RemoveAvailabilityJS();', 0);
}

function RemoveAvailabilityJS() {
    var headAvail = jsAvail.parentNode;

    if (headAvail) {
        headAvail.removeChild(jsAvail);
    }

    delete jsAvail;
}

// Custom qty
function CustomQty() {
    // fixes issue with AJAX not always working
    setTimeout("DelayCustomQty();", 0);
}

function DelayCustomQty() {
    var productName = GetSelectedProduct();
    var quantity = GetSelectedQty();

    if (quantity == '-1') {
        var productName = GetSelectedProduct();
        var txtQuantity = document.getElementById('txtCustomQty');
        var quantity = txtQuantity.value.replace(/\,/g, ''); //removes all commas in the qty

        if (productName == '0') {
            alert('Please select a material from the list.');
            return;
        }

        if (quantity <= '0') {
            HideCustomQtyPrice();
            alert("Invalid number of sheets.");
            return;
        }

        if (quantity > 0) {
            if (isInteger(quantity) == false) {
                alert("Invalid number of sheets.");
                return;
            }
        }
        else {
            alert("Invalid number of sheets.");
            return;
        }

        jsCustomQty = document.createElement('script');
        jsCustomQty.type = 'text/javascript';
        jsCustomQty.src = '/Products/GetCustomQtyJS.aspx?ProductName=' + productName + '&Qty=' + quantity;

        var headCustomQty = document.getElementsByTagName('head')[0];
        headCustomQty.appendChild(jsCustomQty);
    }
    else
        return;

}

function HideCustomQtyPrice() {
    var customQtyPricing = document.getElementById('customQtyPricing');
    var qtySelectCustomRTA = document.getElementById('qtySelectCustomRTA');

    customQtyPricing.style.display = 'none';
    qtySelectCustomRTA.style.display = 'none';
}

function UpdateCustomQty(avail, price, nextQty, nextPrice) {
    var quantity = GetSelectedQty();

    if (quantity != '-1')
        return;    

    document.getElementById('divInStockCustom').style.display = 'none';
    document.getElementById('divInProductionCustom').style.display = 'none';

    if (avail == -1) {
        HideCustomQtyPrice();
        alert('The quantity that you entered is not available in this product.');
        return;
    }
    else if (avail == 1) {
        $("#qtySelectCustomRTA").show();
        $('#divInStockCustom').show("fast");
    }
    else {
        $("#qtySelectCustomRTA").show();
        $('#divInProductionCustom').show("fast");
    }

    $("#custQtyExpanded").parent()[0].style.height = '65px';

    var lblPrice = document.getElementById('lblPrice');
    var lblNextAmount = document.getElementById('lblNextAmount');
    var customQtyPricing = document.getElementById('customQtyPricing');

    customQtyPricing.style.display = 'block'
    lblPrice.innerHTML = "Your price is " + price;

    if (nextQty == '0' && nextPrice == '0')
        lblNextAmount.innerHTML = "";
    else
        lblNextAmount.innerHTML = "*You can order " + addCommas(nextQty) + " sheets for " + nextPrice;
}

function isInteger(s) {
    return (s.toString().search(/^-?[0-9]+$/) == 0);
}

function addCommas(nStr) {
    nStr += '';
    x = nStr.split('.');
    x1 = x[0];
    x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    return x1 + x2;
}

function submitOnKeydown(buttonid, e) {
    var btn = document.getElementById(buttonid);

    if (typeof btn == 'object') {
        if (e.keyCode == 13) {
            btn.focus();
            return false;
        }
    }
}

function RestoreState() {
    var productName = GetSelectedProduct();
    var quantity = GetSelectedQty();
    
    SelectMaterialQty(productName, quantity);
}