﻿// JScript File

//used to position popups
//var posleft = 0;
//var postop = 0;

//Used to store leadtime, stockitem status. 
var stockitem = "";
var leadtime = "";	

//function getOptionPosition(curelem)
//{    
//    for (posleft = 0, postop = 0; curelem.offsetParent; curelem = curelem.offsetParent) 
//	{
//		posleft += curelem.offsetLeft;
//		postop += curelem.offsetTop;
//	}
//}

//function checks if qty is multiples of MinQty field
function validateqty(MinQty, txtboxqty)
{
    elemqty = document.getElementById(txtboxqty);    

    if (elemqty.value == '' || elemqty.value == 0){
        alert("Please enter the quantity.");            
        elemqty.focus();
        return false;
    }
    
    var qty = parseInt(elemqty.value);
    var qtyextra = qty%MinQty;
    if (qtyextra != 0 && MinQty != 0){        
        alert("Order must be in multiples of " + MinQty + ".\nPlease order " + (qty + (MinQty-qtyextra)) + ".");
        elemqty.focus();
        return false;
    }
    
    return true;
}

//validate that all radio groups are selected
function validateRdSelected() {
    var curOptGroupID = "";
    var prevOptGroupID = "";
    var prevGroupHeader = "";
    var prevChecked = false;

    for (i = 0; i < document.aspnetForm.elements.length; i++) {
        elem = document.aspnetForm.elements[i];
        if (elem.type == "radio" && elem.name != "rdaddon") {
            curOptGroupID = elem.parentNode.getAttribute("OptGroupID");

            if (prevOptGroupID != "" && curOptGroupID != prevOptGroupID) {
                //alert(curOptGroupID + "," + prevOptGroupID + "," + prevChecked);
                if (prevChecked)//then reset prevChecked to false for next radio group
                    prevChecked = false;
                else { //not checked. So alert customer that radio must be checked
                    alert("Please " + prevGroupHeader);
                    return false;
                }
            }

            if (elem.checked)
                prevChecked = true;

            prevOptGroupID = elem.parentNode.getAttribute("OptGroupID");
            prevGroupHeader = elem.parentNode.getAttribute("GroupHeader");
        }
    }

    if (prevGroupHeader != "" && prevChecked == false) { //not checked. So alert customer that radio must be checked
        alert("Please " + prevGroupHeader);
        return false;
    }
    
    return true;
}

function validateaddtocart(txtboxqty, hidMinQty, hidPriceView) {
    if (!validateSelAddOnNotExpired())
        return false;

    var curproductid = document.getElementById("productid").value;
    var curPriceView = document.getElementById(hidPriceView).value;
    var MinQty = document.getElementById(hidMinQty).value;
    var price = document.getElementById("price").value;

    if (leadtime == "")
        leadtime = document.getElementById("leadtime").value;

    var isValidQty;
    if (curPriceView == "case") //then qty not multiples of MinQty. Only singles.
        isValidQty = validateqty(1, txtboxqty);  
    else
        isValidQty = validateqty(MinQty, txtboxqty);

    if (isValidQty == true && validateRdSelected() == true) {    
        //if not stockitem, then verify that customer wants to buy anyway
        if (stockitem == "")
            stockitem = document.getElementById("stockitem").value;

        if (stockitem.toUpperCase() == "FALSE") {
			if (!confirm ("This item " + leadtime + ".\nDo you want to order this item anyway?"))
				return false;
        }        
            
 		//Check if product exists in cart.
//        var curoptionsid = document.getElementById("hidoptionsid").value;        
//        
//        var curaddonproductsid = ""; 
//        if (hidAddOn.Contains("addonproductid"))
//            curaddonproductsid = hidAddOn.Get("addonproductid");
        
//		var inelem = document.getElementsByTagName("INPUT");				
//		var j=0;
//		for (i=0;i<inelem.length;i++){
//		    if (inelem[i].id.indexOf("idproductcart") > -1) {
//		        //alert(curaddonproductsid + "," + document.getElementById("idaddonproductscart" + j).value);
//			
//			    if (curPriceView == document.getElementById("QtyType" + j).value && curproductid == document.getElementById("idproductcart" + j).value && curoptionsid == document.getElementById("idoptionscart" + j).value) {
//					if (!confirm("This product is already in your cart.\nDo you want to add more?"))
//						return false;
//				}
//				j++;
//			}
//		}
		return true;       
    }
    else
        return false;
}

function validateaddcombitemtocart(txtboxqty) {
    var isValidQty;
    isValidQty = validateqty(1, txtboxqty); 
    
    if (isValidQty == true && validateRdSelected() == true) {
        return true;
    }
    else
        return false;
}

function scroll()
{
  scrollTo(0,0);
}

//function showImageAddOn(curelem,image,classdescription)
//{
//    if (!image)
//        return;
//    document.getElementById("imghingeoption").src = "images/products/hingeoptions/" + image + ".jpg";
//    document.getElementById("txthingeoption").innerHTML = classdescription;
//    getOptionPosition(curelem);    
//    document.getElementById("divhingeoption").style.left = (posleft + 50) + "px";
//	document.getElementById("divhingeoption").style.top = (postop + 22) + "px";
//    document.getElementById("divhingeoption").style.display = "";
//}



//begining of options functions  

//Show image of option
function showImage(curelem, fullimageurl, description)
{
    curelem.className = "txtLinkOver";
    
    //clear the for attribute so that a click on the label does not select the radio element
    curelem.parentNode.htmlFor = "";
    
    intxt = "<table cellpadding='0' cellspacing='0' align='center'>";
    intxt += "<tr><td><img src='" + fullimageurl + "'></td></tr>";
    intxt += "<tr><td align='left'><b>" + description + "</b></td></tr>";
    //intxt += "<tr><td align='left'>" + descriptionlong + "</td></tr>";
    intxt += "</table>";
    document.getElementById("divdescription").innerHTML = intxt;
    
    //position the popopup
    getElemPosition(curelem);	
	
	document.getElementById("divdescription").style.left = (posleft) + "px";
	document.getElementById("divdescription").style.top = (postop - 185) + "px";
    
    document.getElementById("divdescription").style.display = "";    
}

function hideImage(curelem)
{
    curelem.className = "txtLink";   
    document.getElementById("divdescription").style.display = "none";
}

//show/hide textbox when checking checkbox of opttype "Input"  
function showInput(curelem,cell2,cell3)
{   
    if (curelem.checked == true)
    {        
        document.getElementById(cell2).style.display = '';  
        document.getElementById(cell3).style.display = '';
        
        document.getElementById(cell3).childNodes[0].focus();
    }
    else
    {
        document.getElementById(cell2).style.display = 'none';
        document.getElementById(cell3).style.display = 'none';    
    }
}

  
//function adds/removes to hidoptionsid the current selected options
function updateOption(curelem, pnladdon)
{
	var selOptProdID = "";
    var totalOptProdID = "";
    var productprefix = "";    
    var optminleadtime = "";
    var isdefault = "False";
    var optRating = "";
    var curclass = "";
    
    stockitem = document.getElementById("stockitem").value;
    leadtime = document.getElementById("leadtime").value;	
     	
	for (i=0; i<document.aspnetForm.elements.length; i++) 
    { 
        elem = document.aspnetForm.elements[i];
        if (elem.type == "checkbox" || elem.type == "radio")
        {
            if (elem.checked)
	        { 
                selOptProdID = elem.parentNode.getAttribute("OptProdID");
                if (totalOptProdID == "")
                    totalOptProdID = selOptProdID;
                else
                    totalOptProdID += "," + selOptProdID;   
                    
                for (var x=0;x<optionArray.length;x++)
                {
                    if (optionArray[x][0] == selOptProdID)
                    {
                        productprefix = optionArray[x][1];                            
                        isdefault = optionArray[x][5];
                                        
                        if (isdefault == "False" && (optminleadtime == "" || (parseInt(optionArray[x][4]) > parseInt(optminleadtime)))) //then use later lead time
                        {
                            stockitem = optionArray[x][2];
                            leadtime = optionArray[x][3];
                            optminleadtime = optionArray[x][4];
                        }                        
                    }
                }

                //Set Frame Label Option
                var activateframeopt = curelem.parentNode.getAttribute("activateframeopt");
                if (activateframeopt != null)
                    hidOptProdID.Set("foptprodid", activateframeopt);                    
                

                //for product add ons     
                //selected options cause changes to productaddons only if selected radio option is not a frame option            
                if (elem.type == "radio" && document.getElementById(pnladdon) != null && elem.parentNode.getAttribute("radiooption") == "true" && curelem.parentNode.getAttribute("combitem") != "frame")
                    updateProdAddOn(elem, pnladdon);

                //adds/remove to hidoptionsid the current selected options
                if (totalOptProdID == "")//then no options
                {
                    document.getElementById("hidoptionsid").value = "";
                }
                else//there are options
                {
                    document.getElementById("hidoptionsid").value = totalOptProdID;
                }

                document.getElementById("spnStock").innerHTML = "Lead Time: " + leadtime;

                if (stockitem.toUpperCase() == "TRUE")
                    document.getElementById("spnStock").className = "txtorange";
                else
                    document.getElementById("spnStock").className = "txtred";

                //if productprefix = "PR" (Pair) - change price, update qty label
                var price = document.getElementById("price").value;
                if (productprefix == "PR") {
                    var newprice = price * 2;
                    document.getElementById("spnprice").innerHTML = "<span class='optionwarning'>" + formatCurrency(newprice) + "</span>";
                    document.getElementById("lmQuantitySpan").innerHTML = "Qty <span class='optionwarning'>Pair</span>";
                }
                else {
                    document.getElementById("spnprice").innerHTML = formatCurrency(price);
                    document.getElementById("lmQuantitySpan").innerHTML = "Qty";
                }
            }
        }
    }
}

function checkAll(curelem,optGroupID)
{
    var elem;
    var selRadioCheckboxGroupID;    
    
    var count;
    count = 0;
    
    for (i=0; i<document.aspnetForm.elements.length; i++) 
    {
	    elem = document.aspnetForm.elements[i];
	    selRadioCheckboxGroupID = elem.parentNode.getAttribute("RadioCheckboxGroupID");

	    if (elem.type == "checkbox" && elem.checked == true)
	    {	    	       
	       if (selRadioCheckboxGroupID == optGroupID)
	       {
	           count ++;         	
	           if (elem != curelem)
	               elem.checked = false;
	       }
	    }
	}
	
	if ( count > 1 )
	{
	    alert("You may only select one checkbox from this group");
	}
}

//end of options functions

//**Begin addonproduct functions**
//function sets display of addongroups available  based on option selected
//ex "No Label" gets a louver but "B Label" gets a fusible link louver
function updateProdAddOn(elem, pnladdon) {
    lblAddOnLeadTime.SetVisible(true);
    var showWarning = false;

    if (hidAddOn.Contains("addonproductid"))
        showWarning = true;

    clearAddOn(true);

    //alert("test");

    //updateAddOnChkboxGroup(this, true);

    optRating = elem.parentNode.getAttribute("OptRating");
    hidAddOn.Set("optrating", optRating);

    if (optRating == "A") { //then no VL or LVR
        document.getElementById(pnladdon).style.display = "none";

        if (showWarning)
            alert("A door with an A Label cannot get a Vision Lite or Louver.");
    }
    else if (optRating == "B" || optRating == "0") {
        document.getElementById(pnladdon).style.display = "";

        for (j = 0; j < document.aspnetForm.elements.length; j++) {
            chkelem = document.aspnetForm.elements[j];

            curclass = chkelem.parentNode.getAttribute("prodClass");
            if (curclass == "VLK")
                chkelem.parentNode.style.display = "";
            else if (curclass == "VLKWTG" || curclass == "LVR") {
                if (optRating == "0")
                    chkelem.parentNode.style.display = "";
                else //rated
                    chkelem.parentNode.style.display = "none";
            }
            else if (curclass == "LVRFL") {
                if (optRating == "B")
                    chkelem.parentNode.style.display = "";
                else //nonrated
                    chkelem.parentNode.style.display = "none";
            }
        }

        if (showWarning)
            alert("Please reselect the add on products.");
    }
}

//find selected addon checkbox
function getSelAddOnGroup() {    
    var seladdon;
    for (j = 0; j < document.aspnetForm.elements.length; j++) {
        chkelem = document.aspnetForm.elements[j];
        if (chkelem.parentNode.getAttribute("addonpopup") == "true" && chkelem.checked) {
            seladdon = chkelem;
            break;
        }
    }
    return seladdon;
}

function viewAddOn(seladdon, prodClass) {
    //Selected "None"
    if (prodClass == "") {
        clearAddOn(true);
        return;
    }

    //If addon from this type already selected then return
    var classdescription = seladdon.parentNode.getAttribute("classDescription");    
    var curlabel = $("label[for*='" + seladdon.id + "']").html();
    if (classdescription != curlabel) 
        return;

    //if there is a selected addon from different addon type, then clear it
    if (hidAddOn.Contains("addonproductid")) {
        clearAddOn(false);
    }

    var optRating = hidAddOn.Get("optrating");
    var curproductid = document.getElementById("dproductid").value; //get DOOR productid to then select available AddOn's

    ASPxLoadingPanel1.Show();
    PageMethods.getAddOnProductList(curproductid, prodClass, optRating, OnAddOnMethodComplete);
}

function OnAddOnMethodComplete(result, userContext, viewAddOn) {
    var intxt = "<table align='center' style='padding:0; margin:0'>";
    intxt += "<tr><td align='center' class='header'>Select " + result[0].ClassDescription + "</td></tr>";
    
    //lead time    
    intxt += "<tr><td align='center' ";
    if (result[0].stockitem == true) 
        intxt += "class='txtorange'";
    else 
        intxt += "class='txtred'";
    intxt += ">" + result[0].leadtime + "</td></tr>";
    
    hidAddOn.Set("leadtime", result[0].leadtime);
    hidAddOn.Set("stockitem", result[0].stockitem.toString().toUpperCase());
    
    var curAddOnType = "";
    var prevAddOnType = "";

    for (i = 0; i < result.length; i++) {
        curAddOnType = result[i].AddOnType;
        if (curAddOnType != prevAddOnType) {
            if (prevAddOnType != "") { //then it's not first item. So end row
                intxt += "</table></td><tr></table></fieldset></td></tr>";
            }

            intxt += "<tr><td align='center'><fieldset class='fieldsetPopup'>";
            intxt += "<legend class='fieldsetLegendPopup'>" + curAddOnType + "</legend>";
            intxt += "<table width='260px'>";            
            //image for group
            intxt += "<tr><td valign='top' align='center' width='100px'><img src='" + result[i].Image + "' /></td>";
            //column 2 for list of items in group
            intxt += "<td valign='top' width='150px'><table>";
        }    
        intxt += "<tr><td align='left' id='traddonlink-" + result[i].ProductID + "'>"
        intxt += "<input type='radio' id='rdaddon' name='rdaddon' value='" + result[i].ProductID + "' onclick='selectAddOn()'>&nbsp;" + result[i].Size + "</td>"
        intxt += "<input type='hidden' id='hidDesc_" + result[i].ProductID + "' value='" + result[i].ProdAndProdDesc + "'>";
        intxt += "<input type='hidden' id='hidPrice_" + result[i].ProductID + "' value='" + formatCurrency(result[i].Price) + "'>";

        intxt += "<td>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</td><td align='left'><i>" + formatCurrency(result[i].Price) + "</i></td></tr>";

        prevAddOnType = result[i].AddOnType;
    }

    
    intxt += "</table></fieldset></td></tr>"
    
    intxt += "</table>";
    document.getElementById("divaddontxt").innerHTML = intxt;


    ASPxLoadingPanel1.Hide();
    PopupAddOn.Show();
}

function editAddOn() {
    document.getElementById("btnClearAddOn").style.display = "";
    PopupAddOn.Show();
}

function selectAddOn() {       
    document.getElementById("divaddonwarning").innerHTML = "";
}

function clearAddOn(selectNone) {
    //clears popup of AddOn's
    var elem = document.getElementsByName("rdaddon");
    for (var i = 0; i < elem.length; i++)
        elem[i].checked = false;

    document.getElementById("btnClearAddOn").style.display = "none";    
    
    //clear AddOnGroup
    for (j = 0; j < document.aspnetForm.elements.length; j++) {
        rdelem = document.aspnetForm.elements[j];
        if (rdelem.parentNode.getAttribute("addonpopup") == "true") {
            //enable all radio options
            rdelem.disabled = false;
            rdelem.parentNode.disabled = false;

            if (selectNone) {
                if (rdelem.value == "None")
                    rdelem.checked = true;
                else
                    rdelem.checked = false;
            }

            var classdescription = rdelem.parentNode.getAttribute("classDescription");

            if (classdescription != "") {
                $("label[for*='" + rdelem.id + "']").html(classdescription);
                hidAddOn.Remove("addonproductid");
            }
        }
    }

    updateAddOnStock(false);   
}

function acceptAddOn() {
    var seladdonproductid = $("input[name='rdaddon']:checked").val();

    if (seladdonproductid == null) {              
        document.getElementById("divaddonwarning").innerHTML = "Please select an item";
    }
    else {
        PopupAddOn.Hide();
        PopupAddOn.SetSize(490, 0);

        hidAddOn.Set("addonproductid", seladdonproductid);

        var selectedItemDesc = "<b>" + document.getElementById("hidDesc_" + seladdonproductid).value + "</b>";
        selectedItemDesc += "&nbsp;<input type='button' class='smbutton' style='float:right' value='Edit' onclick='editAddOn()'>"
        selectedItemDesc += "<br><b>[Add " + document.getElementById("hidPrice_" + seladdonproductid).value + "]</b>";
        

        var seladdon = getSelAddOnGroup();
        $("label[for*='" + seladdon.id + "']").html(selectedItemDesc);         
        
        updateAddOnStock(true);
    }
}

function removeAddOnPopup() {
    clearAddOn(true);

    PopupAddOn.Hide();
    PopupAddOn.SetSize(490, 0);
}

function cancelAddOnPopup() {
    var seladdon = getSelAddOnGroup();

    if (hidAddOn.Contains("addonproductid"))  //since customer clicked cancel, reset button to original selection
        $('[name="rdaddon"][value="' + hidAddOn.Get("addonproductid") + '"]').attr('checked', true);
    else //no product selected
        clearAddOn(true);
        
    PopupAddOn.Hide();
    PopupAddOn.SetSize(490,0);
}

//update the label showing lead time 
function updateAddOnStock(hasAddOn) {
    if (hasAddOn) {
        stockitem = hidAddOn.Get("stockitem");
        leadtime = hidAddOn.Get("leadtime");
    }
    else { //use settings of product without addon
        hidAddOn.Remove("stockitem");
        hidAddOn.Remove("leadtime");
        
        stockitem = document.getElementById("stockitem").value;
        leadtime = document.getElementById("leadtime").value;
    }

    
    document.getElementById("spnStock").innerHTML = "Lead Time: " + leadtime;

    if (stockitem.toUpperCase() == "TRUE")
        document.getElementById("spnStock").className = "txtorange";
    else
        document.getElementById("spnStock").className = "txtred";
}

function validateSelAddOnNotExpired() {
    var seladdon = getSelAddOnGroup();
    var seladdonval;
    if (seladdon != null)
        seladdonval = seladdon.value;

    if (seladdonval != "None" && seladdon != null && !hidAddOn.Contains("addonproductid")) { //then customer selected addon, but addonproductid expired from memory
        clearAddOn(true);
        alert("Your session expired. Please update the Add On Product.");
        return false;
    }

    return true;
}
//end addon

//begin ProductVariety functions
function changeProduct(curelem, productID, tablename, optval) 
{
    PageMethods.getAvailProd(productID, tablename, optval, OnProdMethodComplete);
}

function OnProdMethodComplete(result, userContext, showFuncDetails)
{
    var isMatch;

    for (i = 0; i < document.aspnetForm.elements.length; i++) {
        elem = document.aspnetForm.elements[i];
        isMatch = false;
        if (elem.type == "radio") {
            if (elem.checked) {
                for (j = 0; j < result.length; j++) 
                {
                    //alert(elem.value + "," + result[j].Code);
                    if (elem.value == result[j].Code)
                        isMatch = true;
                }

                if (isMatch == false) {
                    if (!confirm(elem.value + " is not available with this option."))
                        return false;
                }                     
            }
        }
    }

    return true;
}


//end ProductVariety functions

function FieldSelectionChanged(s) {
    if (s.GetValue() != null) {
        SelFilter.SetText(s.GetValue() + " Throat");
        CallBackPanel.PerformCallback();        
    }
}

function clickShowSelectList(s) {
     SelFilter.SetText();
     CallBackPanel.PerformCallback();
}

function changeTab()
{ 
    //Get a Handle to the Tab Behavior 
    var tabBehavior = $get('<%=TabContainer1.ClientID%>').control; 
    //Set the Currently Visible Tab 
    tabBehavior.set_activeTabIndex(1);
}

//used on itemlist.ascx to show function detail
function showFuncDetails(curelem, functionid, mfg) {
    curelem.className = 'txtLinkFunctionOver';

    getElemPosition(curelem);
    PageMethods.getFunctionDetails(functionid, mfg, OnMethodComplete);
}

//used on itemlist.ascx to show arm detail
function showArmDetails(curelem, arm) {
    curelem.className = 'txtLinkFunctionOver';

    getElemPosition(curelem);
    document.getElementById("divfunctiondetails").className = "armpopup";
    PageMethods.getArmDetails(arm, OnMethodComplete);
}

function OnMethodComplete(result, userContext, showFuncDetails) {
    document.getElementById("divfunctiondetailsintxt").innerHTML = "<b>" + result.Func + " " + result.FuncSDesc + "<br>" + "</b>" + result.FuncLDesc;

    document.getElementById("divfunctiondetails").style.top = (postop + 18) + "px";
    document.getElementById("divfunctiondetails").style.left = (posleft) + "px";

    document.getElementById("divfunctiondetails").style.display = "";
}


function closeFunctionDetails(curelem) {
    curelem.className = 'txtLinkFunction';
    document.getElementById("divfunctiondetails").style.display = "none";
}


//used on itemlist.ascx to show list of available handing
function showHandDetails(curelem, productid) {
    ASPxLoadingPanel1.Show();
    PageMethods.getHandDescList(productid, OnHandMethodComplete);
}

//used on combnav.ascx to show list of available handing
function showCombHandDetails(curelem, combgroupitemid) {
    ASPxLoadingPanel1.Show();
    PageMethods.getCombHandDescList(combgroupitemid, OnHandMethodComplete);
}

function OnHandMethodComplete(result, userContext, showHandDetails) {
    var intxt = "<table id='handtable' cellpadding='10px'>";;
    for (i = 0; i < result.length; i++) {
        intxt += "<tr><td align='left' id='trhandlink-" + result[i].Hand + "'><input type='radio' name='rdhand' onclick='selectHandImg(\"" + result[i].Hand + "\",\"" + result[i].URLName + "\")'>&nbsp;<b>" + result[i].Hand + "</b>&nbsp;" + result[i].HandDesc + "</td></tr>";
        intxt += "<tr><td align='left' id='trhandimg-" + result[i].Hand + "' class='hidetr'><img src='" + result[i].Image + "' /></td></tr>";       
    }
    intxt += "</table>";
    document.getElementById("divhandtxt").innerHTML = intxt;

    ASPxLoadingPanel1.Hide();
    divhand.Show();
}

function selectHandImg(hand, URLName) {   
    document.getElementById("divhandwarning").innerHTML = "";
    ASPxHiddenField1.Set("produrl", URLName);

    $('#handtable td').each(function() {
    if ((this).id.indexOf('trhandimg-') > -1) {
            $(this).removeClass("showtr");
            $(this).addClass("hidetr");
        }

        //if ((this).id.indexOf('trhandlink-') > -1) {
        //    $(this).removeClass("txtLinkFunctionSelected");    
        //    $(this).addClass("txtLinkFunctionOver");            
       // }
    })

    document.getElementById("trhandimg-" + hand).className = "showtr";
    //document.getElementById("trhandlink-" + hand).className = "txtLinkFunctionSelected";
}

function validateHand() {
    if (!ASPxHiddenField1.Contains("produrl")) {
        document.getElementById("divhandwarning").innerHTML = "Please select the handing";
        return false;
    }
    return true;
}

function closeHandPopup() {
    divhand.Hide();
    document.getElementById("divhandwarning").innerHTML = "";
    ASPxHiddenField1.Clear();
}
//end itemlist.ascx 
