﻿// --------------------------------------------------------
//  Main Function:  functions to validate controls related to Items
//  Created Date:   01/21/2009
//  Created By:     YW
    
//  Modified Date:  
//  Modified By:    
//  Reason for Modifying: 
// --------------------------------------------------------

// hightlight text box and prefill text box with "1"
function PrefillBuyTextBox(event)
{ 
//    if (event.value == "0")
//    {
//        event.value = "1";
//    }
    event.focus(); 
    event.select();
}
    
// check keys - has to be numbers
function keyhandler(e) 
{
    if (document.layers || navigator.appName=="Netscape")
    {
        Key = e.which;
    }
    else
    {
        Key = e.keyCode;
    }
    
    if (Key != 0 && Key != 46 && Key != 9 && Key != 8 && (Key < 48 || Key > 57)) 
    {
    
        PopupMessage( 'Invalid Number', 'You have entered an invalid number. Please enter a number greater than 1 and less than 2000. <br><br>Thank you!', null, null);
        return false;
    }
    return true;
}


function keyhandlerDisableEnter(e) 
{
    if (document.layers || navigator.appName=="Netscape")
    {
        Key = e.which;
    }
    else
    {
        Key = e.keyCode;
    }
    
    if (Key == 13)
    {
        return false;
    }

    if (Key != 0 && Key != 46 && Key != 9 &&  Key != 8 && (Key < 48 || Key > 57)) 
    {
    
        PopupMessage( 'Invalid Number', 'You have entered an invalid number. Please enter a number greater than 1 and less than 2000. <br><br>Thank you!', null, null);
        return false;
    }
    return true;
}      
    
// validate order qty
function IsValideOrderQty(textBox, e)
{
    var orderFormat = /(\d{4})/;
    var orderQty = textBox.value.replace(' ', '');
        
    if (orderQty.length < 4)
    {
        return true;
    }
    else if (orderQty.length == 4)
    {
        return orderFormat.test(orderQty);
    }    
    else
    {
        if (orderFormat.test(orderQty.substring(0, 4)))
        {
            textBox.value = orderQty.substring(0, 4);
        }
        else
        {
            textBox.value = '0';
        }
        return false;
    }
}

// return true if qty text is not 0
function CheckOrderQty(qtyTextBoxID)
{
    var qtyTxt = GetObject(qtyTextBoxID);
        
    if (qtyTxt && qtyTxt.value)
    {
        if (qtyTxt.value == "0")
        {
            PopupMessage('Buy Quantity', 'The quantity you want to buy is zero. Please enter the quantity you want to buy and then click the Buy All or Buy button. <br><br>Thank you!', null, null);
            return false;
        }
    }
    return true;
}
    
function PopShipFlag()
{   
    PopupMessage( "Shipping Flag", "If there is &ldquo;V&rdquo;, &ldquo;T&rdquo;, &ldquo;A&rdquo; or &ldquo;F&rdquo; in the weight column of the item you are buying…<br><br>PLEASE NOTE<br><br>&ldquo;A&rdquo;, &ldquo;V&rdquo; or &ldquo;T&rdquo; means that the item may have a ship weight that is higher than it’s actual weight because the item is oversized.<br>It may not be combined with other items due to its size.<br>&ldquo;F&rdquo; means the item is too large to go UPS or FedEx and can only be shipped by a trucking company or our trucks.", null, null);
}

// buy one item
//TM 051309: Added new param: isFromHistory
function BuyOneItem(itemCode, qtyTextBoxID, availableQty, popUpHeader, popUpContent, isFromHistory, buttonStr, redirectUrl, redirectUrl2)
{
    var qtyTxt = GetObject(qtyTextBoxID);
    if (qtyTxt && qtyTxt.value && qtyTxt.value != "0")
    {
        if (availableQty >= 0 && qtyTxt.value > availableQty)
        {
            if (buttonStr != null && redirectUrl != null && redirectUrl2 != null)
            {
                PopupMessageItem(popUpHeader, popUpContent, buttonStr, redirectUrl, redirectUrl2 + qtyTxt.value + '&isFromHistory=' + isFromHistory);
            }
            else
            {
                PopupMessage(popUpHeader, popUpContent, null, null);
            }
        }
        else
        {
            GoTo('/Product Pages/AddItem.aspx?ItemList=' + itemCode + ','+ qtyTxt.value + '&isFromHistory=' + isFromHistory);            
        }
    }
    else
    {
        PopupMessage('Buy Quantity', 'The quantity you want to buy is zero. Please enter the quantity you want to buy and then click the Buy All or Buy button. <br><br>Thank you!', null, null);
    }
    return false;
}

// buy all item
//TM 051309: Added new param: isFromHistory
function BuyAllItem(buyAllItemStr, isFromHistory)
{
    var gotoStr = "";
    var hasQty = false;
    var limitStock = false;
    var noneStockItem = "";
    var i;
    var noQtyStr = "";
    if (buyAllItemStr != null)
    {
        var itemTxtList = buyAllItemStr.split("|");
        
        if (itemTxtList != null)
        {
            for (i = 0; i < itemTxtList.length; i ++)
            {
                var oneitem = itemTxtList[i].split(",");
                                    
                if (oneitem != null && oneitem.length >= 3 && oneitem[0] != null)
                {
                    var qtyTxt = GetObject(oneitem[1]);
                    var maxQty = oneitem[2];
                    
                    if (qtyTxt && qtyTxt.value != null && qtyTxt.value != "0")
                    {
                        if (maxQty < 0 || (maxQty > -1 && maxQty >= qtyTxt.value))
                        {
                            gotoStr = gotoStr + oneitem[0] + "," + qtyTxt.value + "|";
                        }
                        else
                        {
                            noQtyStr = noQtyStr + oneitem[0] + "|";
                            limitStock = true;
                            noneStockItem += oneitem[0] + ", ";
                        }
                        
                        hasQty = true;
                    }
                }
            }
        }
        
        if (!hasQty)
        {
            if (limitStock)
            {
                PopupMessage('Limited Stock', 'The item you tried to order has limited stock. ', null, null);
            }
            else
            {
                PopupMessage('Buy Quantity', 'The quantity you want to buy is zero. Please enter the quantity you want to buy and then click the Buy All or Buy button. <br><br>Thank you!', null, null);
            }
        }
        else if (gotoStr != "" )
        {
            if (isFromHistory && limitStock && noneStockItem.length > 2)
            {
                noneStockItem = noneStockItem.substr(0, noneStockItem.length - 2);
                PopupMessage('Limited Stock', 'The item(s) below have limited stock and will not be added in the cart: <br>' + noneStockItem + '<br>Do you want to add rest of items to shopping cart?', null, '/Product Pages/AddItem.aspx?ItemList=' + gotoStr + '&isFromHistory=' + isFromHistory );  
            }
            else
            {
                GoTo('/Product Pages/AddItem.aspx?ItemList=' + gotoStr + '&isFromHistory=' + isFromHistory );
            }
        }
        else
        {
            PopupMessage('Limited Stock', 'The item you tried to order has limited stock.', null, null);
        }
    }
    return false;
}

    // enter to click button
    function EnterToClick(e, clickButtonID)
    {
        if(e.which || e.keyCode)
        {            
            if ((e.which == 13) || (e.keyCode == 13)) 
            {            
                UpdateCart(clickButtonID);
                return false;
            }
        } 
        else 
        {
            return true;
        }
    } 
    
    function UpdateCart(clickButtonID)
    {   
        var updateQtyButton = GetObject(clickButtonID);
        if (updateQtyButton != null)
        {
            updateQtyButton.click();
        }
        return false;
    }
    
    // check page flash version
    function MM_CheckFlashVersion(reqVerStr, msg)
    {
	    with(navigator)
	    {
		    var isIE  = (appVersion.indexOf("MSIE") != -1 && userAgent.indexOf("Opera") == -1);
			var isWin = (appVersion.toLowerCase().indexOf("win") != -1);
			if (!isIE || !isWin)
			{  
				var flashVer = -1;
				if (plugins && plugins.length > 0)
				{
					var desc = plugins["Shockwave Flash"] ? plugins["Shockwave Flash"].description : "";
					desc = plugins["Shockwave Flash 2.0"] ? plugins["Shockwave Flash 2.0"].description : desc;
					if (desc == "") 
					{
					    flashVer = -1;
					}
					else
					{
						var descArr = desc.split(" ");
						var tempArrMajor = descArr[2].split(".");
						var verMajor = tempArrMajor[0];
						var tempArrMinor = (descArr[3] != "") ? descArr[3].split("r") : descArr[4].split("r");
						var verMinor = (tempArrMinor[1] > 0) ? tempArrMinor[1] : 0;
						flashVer = parseFloat(verMajor + "." + verMinor);
					}
				}
				// WebTV has Flash Player 4 or lower -- too low for video
				else if (userAgent.toLowerCase().indexOf("webtv") != -1) 
				{
				    flashVer = 4.0;
				}

				var verArr = reqVerStr.split(",");
				var reqVer = parseFloat(verArr[0] + "." + verArr[2]);
										
				if (flashVer < reqVer)
				{
					if (confirm(msg))
					{
					    window.location = "http://www.adobe.com/shockwave/download/download.cgi?P1_Prod_Version=ShockwaveFlash";
					}
				}
			}
	    } 
    }


    //HTTP: PRICE OVERRIDE FUNCTIONS
    function LogManager(clickButtonID) {
        var ManagerLoginButton = GetObject(clickButtonID);
        if (ManagerLoginButton != null) {
            ManagerLoginButton.click();
        }
        return false;
    }

    function DisableEnterKey(e, clickButtonID) {
        if (e.which || e.keyCode) {
            if ((e.which == 13) || (e.keyCode == 13)) {
                LogManager(clickButtonID);
                return false;
            }
            else
                return true;
        }
        else {
            return true;
        }
    }

    function UpdatePriceOverride(item, textbox, priceOverrideHidden, upperUpdateLink) {
        var discountAmt = 0;
        if (textbox != "") {
            discountAmt = GetObject('ctl00_CPH_' + textbox).value;
        }

        priceOverrideHidden.value = item + "|" + discountAmt + "|U";
        return ClickPriceOverride(upperUpdateLink);
    }


    function ClickPriceOverride(upperUpdateLink) 
    {
        var updatePriceButton = GetObject(upperUpdateLink);
        if (updatePriceButton != null) {
            updatePriceButton.click();
        }
        return false;
    }

    function ShowHideManagerPassword(massPriceOverrideClientID, priceOverrideInputID, upperUpdateLink, ManagerConfirm) 
    {
        var isConfirm;
        var massPrice = GetObject(massPriceOverrideClientID);
        var priceOverride = GetObject(priceOverrideInputID);
        priceOverride.value = "";        
        if (ManagerConfirm == "-") {
            PopupMessage('Price Override', 'Price Override not allowed. A customer is not logged in. <br><br>', null, null);
            return false;
        }        
        else if (ManagerConfirm != "") {
            isConfirm = true;
            var ManagerConfirm = GetObject(ManagerConfirm).value = "Manager|All";
            massPrice.value = "Yes";
            $find('managerPasswordPopup').show()
            //ClickPriceOverride(upperUpdateLink);
        }
        else {
            massPrice.value = "YesManagerApproved";
            ClickPriceOverride(upperUpdateLink);
        }
    }

    function ShowHideManagerPasswordForItem(massPriceOverrideClientID, priceOverrideInputID, ManagerConfirmValue, upperUpdateLink) {
        var isConfirm;
        var massPrice = GetObject(massPriceOverrideClientID);
        var priceOverrideInputID = GetObject(priceOverrideInputID);
        priceOverrideInputID.value = ManagerConfirmValue;
        massPrice.value = "";
        var ManagerValue = ManagerConfirmValue.split("|");

        
        if (ManagerValue[0] == "-") {
            PopupMessage('Price Override', 'Price Override not allowed. A customer is not logged in. <br><br>', null, null);
            return false;
        }
        else if (ManagerValue[0] == "Manager")
        {
           $find('managerPasswordPopup').show();
        }
        else
        {
            //var priceOverrideInputID = GetObject(priceOverrideInputID);
            priceOverrideInputID.value = ManagerConfirmValue;
            ClickPriceOverride(upperUpdateLink);
        
        }
    }

    function ComputePriceChange(textboxAmt, textboxDis, orgPrice, priceOverride, upperUpdateLinkButton, itemCode) {

        var priceOverrideTexboxAmt = GetObject('ctl00_CPH_' + textboxAmt);
        var priceOverrideTexboxDis = GetObject('ctl00_CPH_' + textboxDis);
        var priceOverrideHidden = GetObject(priceOverride);
        
        var type = "";
        var flag = true;

        if (priceOverrideTexboxAmt.value == 0) {
            type = "DIS"
            if (priceOverrideTexboxDis.value < 0) {
                PopupMessage('Price Override', 'Discount entered should not be less than 0 <br><br>', null, null);
                flag = false;
            }

            if (priceOverrideTexboxDis.value >= 100) {
                PopupMessage('Price Override', 'Discount entered should not be equal or or more than 100% <br><br>', null, null);
                flag = false;
            }
        }
        else {

            type = "AMT"
            if (parseFloat(priceOverrideTexboxAmt.value) > parseFloat(orgPrice)) {
                PopupMessage('Price Override', 'Unit price entered should not be equal or more than the original unit price <br><br>', null, null);
                flag = false;
            }

            if (priceOverrideTexboxAmt.value <= 0) {
                PopupMessage('Price Override', 'Unit price entered should not be less than or equal to 0 <br><br>', null, null);
                flag = false;
            }
        }

        if (flag == true) {
            if (type == "AMT") {
                if (priceOverrideTexboxAmt.value == orgPrice) {
                    priceOverrideTexboxDis.value = 0;
                }
                else if (priceOverrideTexboxAmt.value == 0) {
                    priceOverrideTexboxDis.value = 0;
                }
                else {
                    priceOverrideTexboxDis.value = round_decimals(((orgPrice - priceOverrideTexboxAmt.value) / orgPrice) * 100, 1)
                }
            }
            else {
                if (priceOverrideTexboxDis.value == 100) {
                    priceOverrideTexboxAmt.value = 0;
                }
                else if (priceOverrideTexboxDis.value == 0) {
                    priceOverrideTexboxAmt.value = orgPrice;
                }
                else {
                    priceOverrideTexboxAmt.value = round_decimals(((100 - priceOverrideTexboxDis.value) * orgPrice) / 100, 2)
                }
            }

            priceOverrideHidden.value = itemCode + priceOverrideTexboxAmt.value + "|U";
            UpdatePriceOverride(itemCode, textboxAmt, priceOverrideHidden, upperUpdateLinkButton)
        }
        else {
            priceOverrideHidden.value = itemCode + "|O";
        }
        return flag;
    }


    function round_decimals(original_number, decimals) {
        var result1 = original_number * Math.pow(10, decimals)
        var result2 = Math.round(result1)
        var result3 = result2 / Math.pow(10, decimals)
        return pad_with_zeros(result3, decimals)
    }

    function pad_with_zeros(rounded_value, decimal_places) {
        var value_string = rounded_value.toString()
        var decimal_location = value_string.indexOf(".")
        if (decimal_location == -1) {
            decimal_part_length = 0
            value_string += decimal_places > 0 ? "." : ""
        }
        else {
            decimal_part_length = value_string.length - decimal_location - 1
        }
        var pad_total = decimal_places - decimal_part_length
        if (pad_total > 0) {
            for (var counter = 1; counter <= pad_total; counter++)
                value_string += "0"
        }
        return value_string
    }
