﻿///////////////////////////////////////////
// Memory Express jQuery Functionality   //
// http://www.memoryexpress.com/         //
///////////////////////////////////////////

/** jQuery No Conflict **/
var jQ = jQuery.noConflict();

/********* Common Functions ***********/

jQ(document).ready(function() {
    var cb = jQ("#colorbox");
    if (cb == null)
        return;

    cb.prependTo("form:first");
});

function LookupVariable(varName, context) {
    var varItem = null;

    if (context != null)
        varItem = jQ("var." + varName, context);
    else
        varItem = jQ("var." + varName);

    if (varItem == null)
        return "";

    return varItem.html();
}

function IsNumeric(sText) {
    var ValidChars = "0123456789.";
    var IsNumber = true;
    var Char;

    for (i = 0; i < sText.length && IsNumber == true; i++) {
        Char = sText.charAt(i);
        if (ValidChars.indexOf(Char) == -1) {
            IsNumber = false;
        }
    }
    return IsNumber;
}

/******** Global Registrations ********/

// Any element with class="Event_NoPropigation" will prevent click's from bubbling up the chain!
jQ(document).ready(function() {
    jQ(".Event_NoPropigation").each(function() {
        jQ(this).click(function(e) {
            e.stopPropagation();
        });
    });
});

/******** Validation ***********/

function validate_range(self, min, max) {
    var val = jQ(self).attr('value');

    if (!IsNumeric(val))
        jQ(self).attr('value', min);

    if (val > max)
        jQ(self).attr('value', max);
    if (val < min)
        jQ(self).attr('value', min);
}

/********* Product Details **********/

// IPR Panel Postback
jQ(document).ready(function() {
// All Radio Buttons in the IPR Selector
    var options = jQ(".ipr_options input[type='radio']");
    if (options != null)
        options.each(function() { InitPanelPostback(this); });
    //var InputItems = jQ(".ipr_options input");
});

function InitPanelPostback(obj) {
    jQ(obj).click(function() {
        var postBackElement = jQ(".ipr_post_back");
        if (postBackElement == null)
            return;

        var productElement = jQ(".ipr_product");
        if (productElement == null)
            return;

        var url = postBackElement.first().attr("value");
        var product = productElement.first().attr("value");

        var val = jQ(this).attr("value");

        var priceSummary = jQ("#PriceSummary");
        var view = "Regular";
        if (priceSummary == null || priceSummary.size() == 0)
            view = "Bundle";

        jQ("#AddIPR").attr('value', val);

        jQ.ajax({
            type: "POST",
            url: url,
            data: { iprKey: product, iprSelect: val, viewType: view },
            dataType: "html",
            success: function(h) {
                var replaceContext = jQ("#PriceSummary");
                if (replaceContext == null || replaceContext.size() == 0)
                    replaceContext = jQ("#Ajax_Replace_PriceDetails");

                replaceContext.html(h);
                // Re-Bind
                RegisterPDBundleMouseOverlay(replaceContext);
                RegisterPDBundleDetails(replaceContext);

                UpdatePriceFromVar();
            }
        });
    });
    UpdatePriceFromVar();
}

function UpdatePriceFromVar() {
    var varLookup = jQ("#Ajax_PriceCopy");
    var varReplace = jQ("#Ajax_PriceReplace");

    if (varLookup == null || varReplace == null) {
        return;
    }

    varReplace.html(varLookup.html());
}

// IPR About IPR Popup
jQ(document).ready(function() {
    var iprAbout = jQ(".ipr_about a[rel='aboutIPR']");
    
    if (iprAbout == null)
        return;
    
    iprAbout.colorbox({
        inline: true,
        href: ".ipr_popup",
        height: "75%",
        width: "60%"
    });
    jQ(".ipr_popup_close").click(function(event) {
        event.preventDefault();
        iprAbout.colorbox.close();
    });
});

// MouseOver For Bundle Details
jQ(document).ready(function() {
    RegisterPDBundleMouseOverlay(null);
    //return false;
});

function RegisterPDBundleMouseOverlay(context)
{
    var pdBundleOverlay = jQ("#BundleMouseOverlay");

    if (pdBundleOverlay.length == 0)
    {
        return false;
    }
    
    pdBundleOverlay.hide();
    
    var links;
    if (context == null)
        links = jQ(".LI_Title a.Action_ProductDetails");
    else
        links = jQ(".LI_Title a.Action_ProductDetails", context);
}

// Bundle Details Panel
jQ(document).ready(function() {
    RegisterPDBundleDetails(null);
});

function RegisterPDBundleDetails(context) 
{
    // #PriceDetails a.Action_ProductDetails

    var links;
    var rows;
    if (context == null) {
        links = jQ(".Action_ProductDetails");
        rows = jQ("div.PP_LineItem");
    }
    else {
        links = jQ(".Action_ProductDetails", context);
        rows = jQ("div.PP_LineItem", context);
    }

        
    if (links.length == 0) {
        return false;
    }
    
    links.unbind("click"); // Incase we're traversing an existing link (we probably wont be)
    links.bind("click", function(e) {
        //alert("Start!");
        if (e.preventDefault) {
            e.preventDefault();
        }
        else {
            // IE is stupid! :)
            e.returnValue = false;
        }

        //alert("We Made it!");

        memxShowProductDetails(this);

        return false;
    });

    rows.hover(
        function() {
            jQ(this).addClass("PP_Hover").addClass("PP_Hover_Base");
            var titles = jQ(this).find(".PP_Title");
            var prices = jQ(this).find(".PP_Price");
            titles.addClass("PP_Hover");
            prices.addClass("PP_Hover");

            ShowBundleOverlay(this);
        },
        function() {
            jQ(this).removeClass("PP_Hover").removeClass("PP_Hover_Base");
            jQ(this).find(".PP_Title").removeClass("PP_Hover");
            jQ(this).find(".PP_Price").removeClass("PP_Hover");

            HideBundleOverlay();
        }
    );

    var overlay = jQ("#BundleMouseOverlay");
    
    overlay.hover(
        function() {
            clearTimeout(overlay.data('timeoutId'));
        },
        function() {
            HideBundleOverlay();
        }
    );
}

function ShowBundleOverlay(item) {
    var overlay = jQ("#BundleMouseOverlay");
    var overlayBody = jQ("#BundleMouseOverlay .BMO_Body");

    clearTimeout(overlay.data('timeoutId'));

    overlayBody.html("");

    var lSKU = LookupVariable("Lookup_MXID", jQ(item));
    var lILC = LookupVariable("Lookup_ILC", jQ(item));
    var lTitle = LookupVariable("Lookup_Title", jQ(item));

    // Title
    var spanTitle = jQ("<h6></h6>");
    spanTitle.html(lTitle);
    overlayBody.append(spanTitle);

    // Image
    var img = jQ("<img />");
    img.attr('src', "/Images/Products/ShowImage.axd?ImgType=Product&ImgID=" + lSKU + "(ME)-0&ImgSize=Default");
    overlayBody.append(img);

    // Numbers
    var table = jQ("<table></table>").attr('align', 'center');
    var ulNumbers = jQ("<tr></tr>");
    ulNumbers.addClass("float");
    ulNumbers.addClass("float_2px");
    if (lSKU != "")
        ulNumbers.append(jQ("<td><strong>SKU: </strong>" + lSKU + "</td>\n"));
    if (lILC != "")
        ulNumbers.append(jQ("<td><strong>ILC: </strong>" + lILC + "</td>"));

    table.append(ulNumbers);
    overlayBody.append(table);

    var linePosition = jQ(item).position();

    overlay.show();
    overlay.css({
        top: (linePosition.top-26) + "px",
        left: (linePosition.left-250) + "px"
    });
}

function HideBundleOverlay() {
    var overlay = jQ("#BundleMouseOverlay");

    var timeoutId = setTimeout(function() { overlay.fadeOut(250); }, 100);
    overlay.data('timeoutId', timeoutId);
}

// Called by Bundle Details Line Items' OnClick() Function
function memxShowProductDetails(item) {
    var prodID = jQ(item).attr('rel');
    var details = jQ("#DetailsDialog-" + prodID);

    if (details.length) {
        // We have a dialog, let's ajax load it!
        if (details.html() == "") {
            // we're empty, insert the loading image and ajax load it!
            details.html("<img src=\"/Images/Common/loading.gif\" />");

            jQ.ajax({
                type: "POST",
                //contentType: "application/json",
                url: "/AjaxHelper.asmx/GetProductSummary",
                dataType: "html",
                data: { productId: prodID },
                success: function(h) {
                    details.html(h);
                },
                error: function(request, status, err) {
                    details.html("<b>An Error Occured: " + status + "</b><br /><p>" + err + "</p>");
                }
            });
        }

        details.dialog({ 
            width: 430, 
            height: 330,
            draggable: true,
            resizable: false,
            closeText: "Close"
        });
    }
}

jQ(document).ready(function() {
    jQ("a.Colorbox_IFrameLink").colorbox({ width: "60%", height: "75%", iframe: true });
});

/* Inventory DropDown */

jQ(document).ready(function() {
    RegisterInventoryDropDown();
});

function RegisterInventoryDropDown() {
    var dropButton = jQ("#CityInventory .PInv_DropDown");
    var dropBar = jQ("#Inv_Selection");
    var dropList = jQ("#Inv_CityList");
    var dropBody = jQ("#Inv_Details");

    if (dropButton == null ||
        dropBar == null ||
        dropList == null ||
        dropBody == null)
        return;

    var dropPos = jQ("#CityInventory").position();

    dropBar.data("open", false);

    // Drop Down Click Function //
    dropBar.click(function(e) {
        e.stopPropagation();
        var open = dropBar.data("open");
        if (open) {
            HideInventoryList(dropBar, dropList);
        }
        else {

            // Align the overlay
            dropList.css({
                left: 0 + "px",
                top: -2 + "px"
            });
            dropList.show();
            dropBar.data("open", true);
            jQ(document).data("inventoryOpen", dropBar);
        }
    });
}

function SelectInventoryCity(city) {
    var dropBar = jQ("#Inv_Selection");    
    var dropBody = jQ("#Inv_Details");

    dropBar.data("open", false);

    HideInventoryList(dropBar, null);

    var cityInventory = jQ("#Inv_Details_" + city);
    if (cityInventory == null)
        return;

    UpdateInventorySelection(city);

    dropBar.html(city);
    dropBody.html(cityInventory.html());
}

function HideInventoryList(dropBar, dropList) {
    if (dropList == null)
        dropList = jQ("#Inv_CityList");
    if (dropBar == null)
        dropBar = jQ("#Inv_Selection");
        
    dropBar.data("open", false);
    dropList.hide();
}

function UpdateInventorySelection(city) {
    /* Ajax Call */
    jQ.ajax({
        type: "POST",
        url: '/AjaxHelper.asmx/UpdateInventoryRegion',
        data: { region: city }
    });
}

/** Close Click For Inventory **/
jQ(document).click(function(e) {
    var dropBar = jQ("#Inv_Selection");
    if (dropBar.data("open") == true)
        HideInventoryList(dropBar, null);
});

/** Rollover for inventory **/
jQ(document).ready(function() {
    jQ(".PInv_Select_Rollover").hover(
        function() {
            jQ(this).addClass("PP_Hover");
        },
        function() {
            jQ(this).removeClass("PP_Hover");
        }
    );
});

/***** Add To Cart: Special Order Notification *****/
jQ(document).ready(function() {
    jQ(".SpecialOrder_AddToCart").each(function() {
        // Foreach Special Order Add-To-Cart Button
        var webActionButton = jQ(this).siblings("var").first();
        if (webActionButton == null)
            return;

        jQ(this).colorbox({
            inline: true,
            href: "#SpecialOrder_Confirmation",
            width: "400px",
            height: "260px",
            onOpen: function() {
                jQ("#SpecialOrder_Confirmation .AddToCartButton").html(webActionButton.html());
            }
        });
    });
    jQ("#SpecialOrder_Confirmation .CloseButton").click(function(event) {
        event.preventDefault();
        jQ.fn.colorbox.close();
    });
});

/** Logo Contest Entry Colorbos **/

jQ(document).ready(function() {
    jQ(".LogoEntry_Colorbox").colorbox({
        width: "700px",
        height: "500px",
        photo: true
    });
});