﻿

var _updateProgressDiv;
var _backgroundDiv;
var _panelToOverlay;
var _parentpanel;
var _HandlersAdded = false;
var _updating = false;
var divScrollHeight;
var divScrollOffset = 12;
var iCartTrys = 0
var CartLoaded = false;
var cartLoadRequest = false;
var cancelCart = false;
var cancelCartLoading = false;
var imgsLoaded = false;

function pageLoad() {
    ajaxReady = true;
    if (_HandlersAdded == false) {
        Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(MainBeginRequest);
        Sys.WebForms.PageRequestManager.getInstance().add_endRequest(MainEndRequest);
        Sys.WebForms.PageRequestManager.getInstance().add_initializeRequest(MainInitializeRequest);
        Sys.Application.add_load(ModalHooks);
        ModalHooks();
        _HandlersAdded = true;
    }



}


//preload images 
img1 = new Image();
img2 = new Image();
img3 = new Image();
img4 = new Image();
img5 = new Image();
img6 = new Image();
img7 = new Image();
img8 = new Image();
img9 = new Image();
img1.src = "/images/Buttons/b1MiddleOver.gif";
img2.src = "/images/Buttons/b1RightOver.gif";
img3.src = "/images/Buttons/b1LeftOver.gif";
img4.src = "/images/Buttons/b1Middle.gif";
img5.src = "/images/Buttons/b1Right.gif";
img6.src = "/images/Buttons/b1Left.gif";
img7.src = "/images/header/tabBlue.gif";
img8.src = "/images/header/tabBlueOver.gif";
img9.onLoad = imgsComplete();
img9.src = "/images/header/tabYellow.gif";

function imgsComplete() {
    imgsLoaded = true;
}



function MainInitializeRequest(sender, args) {

}


function ModalHooks() {


    var bgElement = $get('modalCart_backgroundElement');
    if (bgElement != null) {
        bgElement.onclick = function() { $find('modalCart').hide(); };
    }


    if ($find('modalCartLoading') != null) {
        $find('modalCartLoading').add_shown(function() { CartLoadingShown(); });
    }

    if ($find('modalCart') != null) {
        $find('modalCart').add_showing(function() {  });
        $find('modalCart').add_hidden(function() { CartHidden(); });
        $find('modalCart').add_hiding(function() { });
        $find('modalCart').add_shown(function() { CartShown(); });
    }

}


function HideModal() {
    $find('modalCart').hide();
}
function showCart() {
    //$find('modalCart').show()
    try {
        $find('modalCartLoading').show(); //while loading cart
    } catch (ex) { }
    $get(clientBase + 'ShoppingCart_cmdInvokeCart').click();
}



function MainBeginRequest(sender, args) {

    if ($get(clientBase + 'divCart') != null && $get(clientBase + 'divCart').style.display == "none" && args._postBackElement.id == 'ctl00_ctl00_ctl00_cphSite_ShoppingCart_cmdInvokeCart') {
        return;
    }
    else {
        ajaxOverlay(sender, args)
    }

}

function MainEndRequest(sender, args) {
    if (_updating == true) {
        ajaxOverlayQuit(sender, args)
    }

    ScrollDivRendor();

    Tracking(sender, args);

    _updating = false;

}


function Tracking(sender, args) {

    if (sender._postBackSettings.sourceElement != null) {
        var sourceID = sender._postBackSettings.sourceElement.id
        if (sourceID.length > 0) {
            var sendObj = $get(sender._postBackSettings.sourceElement.id);

            if (sendObj != null && sendObj.attributes.trackURL != null) {
                if (typeof (_gat) != "undefined") {
                    var pageTracker = _gat._getTracker("UA-785006-1");
                    pageTracker._initData();
                    pageTracker._trackPageview(window.location.pathname + '?track=' + sendObj.attributes.trackURL.nodeValue);
                }
            }
        }
    }
}



function ajaxOverlayQuit(sender, args) {

    if (_panelToOverlay != null) {
        _backgroundDiv.style.display = 'none';
    }

    if (_updateProgressDiv != null) {
        _updateProgressDiv.style.display = 'none';
    }

}

function ScrollDivRendor() {
    var divScroll;
    divScroll = $get('divScroll');
    if (divScroll != null) {
        try {
            $removeHandler(window, 'resize', MakeScrollDiv);
        }
        catch (ex) {
        }

        var elementBounds = Sys.UI.DomElement.getBounds(divScroll);

        divScrollHeight = elementBounds.height;



        if (divScrollHeight <= 0) {
            divScrollHeight = (divScroll.clientHeight);
        }

        if (divScrollHeight <= 0) {
            divScrollHeight = (divScroll.offsetHeight);
        }

        if (divScrollOffset > 0 && divScrollHeight > divScrollOffset) {
            divScrollHeight = divScrollHeight - divScrollOffset;
        }

        $addHandler(window, 'resize', MakeScrollDiv);
        MakeScrollDiv();
    }
}
var restarting = false;
function ValidCartPage() {
    var sPath = window.location.pathname.toLowerCase();

    if (sPath.indexOf('ordercc.aspx') >= 0 || sPath.indexOf('orderconfirm.aspx') >= 0) {
        if (restarting == false) {//protect from asking twice
            if (confirm("Your shopping cart cannot be modified during the checkout process. Would you like to restart your order?")) {
                restarting = true;
                location.href = '/default.aspx?CartID=Session';
            }
            else {
                HideModal();
            }
        }

    }


}
function ajaxOverlay(sender, args) {
    _updating = true;





    var panelID = sender._postBackSettings.panelID.split('|')[0]; panelID = panelID.replace(/\$/gi, '_');
    var updatepanel = $get(panelID);


    _panelToOverlay = getParentWrap($get(args._postBackElement.id));
    _parentpanel = getabsolutewrap($get(args._postBackElement.id));



    if (_parentpanel == null) {

        if ((Sys.Browser.agent === Sys.Browser.InternetExplorer) && (Sys.Browser.version < 7)) {
            _parentpanel = $get('content');
        } else { _parentpanel = $get('main'); }
    }


    if (_panelToOverlay != null && _panelToOverlay.style.display != 'none') {



        //_updateProgressDiv = $get('updateProgress');
        _updateProgressDiv = getEmbeddedChild(updatepanel, 'updateProgress');

        if (_updateProgressDiv == null) {
            _updateProgressDiv = document.createElement('divProgress');
            _updateProgressDiv.style.display = 'none';
            _updateProgressDiv.style.position = 'absolute';
            _updateProgressDiv.style.zIndex = 10009;
            _updateProgressDiv.style.width = "80px";
            _updateProgressDiv.style.height = "40px";
            _updateProgressDiv.className = 'updateProgress';
            _updateProgressDiv.style.visibility = 'visible';
            _updateProgressDiv.id = 'divProgress';

            //  add the element to the DOM
            _panelToOverlay.parentNode.appendChild(_updateProgressDiv);
        }

    }


    //&& sender._postBackSettings.panelID.indexOf('frmQuote') > 0) {
    if (_panelToOverlay != null) {
        if (document.getElementById("divDisabler") == null) {
            _backgroundDiv = document.createElement('div');
            _backgroundDiv.style.display = 'none';

            _backgroundDiv.style.position = 'absolute';
            _backgroundDiv.style.zIndex = 10000;
            _backgroundDiv.className = 'AjaxOverlay';
            _backgroundDiv.id = 'divDisabler';

            //  add the element to the DOM
            _panelToOverlay.parentNode.appendChild(_backgroundDiv);
        }

        var panelBounds = Sys.UI.DomElement.getBounds(_panelToOverlay);
        var mainBounds = Sys.UI.DomElement.getBounds(_parentpanel);

        //        if (_parentpanel != null && _parentpanel.id == 'main') {
        //            mainBounds.x = 0;
        //            mainBounds.y = 0;
        //        }

        _backgroundDiv.style.width = panelBounds.width + 'px';
        _backgroundDiv.style.height = panelBounds.height + 'px';


        Sys.UI.DomElement.setLocation(_backgroundDiv, panelBounds.x - mainBounds.x, panelBounds.y - mainBounds.y);


        //    set the progress element to this position
        if (_updateProgressDiv != null) {
            var updateWidth = _updateProgressDiv.clientWidth;
            var updateHeight = _updateProgressDiv.clientHeight;


            if (updateWidth == 0) {
                if (_updateProgressDiv.style.pixelWidth != undefined)
                { updateWidth = _updateProgressDiv.style.pixelWidth; } else { updateWidth = 80; }
            }
            if (updateHeight == 0) {
                if (_updateProgressDiv.style.pixelHeight != undefined)
                { updateHeight = _updateProgressDiv.style.pixelHeight; } else { updateHeight = 40; }
            }

            var x = panelBounds.x - mainBounds.x + Math.round(panelBounds.width / 2) - Math.round(updateWidth / 2);
            var y = panelBounds.y - mainBounds.y + Math.round(panelBounds.height / 2) - Math.round(updateHeight / 2);
            Sys.UI.DomElement.setLocation(_updateProgressDiv, x, y);
        }
        //  place the div over the gridview

        t = setTimeout('showUpdating()', 100);
        _updateProgressDiv.style.display = '';
        _backgroundDiv.style.display = '';
    }


}

function showUpdating() {
    if (_updating == true) {
        if (_updateProgressDiv != null) {
            _updateProgressDiv.style.display = '';
        }
    }
}


function getEmbeddedChild(parent, ctrlName) {

    if (parent == null) {
        parent = document;
    }

    var elem = parent.getElementsByTagName("*");
    for (var i = 0; i < elem.length; i++) {
        if (elem[i].id == ctrlName) {
            return elem[i]
        }
    }
    return null
}


function getParentWrap(ele) {
    var pEle = getParent(ele);
    while ((pEle != null) && (pEle.id != 'main')) {
        if (pEle.attributes != null && pEle.attributes.updatewrap != null) {
            return pEle;
        }
        else {
            pEle = getParent(pEle);
        }
    }
}
function getabsolutewrap(ele) {
    var pEle = getParent(ele);
    while ((pEle != null) && (pEle.id != 'main')) {
        if (pEle.attributes != null && pEle.attributes.absolutewrap != null) {
            return pEle;
        }
        else {
            pEle = getParent(pEle);
        }
    }
}



function getParent(ele) {

    return ele.parentNode;
}

function MakeScrollDiv() {

    var divScroll;
    divScroll = $get('divScroll');
    if (divScroll != null) {

        var headfoot = 450;
        if (divScroll.attributes.headfoot != null && divScroll.attributes.headfoot.nodeValue != null) {
            headfoot = divScroll.attributes.headfoot.nodeValue;
        }

        var winHeight = windowSize(true) - headfoot;
        winHeight = (winHeight < 0) ? 0 : winHeight;



        if (divScrollHeight > winHeight && winHeight > 0) {
            divScroll.style.height = winHeight + 'px';
            divScroll.style.overflowX = "hidden";
            divScroll.style.overflow = "scroll";
        }
        else if (divScrollHeight == 0 || winHeight == 0) {
            divScroll.style.height = '200px';
            divScroll.style.overflowX = "hidden";
            divScroll.style.overflow = "scroll";
        }
        else {
            divScroll.style.height = divScrollHeight + 'px';
            //divScroll.style.overflowX = "hidden";
            //divScroll.style.overflow = "hidden";

        }



    }

}

function windowSize(Height) {
    var myWidth = 0, myHeight = 0;
    if (typeof (window.innerWidth) == 'number') {
        //Non-IE
        myWidth = window.innerWidth;
        myHeight = window.innerHeight;
    } else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
        //IE 6+ in 'standards compliant mode'
        myWidth = document.documentElement.clientWidth;
        myHeight = document.documentElement.clientHeight;
    } else if (document.body && (document.body.clientWidth || document.body.clientHeight)) {
        //IE 4 compatible
        myWidth = document.body.clientWidth;
        myHeight = document.body.clientHeight;
    }

    if (Height == true) {
        if (isNaN(parseFloat(myHeight))) {
            return 0;
        }
        else {
            return myHeight;
        }
    }
    else {
        if (isNaN(parseFloat(myWidth))) {
            return 0;
        }
        else {
            return myWidth;
        }

    }

}


function KeyingBuyMe(item, qty) {
    if (qty == 0) {
        return;
    }
    else {
        BuyMe(item, qty)
    }


}



function BuyMe(item, qty) {
    cartProduct = item;

    if (qty == 0) {
        if (confirm('Remove Item?') == false) {
            return;
        }
    }
    else {
        //track the addition
        if (typeof (_gat) != "undefined") {
            var pageTracker = _gat._getTracker("UA-785006-1");
            pageTracker._initData();
            pageTracker._trackPageview(window.location.pathname + '?track=Add2Cart&Product=' + item + '&qty=' + qty);
        }


    }
    if (cartRequest == false) {

        try {
            $find('modalCartLoading').show(); //while loading cart
        } catch (ex) { }

        cartRequest = true;
        var wRequest = new Sys.Net.WebRequest();
        wRequest.set_httpVerb("GET");
        wRequest.set_url(SiteRoot + "/ASHX/Cart.ashx?ItemID=" + item + "&Qty=" + qty);
        wRequest.add_completed(BuyMeFinish);
        wRequest.invoke();
    }
    else {
        alert('Please wait');
    }
}

function BuyMeFinish(executor, eventArgs) {
    if (executor.get_responseAvailable()) {
        //load data into the array
        //show the cart
        //__doPostBack('CartRendor', '');



        showCart();
        UpdateCartCookie();

        cartRequest = false;
    }
    else {
        alert('There was a problem with the request. Please try again');
    }

}
function getCookie(c_name) {
    if (document.cookie.length > 0) {
        c_start = document.cookie.indexOf(c_name + "=");
        if (c_start != -1) {
            c_start = c_start + c_name.length + 1;
            c_end = document.cookie.indexOf(";", c_start);
            if (c_end == -1) c_end = document.cookie.length;
            return unescape(document.cookie.substring(c_start, c_end));
        }
    }
    return "";
}



function CartHidden() {

    UpdateCartCookie();


}



function CartLoadingShown() {

    if (cancelCartLoading == true) {
        $find('modalCartLoading').hide();
        cancelCartLoading = false;
        return;
    }
}

function CartShown() {


    if (cancelCart == true) {
        $find('modalCart').hide();
        cancelCart = false;
        return;
    }

    ScrollDivRendor();

    ValidCartPage();

    try {
        $find('modalCartLoading').hide();
    }
    catch (ex) {
    }


}

function cancelLoading() {
    cancelCart = true;
    cancelCartLoading = true;
    try {
        $find('modalCartLoading').hide();
    } catch (ex) { }
    try {
        $find('modalCart').hide();
    } catch (ex) { }

}

function UpdateCartCookie() {

    var s = getCookie("SNCart");
    var cookieItems = s.split('&');
    var qty = '0';
    for (i = 0; i < cookieItems.length; i++) {
        if (cookieItems[i].indexOf("Qty") >= 0) {
            if (cookieItems[i].length > 4) {
                qty = cookieItems[i].substring(4, (cookieItems[1].length));
            }

        }
    }

    if (qty > 0) {
        if (qty == 1) {
            $get(clientBase + 'hlCartLink').innerHTML = 'Checkout / Cart (' + qty + ' item)';
        }
        else {
            $get(clientBase + 'hlCartLink').innerHTML = 'Checkout / Cart (' +  qty + ' items)';
        }
    } else {
        $get(clientBase + 'hlCartLink').innerHTML = 'Your Shopping Cart is Empty';
    }


}