﻿var timerSet;

//This jquery function are used for auto logoff and login 
function doTimeoutTest() {
    alert("I fired");
    // restart it
    setTimeout('doMyFunction()', 3000);
}
var autoLogoffTimer;
var logonUrl = rootpath + "Account/LogOn";
var logoffUrl = rootpath + "Account/LogOff";
var locPath = window.location.pathname;
var timeoutObject;
var timePeriod = 9000000; //30 minutes
var warnPeriod = 60000;  //60 seconds

//var timePeriod = 60000;
//var warnPeriod = 30000;

function promptForLogoff() {
    var autoLogoffDiv = document.getElementById('autoLogoffDiv');
    if (locPath == logonUrl) {
        //if already at the logon page then do not display inactivity timer
        resetTimeout();
    }
    else {
        autoLogoffDiv.style.display = 'block';
        autoLogoffTimer = setTimeout("definitelyLogoff()", warnPeriod);
    }
}
function autoLogoff() {
    var autoLogoffDiv = document.getElementById('autoLogoffDiv');
    autoLogoffDiv.style.display = 'block'; //shows message on page.
    autoLogoffTimer = setTimeout("definitelyLogoff()", timePeriod); //starts countdown to closure
}
function cancelLogoff() {
    var autoLogoffDiv = document.getElementById('autoLogoffDiv');
    clearTimeout(autoLogoffTimer); //stops auto-close timer.
    autoLogoffDiv.style.display = 'none'; //hides message.
}
function resetTimeout() {
    clearTimeout(timeoutObject); //stops timer
    timeoutObject = setTimeout("promptForLogoff()", timePeriod); //restarts timer from 0
}
function definitelyLogoff() {
    window.location.href = logoffUrl;
    //top.opener = self;
    //top.window.close();
}
//end auto login


// A script for selecting jqGrid row on focus of qty textbox
function selectRow(rowId) {
    if (rowId.indexOf("OSH") != -1) {
        rowId = rowId.replace("OSH", "");
        jQuery("#orderSheetList").setSelection(parseInt(rowId), false);
    }
    else if (rowId.indexOf("FAV") != -1) {
        rowId = rowId.replace("FAV", "");
        jQuery("#favoriteList").setSelection(parseInt(rowId), false);
    }
    else if (rowId.indexOf("INV") != -1) {
        rowId = rowId.replace("INV", "");
        jQuery("#invList").setSelection(parseInt(rowId), false);
    }
    else if (rowId.indexOf("ORD") != -1) {
        rowId = rowId.replace("ORD", "");
        jQuery("#cartList").setSelection(parseInt(rowId), false);
    }
}

// A script for handling Arror Keys [LEFT,UP,RIGHT,DOWN] in jqGrid
function isNumberKey(evt, qtyCtrl) {
    var charCode = (evt.which) ? evt.which : evt.keyCode;
    var ctrlId = jQuery(qtyCtrl).attr("id");
    var gridName = "";
    var temp = "";
    var newCtrl = "";
    var selectedRow = "";
    if (ctrlId.indexOf("OSH") != -1) {
        gridName = "orderSheetList";
    }
    else if (ctrlId.indexOf("FAV") != -1) {
        gridName = "favoriteList";
    }
    else if (ctrlId.indexOf("qtyRelDisp") != -1 && (charCode == 40 || charCode == 38)) {
        if (ctrlId.indexOf("qtyRelDispEven") != -1) {
            temp = parseInt(ctrlId.replace("qtyRelDispEvenINV", ""));
            newCtrl = "qtyRelDispOddINV";
        }
        else {
            temp = parseInt(ctrlId.replace("qtyRelDispOddINV", ""));
            newCtrl = "qtyRelDispEvenINV";
        }
        if (charCode == 38) { //UP ARROW
            temp = parseInt(temp) - 1;
            newCtrl = newCtrl + temp;
        }
        if (charCode == 40) { //DOWN ARROW
            temp = parseInt(temp) + 1;
            newCtrl = newCtrl + temp;
        }
        var findrel = jQuery("#" + newCtrl + "").length;
        if (findrel != "0") {
            jQuery("#" + newCtrl + "").focus();
        }
        return true;
    }
    else if (ctrlId.indexOf("qtyProdGrp") != -1 && (charCode == 40 || charCode == 38)) {
        if (ctrlId.indexOf("qtyProdGrpEven") != -1) {
            temp = parseInt(ctrlId.replace("qtyProdGrpEvenINV", ""));
            newCtrl = "qtyProdGrpOddINV";
        }
        else {
            temp = parseInt(ctrlId.replace("qtyProdGrpOddINV", ""));
            newCtrl = "qtyProdGrpEvenINV";
        }
        if (charCode == 38) { //UP ARROW
            temp = parseInt(temp) - 1;
            newCtrl = newCtrl + temp;
        }
        if (charCode == 40) { //DOWN ARROW
            temp = parseInt(temp) + 1;
            newCtrl = newCtrl + temp;
        }
        var findProd = jQuery("#" + newCtrl + "").length;
        if (findProd != "0") {
            jQuery("#" + newCtrl + "").focus();
        }
        return true;
    }
    else if (ctrlId.indexOf("INV") != -1) {
        gridName = "invList";
    }
    else if (ctrlId.indexOf("ORD") != -1) {
        gridName = "cartList";
    }
    if (charCode == 39) {
        incQty(ctrlId);
        return true;
    }
    if (charCode == 37) {
        decQty(ctrlId);
        return true;
    }
    if (charCode == 40 && gridName != "") { //down arrow
        selectedRow = jQuery("#" + gridName + "").getGridParam("selrow");
        var cnt = "0";
        if (gridName == "invList") {
            cnt = jQuery("#" + gridName + "").getGridParam("rowNum");
        }
        else {
            cnt = jQuery("#" + gridName + "").getGridParam("records");
        }
        if (cnt != selectedRow) {
            jQuery("#" + gridName + "").resetSelection(parseInt(selectedRow), false);
            jQuery("#" + gridName + "").setSelection(parseInt(selectedRow) + 1, false);
            if (ctrlId.indexOf("OSH") != -1) {
                temp = parseInt(ctrlId.replace("QtyOSH", "")) + 1;
                newCtrl = "QtyOSH" + temp;
            }
            else if (ctrlId.indexOf("FAV") != -1) {
                temp = parseInt(ctrlId.replace("QtyFAV", "")) + 1;
                newCtrl = "QtyFAV" + temp;
            }
            else if (ctrlId.indexOf("INV") != -1) {
                temp = parseInt(ctrlId.replace("QtyINV", "")) + 1;
                newCtrl = "QtyINV" + temp;
            }
            else if (ctrlId.indexOf("ORD") != -1) {
                temp = parseInt(ctrlId.replace("QtyORD", "")) + 1;
                newCtrl = "QtyORD" + temp;
            }
            jQuery("#" + newCtrl + "").focus();
        }
    }
    if (charCode == 38 && gridName != "") { //up arrow
        selectedRow = jQuery("#" + gridName + "").getGridParam("selrow");
        if (selectedRow != 1) {
            jQuery("#" + gridName + "").resetSelection(parseInt(selectedRow), false);
            jQuery("#" + gridName + "").setSelection(parseInt(selectedRow) - 1, false);
            if (ctrlId.indexOf("OSH") != -1) {
                temp = parseInt(ctrlId.replace("QtyOSH", "")) - 1;
                newCtrl = "QtyOSH" + temp;
            }
            else if (ctrlId.indexOf("FAV") != -1) {
                temp = parseInt(ctrlId.replace("QtyFAV", "")) - 1;
                newCtrl = "QtyFAV" + temp;
            }
            else if (ctrlId.indexOf("INV") != -1) {
                temp = parseInt(ctrlId.replace("QtyINV", "")) - 1;
                newCtrl = "QtyINV" + temp;
            }
            else if (ctrlId.indexOf("ORD") != -1) {
                temp = parseInt(ctrlId.replace("QtyORD", "")) - 1;
                newCtrl = "QtyORD" + temp;
            }
            jQuery("#" + newCtrl + "").focus();
        }
    }
}
function adjustFooter() {
    var gridBody = document.getElementById('gridBody');
    var bodyRows = gridBody.rows.length;
    if (bodyRows == "0") {
        $("#gridFooter").hide();
    }
    else {
        $("#gridFooter").show();
    }
}

// This jquery function is used for calling method in home controller for move product into cart.
//flag ismobile=false for full site
function MoveToOrder(isMobile) {
    isMobile = getMobileFlag(isMobile);
    jQuery('#unitList').attr('size', 2);
    var body = document.getElementById("gridBody");
    var rowCount = body.rows.length
    if (rowCount == 0) {
        alert("There are no items to Move to Cart");
        return;
    }
    var params = { 'transType': 'TCART' };
    jQuery.ajax({
        url: rootpath + 'Home/MoveToCart',
        type: 'POST',
        data: params,
        dataType: 'json',
        async: false,
        ContentType: 'application/json',
        success: function (data) {
            if (data.statusMsg == "Success") {
                if (isMobile) {
                    window.location = rootpath + "Home/MobileOrderEntry";
                }
                else {
                    jQuery.jGrowl("Now Moving items To Cart!"); //Do msg here because on errors it shows after the error message.
                    window.location = rootpath + "Home/OrderEntry";
                }
            }
            else {
                alert(data.statusMsg);
            }
        },
        Error: function () { alert("Error in Move to Order in Order Entry."); }
    });
}

//This jquery function is used for add item(product) in cart.
function AddToOrder(part, unit, price, qtyId, transType, lineComment, isMobile) {
    isMobile = getMobileFlag(isMobile);
    var retEntrySeq = "";
    var isAsync = true;
    var qty = document.getElementById(qtyId).value;
    if (transType == "TCART") {
        isAsync = false;
    }
    if (isNaN(parseInt(qty)) == false) {
        qty = parseInt(qty);
    }
    else {
        alert("Please enter a valid quantity");
        return false;
    }
    if (part == "")
        alert("Part is required");
    else if (unit == "")
        alert("Unit is required");
    else if (qty <= 0)
        alert("Quantity must be greater than zero.");
    else if (qty == "")
        alert("Quantity is required");
    else {
        var params = { 'part': part, 'unit': unit, 'price': price, 'Qty': qty, 'transType': transType, 'lineComment': lineComment };
        jQuery.ajax({
            url: rootpath + 'Home/AddToOrder',
            type: 'POST',
            data: params,
            dataType: "json",
            async: isAsync,
            ContentType: "application/json",
            success: function (data) {
                retEntrySeq = data.entrySeqVal;
                if (data.statusVal == "True") {
                    GetCartSummary(isMobile);
                    if (transType == 'CART') {
                        if (isMobile) {
                            alert("Item added to cart");
                        }
                        else {
                            $.jGrowl("Item added to cart");
                            var grid = jQuery("#invList");
                            grid.trigger("reloadGrid");
                            grid = jQuery("#cartList");
                            grid.trigger("reloadGrid");
                            grid = jQuery("#orderSheetList");
                            grid.trigger("reloadGrid");
                            grid = jQuery("#favoriteList");
                            grid.trigger("reloadGrid");
                            GetCartTotal(isMobile);
                        }
                    }
                }
                else
                    alert(data.errorMsgVal);
            },
            Error: function () { alert("Error calling Add to Order)"); }
        });
    }
    return retEntrySeq;
}

//update cart order qty on cart page transType--CART
function ReCalculateCart(part, unit, price, qtyId, isMobile) {
    isMobile = getMobileFlag(isMobile);
    var qty = document.getElementById(qtyId).value;
    if (part == "")
        alert("Part is required");
    else if (unit == "")
        alert("Unit is required");
    else if (qty <= 0)
        alert("Quantity must be greater than zero.");
    else if (qty == "")
        alert("Quantity is required");
    else {
        var params = { 'part': part, 'unit': unit, 'price': price, 'Qty': qty, 'transType': 'CART' };
        jQuery.ajax({
            url: rootpath + 'Home/AddToOrder',
            type: 'POST',
            data: params,
            dataType: "json",
            ContentType: "application/json",
            success: function (data) {
                if (data.statusVal == "True") {
                    if (!isMobile) {
                        var grid = jQuery("#cartList");
                        grid.trigger("reloadGrid");
                        $.jGrowl("Cart updated");
                    }
                    else {
                        alert("Cart updated");
                        location.href = document.location;
                    }
                    GetCartTotal(isMobile);
                }
                else {
                    alert(data.errorMsgVal);
                }
            },
            Error: function () { alert("Error Calling Add to Cart."); }
        });
        return false;
    }
}

//update cart order qty on order entry page transType--TCART
function UpdateOrderEntryQty(entrySeq, part, unit, price, qtyId, lineComment, isMobile) {
    isMobile = getMobileFlag(isMobile);
    var qty = document.getElementById(qtyId).value;
    if (part == "")
        alert("Part is required");
    else if (unit == "")
        alert("Unit is required");
    else if (qty <= 0)
        alert("Quantity must be greater than zero.");
    else if (qty == "")
        alert("Quantity is required");
    else {
        var params = { 'entrySeq': entrySeq, 'part': part, 'unit': unit, 'price': price, 'Qty': qty, 'lineComments': lineComment, 'transType': 'TCART' };
        jQuery.ajax({
            url: rootpath + 'Home/UpdateOrder',
            type: 'POST',
            data: params,
            dataType: "json",
            ContentType: "application/json",
            success: function (data) {
                if (data.statusVal == "True") {
                    if (!isMobile) {
                        $.jGrowl("Order Entry updated");
                    }
                    else {
                        alert("Order Entry updated");
                        location.href = document.location;
                    }
                }
                else {
                    alert(data.errorMsgVal);
                }
            },
            Error: function () { alert("Error Calling Update Order Qty."); }
        });
        return false;
    }
}

//This function is used for show comment box on page. 
function ShowCommentBox(divId, txtboxToSetFocus, linecommentId, isMobile) {
    isMobile = getMobileFlag(isMobile);
    if (!isMobile && linecommentId != "null")
        document.getElementById(linecommentId).style.display = "none";
    document.getElementById(divId).style.display = "block";
    document.getElementById(txtboxToSetFocus).focus();
    return false;
}

//function is used for save comment for particular paroduct
function SaveLineComments(entrySeqValue, commentTextID, transType, isMobile) {
    //transType = CART or TCART
    isMobile = getMobileFlag(isMobile);
    var lineComments;
    if (commentTextID == '')
        lineComments = '';
    else
        lineComments = document.getElementById(commentTextID).value;
    var params = "";
    if (commentTextID == '') {
        if (confirm("Do you want to delete line comment?")) {
            params = { 'entrySeq': parseInt(entrySeqValue), 'lineComments': lineComments, 'flag': 'delete', 'transType': transType };
            jQuery.ajax({
                url: rootpath + 'Home/SaveLineComments',
                type: 'POST',
                data: params,
                dataType: "text",
                ContentType: "application/text",
                complete: function (data) {
                    if (data.responseText == "Removed") {
                        if (isMobile) {
                            location.reload();
                        }
                        else {
                            var grid = jQuery("#cartList");
                            grid.trigger("reloadGrid");
                            $.jGrowl("Line comments removed!");
                            location.href = document.location;
                        }
                    }
                    else {
                        alert(data.responseText);
                    }
                },
                Error: function () { alert("Error Calling Save line comments."); }
            });
        }
    } else {
        params = { 'entrySeq': parseInt(entrySeqValue), 'lineComments': lineComments, 'flag': 'save', 'transType': transType };
        jQuery.ajax({
            url: rootpath + 'Home/SaveLineComments',
            type: 'POST',
            data: params,
            dataType: "text",
            ContentType: "application/text",
            complete: function (data) {
                if (data.responseText == "Saved") {
                    if (isMobile) {
                        location.reload();
                    }
                    else {
                        var grid = jQuery("#cartList");
                        grid.trigger("reloadGrid");
                        $.jGrowl("Line comments saved!");
                        location.href = document.location;
                    }
                }
                else {
                    alert(data.responseText);
                }
            },
            Error: function () { alert("Error Calling Save line comments."); }
        });
    }
}

//function calling from cancel button
function CancelComment(divId, textId, linecommentId, isMobile) {
    isMobile = getMobileFlag(isMobile);
    if (!isMobile)
        document.getElementById(linecommentId).style.display = "block";
    document.getElementById(textId).innerHTML = document.getElementById(textId).title;
    document.getElementById(divId).style.display = "none";
    return false;
}

//function is used fro calculate total cart value
function GetCartTotal(isMobile) {
    isMobile = getMobileFlag(isMobile);
    jQuery.ajax({
        type: 'Post',
        dataType: 'string',
        data: { 'renderMobile': isMobile },
        url: rootpath + 'Home/GetCartTotal',
        success: function (data) {
            if (data.length > 0)
                jQuery("#cartTotal").html(data);
            else
                jQuery("#cartTotal").html("<b>Your cart is empty</b>");
        },
        Error: function () {
            jQuery("#cartTotal").html("<b>Error Calling GetCartTotal.</b>");
        }
    });
}

//function is used for cart summary
function GetCartSummary(isMobile) {
    isMobile = getMobileFlag(isMobile);
    jQuery.ajax({
        type: 'Post',
        dataType: 'string',
        data: { 'renderMobile': isMobile },
        url: rootpath + 'JSON/GetCartSummary',
        success: function (data) {
            if (data.length > 0) {
                jQuery("#CartSummaryProdDet").html(data);
                jQuery("#CartSummary").html(data);
            }
        },
        Error: function () {
            jQuery("#CartSummaryProdDet").html("<b>Error Calling Cart Summary.</b>");
            jQuery("#CartSummary").html("<b>Error Calling Cart Summary.</b>");
        }
    });
}

//delete order for orderentry page
function DeleteFromOrder(idKey, transType, isMobile) {
    isMobile = getMobileFlag(isMobile);
    var params = { 'entrySeq': idKey, 'transType': transType };
    jQuery.ajax({
        type: "POST",
        url: rootpath + 'Home/DeleteFromOrder',
        data: params,
        dataType: "string",
        success: function (data) {
            if (data == "True") {
                if (transType == "CART") {
                    if (isMobile) {
                        location.href = document.location;
                    }
                    else {
                        var grid = jQuery("#cartList");
                        grid.trigger("reloadGrid");
                    }
                    GetCartTotal(isMobile);
                }
                else if (transType == "TCART") {
                    window.location = rootpath + "Home/OrderEntry";
                }
            }
            else {
                alert(data);
            }
        },
        Error: function () {
            alert("Error calling Delete From Order");
        }
    });
}
//delete order for cart page
function DeleteOrder(transType, isMobile) {
    isMobile = getMobileFlag(isMobile);
    var msg = "Invalid trans type";
    if (transType == "CART") {
        msg = "Do you want to empty the Cart?";
    }
    else if (transType == "TCART") {
        msg = "Do you want to clear all Order Entry items?";
    }
    if (confirm(msg)) {
        var params = { 'transType': transType };
        jQuery.ajax({
            type: 'Post',
            data: params,
            dataType: 'text',
            ContentType: "application/text",
            url: rootpath + 'Home/DeleteOrder',
            success: function (data) {
                if (data == "Success") {
                }
                else {
                    alert(data);
                }
                if (transType == "CART") {
                    if (isMobile) {
                        location.href = document.location;
                    }
                    else {
                        var grid = jQuery("#cartList");
                        grid.trigger("reloadGrid");
                    }
                }
                else {
                    if (isMobile) {
                        window.location = rootpath + "Home/MobileOrderEntry";
                    }
                    else {
                        window.location = rootpath + "Home/OrderEntry";
                    }
                }
            },
            Error: function () { alert("Error Calling Delete Order."); }
        });
    }
}

//This function is used for add to cart +/- button
function incQty(qtyId) {
    var intVal = 0;
    var val = jQuery("#" + qtyId + "").val();
    if (isNaN(parseInt(val)) == false) {
        intVal = parseInt(val);
    }
    if (intVal == 0) {
        jQuery("#" + qtyId + "").val("1");
    }
    else {
        jQuery("#" + qtyId + "").val(intVal + 1);
    }
}

function decQty(qtyId) {
    var intVal = 0;
    var val = jQuery("#" + qtyId + "").val();
    if (isNaN(parseInt(val)) == false) {
        intVal = parseInt(val);
    }
    if (intVal == 0) {
        jQuery("#" + qtyId + "").val("0");
    }
    else {
        jQuery("#" + qtyId + "").val(intVal - 1);
    }
}

function AddToFavorite(part, unit, isMobile) {
    isMobile = getMobileFlag(isMobile);
    var params = { 'part': part, 'unit': unit };
    jQuery.ajax
    ({
        url: rootpath + 'Home/AddToFavorite',
        type: 'POST',
        data: params,
        dataType: "text",
        ContentType: "application/text",
        success: function (data) {
            if (data == "True") {
                if (isMobile) {
                    alert("Item added to Favorites.");
                }
                else {
                    var grid = jQuery("#favoriteList");
                    grid.trigger("reloadGrid");
                    $.jGrowl("Item added to Favorites.");
                }
            }
            else {
                alert(data);
            }
        },
        Error: function () { alert("Error calling Add to Favorites"); }
    });
}

function GetLastUpdateMsg() {
    jQuery.ajax({
        type: "POST",
        url: rootpath + 'Customer/GetLastUpdateMsg',
        dataType: "string",
        success: function (data) {
            jQuery("#lastUpdateMsg").html(data);
        },
        Error: function () {
            alert("Error calling GetLastUpdateMsg");
        }
    });
}
function GetHoldandCreditMsg() {
    jQuery.ajax({
        type: "POST",
        url: rootpath + 'Customer/GetHoldandCreditMsg',
        dataType: "string",
        success: function (data) {
            jQuery("#holdAndCreditMsg").html(data);
        },
        Error: function () {
            alert("Error calling GetHoldandCreditMsg");
        }
    });
}

function SendOrderEmail(OrderNo, isMobile) {
    isMobile = getMobileFlag(isMobile);
    var params = { 'orderNo': OrderNo };
    jQuery.ajax({
        url: rootpath + 'Home/OrderEmail',
        type: 'POST',
        data: params,
        dataType: 'text',
        ContentType: 'application/text',
        complete: function (data) {
            if (data.responseText == "Success") {
                if (isMobile) {
                    alert("Email sent successfully!");
                }
                else {
                    $.jGrowl("Email sent successfully!");
                }
            }
            else {
                alert(data.responseText);
            }
        },
        Error: function () { alert("Error Sending Order Email."); }
    });
}

//Utilities.
function CurrencyFormat(amount) {
    //Format amount into US currency format.
    amount = new String(amount);
    var arr = amount.split('.', 2)
    var dec = "";
    if (arr.length > 1)
        dec = arr[1];
    var i = parseInt(arr[0]);
    if (isNaN(i)) {
        return amount; //Invalid number return original value.
    }
    var minus = '';
    if (i < 0) {
        minus = '-';
    }
    i = Math.abs(i);
    var number = new String(i);
    arr = [];
    while (number.length > 3) {
        var newNumber = number.substr(number.length - 3);
        arr.unshift(newNumber);
        number = number.substr(0, number.length - 3);
    }
    if (number.length > 0) {
        arr.unshift(number);
    }
    number = arr.join(','); //Add commas.
    if (dec.length < 1) {
        amount = number + '.00'; //No decimals, add 00.
    }
    else if (dec.length == 1) {
        amount = number + '.' + dec + '0'; //Single digit decimal add trailing zero.
    }
    else {
        amount = number + '.' + dec; //Add decimal.
    }
    amount = "$" + minus + amount;
    return amount;
}

function pad(number, length) {
    //pad number with leading zero's.
    var str = '' + number;
    while (str.length < length) {
        str = '0' + str;
    }
    return str;
}
function padright(str, length) {
    //pad right side of string with trailing spaces.
    while (str.length < length) {
        str = str + "&nbsp;";
    }
    return str;
}

function doBlink() {
    var isVisible = $(".BLINK").is(':visible');
    if (isVisible == true) {
        jQuery(".BLINK").hide();
    }
    else {
        jQuery(".BLINK").show();
    }
}

function startBlink() {
    timerSet = setInterval("doBlink()", 1000);
}
//This function is used for open product details pop-up
function openLangBox(openBox, isMobile) {
    isMobile = getMobileFlag(isMobile);
    if (linkWindowName != "") {
        jQuery("#" + linkWindowName + "").hide();
    }
    linkWindowName = openBox;
    var left = "";
    var width = "";
    var position = "";
    var zindex = "";
    if (isMobile) {
        left = "0%";
        width = "99%";
        position = "relative";
        zindex = "0";
    }
    else {
        left = "36%";
        width = "425px";
        position = "fixed";
        zindex = "10000";
    }
    jQuery("#" + openBox + "").css({
        'left': left,
        'position': position,
        'top': '45%',
        'z-index': zindex,
        'background-color': 'white',
        'width': width
    });
    jQuery("#" + openBox + "").show();
}
//This function is used for open documents pages on product details page like MSDS TDS etc..
function openDocument(linkToOpen, closeBox, defaCheckBox, linkClicked, isMobile) {
    isMobile = getMobileFlag(isMobile);
    jQuery("#" + closeBox + "").hide();
    var setDefault = jQuery("#" + defaCheckBox + "").attr('checked');
    var languageToSet = linkClicked;
    if (setDefault == true) {
        jQuery.ajax({
            type: "POST",
            url: rootpath + 'Home/setAsDefaultLanguage',
            data: { lang: languageToSet },
            dataType: "json",
            ContentType: "application/json",
            success: function (data) {
                if (data.status == "Fail") {
                    alert(data.errorMsg);
                }
                else {
                    if (isMobile) {
                        alert("No favoriteList and orderSheetList jqgrid To reload");
                    }
                    else {
                        var grid = jQuery("#favoriteList");
                        grid.trigger("reloadGrid");
                        grid = jQuery("#orderSheetList");
                        grid.trigger("reloadGrid");
                    }
                }
            },
            Error: function () {
                alert("Error calling setAsDefaultLanguage");
            }
        });
    }
    newwindow = window.open(linkToOpen, "", "toolbar=no,location=no,directories=no,status=yes,menubar=yes," + "scrollbars=yes,copyhistory=no,resizable=yes,width=800,height=650");
}
function callSelectInvSubmit(event) {
    var charCode = (event.which) ? event.which : event.keyCode;
    if (charCode == 13) {
        $('#selectInvSubmit').click();
    }
}

function emailProduct(part, unit) {
    var url = rootpath + 'Home/EmailPage?part=' + part + '&unit=' + unit;
    window.open(url, 'EmailPage', 'location=1,menubar=1,resizable=1,scrollbars=1,fullscreen=yes');
    return false;
}

function createCookie(name, value, days) {
    var expires = "";
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        expires = "; expires=" + date.toGMTString();
    }
    document.cookie = name + "=" + value + expires + "; path=/";
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }
    return null;
}

function eraseCookie(name) {
    createCookie(name, "", -1);
}

function getExpiryDate() {
    var theDate = new Date();
    var oneYearLater = new Date(theDate.getTime() + 31536000000);
    var expiryDate = oneYearLater.toGMTString();
    return expiryDate;
}

function getMobileFlag(mobileFlag) {
    var flag = jQuery.trim(mobileFlag.toString());
    if (flag == "" || flag.toUpperCase() == "FALSE")
        flag = false;
    else
        flag = true;
    return flag;
}

function IsAppleDevice() {
    var appleDev = false;
    //alert(navigator.userAgent.toString());
    if (navigator.userAgent.match(/iPad/i) || navigator.userAgent.match(/iPhone/i)) {
        appleDev = true;
    }
    return appleDev;
}
function ClearTextBoxIfApple(textId) {
    if (IsAppleDevice()) {
        jQuery('#' + textId).val('');
    }
}
String.prototype.nl2br = function () {
    var br;
    if (typeof arguments[0] != 'undefined') {
        br = arguments[0];
    }
    else {
        br = '<br />';
    }
    return this.replace(/\r?\n|\r/g, br);
}

String.prototype.br2nl = function () {
    var nl;
    if (typeof arguments[0] != 'undefined') {
        nl = arguments[0];
    }
    else {
        nl = '\r\n';
    }
    return this.replace(/\<BR\>/gi, nl);
}

function showPane(divIDToShow, isMobile) {
    isMobile = getMobileFlag(isMobile);
    if (isMobile) {
        $(".smpane").hide();
    } else {
        $(".pane").hide();
    }

    document.getElementById(divIDToShow).style.display = 'block';
    if (divIDToShow == "RelatedProducts") {
        $("#rel").addClass("current");
        $("#pgps").removeClass("current");
        $("#alt").removeClass("current");
        $("#addimages").removeClass("current");
    }
    if (divIDToShow == "ProductGroup") {
        $("#pgps").addClass("current");
        $("#rel").removeClass("current");
        $("#alt").removeClass("current");
        $("#addimages").removeClass("current");
    }
    if (divIDToShow == "AlternateProducts") {
        $("#alt").addClass("current");
        $("#rel").removeClass("current");
        $("#pgps").removeClass("current");
        $("#addimages").removeClass("current");
    }
    if (divIDToShow == "AdditionalImages") {
        $("#addimages").addClass("current");
        $("#rel").removeClass("current");
        $("#pgps").removeClass("current");
        $("#alt").removeClass("current");
    }
}
function openAdditionalImagePage(part, unit, defaultLink, isMobile) {
    createCookie('defaLink', defaultLink, 1);
    isMobile = getMobileFlag(isMobile);
    if (isMobile == false) {
        var url = rootpath + 'Home/AdditionalImages?part=' + part + '&unit=' + unit;
        window.open(url, 'AdditionalImages', 'location=1,menubar=1,resizable=1,scrollbars=1,fullscreen=yes');
    }
    else {
        var url = rootpath + 'Home/MobileAdditionalImages?part=' + part + '&unit=' + unit;
        window.open(url, 'AdditionalImages', 'location=1,menubar=1,resizable=1,scrollbars=1,fullscreen=yes');
    }
}
//This function is used for get secret question (forgot password)
function showSecretQuestion() {
    var userName = jQuery("#UserName").val();
    if (userName == "") {
        alert("Please enter Username");
        jQuery("#UserName").focus();
    }
    else {
        jQuery.ajax({
            url: rootpath + 'Account/GetSecurityQuestion',
            type: 'POST',
            data: { 'Username': userName },
            dataType: "json",
            ContentType: "application/json",
            success: function (data) {
                if (data.status == "Success") {
                    jQuery("#securityUserName").html(userName);
                    jQuery("#securityQuestion").html(data.securityQuestion);
                    jQuery("#secretQA").css({ 'display': 'block' });
                    jQuery("#securityAnswer").focus();
                    document.getElementById("sendEmailButton").scrollIntoView(false);
                }
                else {
                    alert(data.status);
                }
            },
            Error: function () {
                alert("Error in getting Security Question");
            }
        });
    }
}

function sendPasswordByEmail(isMobile) {
    var userName = jQuery("#securityUserName").html();
    var securityAnswer = jQuery("#securityAnswer").val();
    if (securityAnswer == "") {
        alert("Answer cannot be left blank");
        jQuery("#securityAnswer").focus();
        return false;
    }
    //$.jGrowl("Now emailing password, please wait...");
    if (isMobile) {
        $("#plzWait").show();
    } else {
        $.jGrowl("Now emailing password, please wait...");
    }

    jQuery.ajax({
        url: rootpath + 'Account/EmailPassword',
        type: 'POST',
        data: { 'userName': userName, 'securityAnswer': securityAnswer },
        dataType: "json",
        ContentType: "application/json",
        async: true,
        success: function (data) {
            if (isMobile) {
                $("#plzWait").hide();
            }
            if (data.status == "Success") {
                alert("Password has been emailed");
                jQuery("#secretQA").css({ 'display': 'none' });
            }
            else if (data.status == "Fail") {
                alert(data.errorMessage);
            }
        },
        Error: function () {
            if (isMobile) {
                $("#plzWait").hide();

            } alert(data);
        }
    });
}

function VerifyNewCustFields() {
    if (jQuery("#fname").val() == "") {
        jQuery("#fname").focus();
        alert("First name is required");
        return false;
    }

    if (jQuery("#lname").val() == "") {
        jQuery("#lname").focus();
        alert("Last name is required");
        return false;
    }

    if (jQuery("#company").val() == "") {
        jQuery("#company").focus();
        alert("Company name is required");
        return false;
    }

    if (jQuery("#address").val() == "") {
        jQuery("#address").focus();
        alert("Address is required");
        return false;
    }

    if (jQuery("#city").val() == "") {
        jQuery("#city").focus();
        alert("City name is required");
        return false;
    }

    if (jQuery("#state").val() == "--") {
        jQuery("#state").focus();
        alert("State name is required");
        return false;
    }

    if (jQuery("#zipcode").val() == "") {
        jQuery("#zipcode").focus();
        alert("Zipcode is required");
        return false;
    }

    if (jQuery("#emailAddr").val() == "") {
        jQuery("#emailAddr").focus();
        alert("Email address is required");
        return false;
    }

    if (jQuery("#phone").val() == "") {
        jQuery("#phone").focus();
        alert("Phone number is required");
        return false;
    }
    if (jQuery("#txtcaptcha").val() == "") {
        alert("Captcha Code is required");
        return false;
    } else {
        var captCode = jQuery("#myc").html().trim();
        var val = jQuery("#txtcaptcha").val();
        if (val != captCode) {
            alert("Captcha Code does not match! Try again.");
            return false;
        }
    }
    return true;
}
function GetCharCode(event) {
    var charCode = "";
    if (event == null) {
        return charCode;
    };
    if (event.which == null) {
        charCode = event.keyCode;
    }
    else {
        charCode = event.which;
    }
    return charCode;
}

//OrderSummary
var createNewPayloadId = false;  //srs. 11/17/2011.
var isPlaced = false;

function clearComment() {
    $("#orderComments").val("");
}

function ReadOrderCreateEmailConf(isMobile) {
    isMobile = getMobileFlag(isMobile);
    if (isMobile == false)
        $.jGrowl("Now creating order confirmation, please wait");

    $.ajax({
        url: rootpath + 'Home/ReadOrderCreateEmailConf',
        type: 'POST',
        data: '',
        dataType: "text",
        ContentType: "application/text",
        complete: function (data) {
            if (data.responseText == "Success") {
            }
            else {
                alert("Error submitting order: \n" + data.responseText);
            }
            //Go to Order Confirmation page no matter if this call is successful or not.
            window.location = rootpath + 'Home/OrderConfirmation';
        },
        Error: function () {
            alert("Error in SubmitOrder call.");
            $("#OrderSummaryWait").hide();
            $("#OrderSummaryContent").show();
        }
    });
}
function SaveOrder(poRefId, placedById, placedByPhoneId, orderCommentsId, redirectToCart, ValidateAll, isMobile) {
    isMobile = getMobileFlag(isMobile);
    if (redirectToCart == "OrderConf") {
        if (isPlaced == false) {
            isPlaced = true;
        }
        else {
            return false;
        }
        $("#OrderSummaryWait").show();
        $("#OrderSummaryContent").hide();
    }

    var value = { 'currentUserOrder_PO_REF': $("#" + poRefId + "").val(),
        'currentUserOrder_PLACED_BY': $("#" + placedById + "").val(),
        'currentUserOrder_PLACED_BY_PHONE_NO': $("#" + placedByPhoneId + "").val(),
        'orderComments': $("#" + orderCommentsId + "").val(), 'ValidateAll': ValidateAll
    };

    $.ajax({
        url: rootpath + 'Home/SaveOrder',
        type: 'POST',
        data: value,
        dataType: "text",
        async: false,
        ContentType: "application/text",
        complete: function (data) {
            if (data.responseText == "Saved") {
                if (redirectToCart == "Cart") {
                    if (isMobile == true) {
                        window.location = rootpath + 'Home/MobileCart';
                        //  window.location = '<%= Url.Action("MobileCart", "Home") %>';
                    }
                    else if (isMobile == false) {
                        window.location = rootpath + 'Home/Cart';
                        //  window.location = '<%= Url.Action("Cart", "Home") %>';
                    }
                }
                else if (redirectToCart == "OrderConf")
                    SubmitOrder(isMobile);
            }
            else {
                isPlaced = false;
                $("#OrderSummaryWait").hide();
                $("#OrderSummaryContent").show();
                alert("Error saving order: \n" + data.responseText);
            }
        },
        Error: function (data) {
            isPlaced = false;
            //srs. 11/17/2011.
            alert("Error in SaveOrder call." + data.responseText);
            $("#OrderSummaryWait").hide();
            $("#OrderSummaryContent").show();
        }
    });
}
function SubmitOrder(isMobile) {
    $.ajax({
        url: rootpath + 'Home/SubmitOrder',
        type: 'POST',
        data: { createNewPayloadId: createNewPayloadId },
        dataType: "text",
        async: true,
        ContentType: "application/text",
        complete: function (data) {
            if (data.responseText == "200") {
                ReadOrderCreateEmailConf(isMobile);
            }
            else if (data.responseText == "406") {
                isPlaced = false;
                //srs. 11/17/2011.
                createNewPayloadId = true;
                $("#OrderSummaryWait").hide();
                $("#OrderSummaryContent").show();
                alert("There was an error due to duplicate payload id. please submit the Order again.");
            }
            else {
                isPlaced = false;
                //srs. 11/17/2011.
                $("#OrderSummaryWait").hide();
                $("#OrderSummaryContent").show();
                alert("Error submitting order: \n" + data.responseText);
            }
        },
        Error: function () {
            alert("Error in SubmitOrder call.");
            $("#OrderSummaryWait").hide();
            $("#OrderSummaryContent").show();
        }
    });
}

function MobileNavigation() {
    window.location = rootpath + 'Home/MobileNavigation';
}
