var BHG = window.BHG || {};

BHG.CatalogCookie = (function () {

    var cookieName = "cataloglist";

    // TODO: test vs. function FindCrumb(crumbs, crumbName) {
    var FindCrumb = function (crumbs, crumbName) {

        if (crumbs === null) {
            return null;
        }

        var i = 0;
        for (; i < crumbs.length; i++) {
            var crumb = crumbs[i].split("=");

            if (crumb[0] === crumbName) {
                return crumb[1];
            }
        }

        return null;
    };

    return {

        GetCrumb: function (crumbName) {

            var cookie = $.cookie(cookieName);

            if (cookie === null) {
                return null;
            } else {
                var crumbs = cookie.split("&");

                return FindCrumb(crumbs, crumbName);
            }
        }
    };
})();

BHG.CategoryCookie = (function () {

    var categoryCookieName = "selectedCategory";

    return {

        Get: function () {
            return $.cookie(categoryCookieName);
        },

        Reset: function () {
            this.Set(null);
        },

        Set: function (value) {
            $.cookie(categoryCookieName, value, { path: '/' });
        }
    };
})();

BHG.ResetSearch = function () {
    $.cookie("cataloglist", "category=ALL", { raw: true, path: "/servlet/" });
    BHG.CategoryCookie.Reset();
};

// if a user enters something into product search, this fills it back into the edit box on the results page
BHG.PersistProductSearch = function () {
    if (/\/Categories$/.test(document.location)) {
        var productName = $("#ProductName"), crumb = BHG.CatalogCookie.GetCrumb("product");
        if (crumb !== null) {
            productName[0].value = crumb.replace(/\+/g, ' ');
        }
    }
};

BHG.Category = (function () {
	var openItemId = "", selectItemId = "";
	
    selectItemId = BHG.CategoryCookie.Get();

    if (selectItemId === null) {
        selectItemId = "";
        openItemId = "";
    } else {
        if (selectItemId.length === "itemX".length) { // then we are a parent node
            openItemId = selectItemId;
        } else {
            openItemId = selectItemId.substr(0, selectItemId.length - 1);
        }
    }
        
    return {
        OpenItemId: function () {
			return openItemId;
		},
        SelectItemId: function () {
			return selectItemId;
        }
    };
})();

BHG.InitializeCategoryTree = function () {

    var url = 
    $("#CategoriesTree").jstree({
        "themes": {
            "theme": "default",
            "url": "/themes/default/style.css",
            "dots": false,
            "icons": false
        },
        "core": { "initially_open": [BHG.Category.OpenItemId()] },
        "ui": { "select_limit": 1, "selected_parent_close": false,
            "initially_select": [BHG.Category.SelectItemId()]
        },
        "plugins": ["themes", "html_data", "ui"]
    });

    $("#CategoriesTree").show();
};

// Main

$(function () {
    $(".panel-layout").removeAttr("width"); // ProStores wraps right content div in a table with a width of 100%
    $("#ProductName").attr("name", "$catalog.product"); // ProStores strips the name attribute from the HTML

    $("#Search").button();

    $(".ShoppingCart").button({
        icons: {
            primary: "ui-icon-cart"
        }
    });

    BHG.InitializeCategoryTree();

    BHG.PersistProductSearch();

    $("#CategoriesTree a").click(function (event) {
        BHG.ResetSearch();
        BHG.CategoryCookie.Set(this.parentNode.id);
        window.location = this.href;
    });

    $("#ProductsLink").click(function () {
        BHG.ResetSearch();
    });
});

// Products

BHG.Products = (function () {

    var AttachSelect = function (textBoxId, selectId, crumbName) {

        var textBox = $(textBoxId), select = $(selectId);

        select.change(function () {
            textBox.val($(selectId).val());
        });

        var crumb = BHG.CatalogCookie.GetCrumb(crumbName);

        textBox.val(crumb);

        select.val(crumb === null ? "" : crumb);
    };

    var ProductName = function () {
        $("#ProductNameCopy").attr("name", "$catalog.product");
        var productNameCopy = $("#ProductNameCopy");
        productNameCopy[0].value = BHG.CatalogCookie.GetCrumb("product");
    };

    var Publisher = function () {
        var publisher = $("#Publisher");
        publisher.attr("name", "$catalog.oem");
        var crumb = BHG.CatalogCookie.GetCrumb("oem");
        publisher[0].value = crumb === null ? "" : crumb.replace(/\+/g, ' ');
    };

    var CustomTexts = function () {
        $("#Custom1Textbox").attr("name", "$catalog.custom1");
        $("#Custom2Textbox").attr("name", "$catalog.custom2");
        $("#Custom3Textbox").attr("name", "$catalog.custom3");

        AttachSelect("#Custom1Textbox", "#Custom1Select", "custom1");
        AttachSelect("#Custom2Textbox", "#Custom2Select", "custom2");
        AttachSelect("#Custom3Textbox", "#Custom3Select", "custom3");
    };

    var Price = function () {
        var price = BHG.CatalogCookie.GetCrumb("price");
        $("#priceRange").val(price === null ? "all" : price);
    };

    var Advanced = function () {
        if ($("#Custom1Select")[0].selectedIndex > 0 ||
			$("#Custom2Select")[0].selectedIndex > 0 ||
			$("#Custom3Select")[0].selectedIndex > 0 ||
			$("#priceRange")[0].selectedIndex > 0 ||
			$("#Publisher")[0].selectedIndex > 0) {
            $("#AdvancedSearch").show();
        } else {
            $("#AdvancedSearch").hide();
        }

        $("#AdvancedSearchLink").toggle(function () {
            $("#AdvancedSearch").show();
        }, function () {
            $("#AdvancedSearch").hide();
        });
    };

    var Category = function () {
        if (window.location.href.lastIndexOf("/Categories") !== -1) {

            var selectedCategory = BHG.CategoryCookie.Get();
            if (selectedCategory === null || selectedCategory === "" || $("#Category" + selectedCategory).length === 0) {
                selectedCategory = "All";
            }
            $("#Category" + selectedCategory).show();
        }
    };

    return {

        Initialize: function () {

            $("#Refresh").button();

            ProductName();

            Publisher();

            CustomTexts();

            Price();

            Advanced();

            Category();

            $(".Sale").button({
                icons: {
                    primary: "ui-icon-tag"
                }
            });
        }
    };
})();

// Product Details

function tuple(lv, uv) {
    this.lowerValue = lv;
    this.upperValue = uv;
}

BHG.ProductDetails = (function () {

    var ParseInt = function (integer) {
        var parsed = parseInt(integer, 10);

        if (isNaN(parsed)) {
            parsed = null;
        }

        return parsed;
    };

    var ConvertPlayingTime = function (minutes) {

        if (minutes === null || isNaN(minutes) || minutes === 0) {
            return "";
        } else {
            return minutes + " min";
        }
    };

    var SwitchManufacturerToPublisher = function () {
        var manufacturer = $("h1 + div");
        if (manufacturer[0].innerHTML.toLowerCase().indexOf("<b>n/a</b>") == -1) {
            manufacturer[0].innerHTML = manufacturer[0].innerHTML.replace("Manufacturer", "Publisher");
        } else {
            manufacturer.hide();
        }
    };

    var FixReturnToProductsLink = function () {
        var returnToCatalogLink = $("a[href='/servlet/Categories']").last();
        returnToCatalogLink.addClass("NormalLink");
        returnToCatalogLink[0].innerHTML = "Return to Products";
    };

    var HideCustomTextsColumnsIfNeeded = function () {
        if ($("#agesDisplay")[0].innerHTML == "") {
            $("#agesHeader").hide();
            $("#agesDisplay").hide();
        }
        if ($("#numberOfPlayersDisplay")[0].innerHTML == "") {
            $("#numberOfPlayersHeader").hide();
            $("#numberOfPlayersDisplay").hide();
        }
        if ($("#playingTimeDisplay")[0].innerHTML == "") {
            $("#playingTimeHeader").hide();
            $("#playingTimeDisplay").hide();
        }
    };

    var CustomTexts = function () {
        if ($("#agesDisplay")[0].innerHTML != "" || $("#numberOfPlayersDisplay")[0].innerHTML != "" || $("#playingTimeDisplay")[0].innerHTML != "") {
            $("#customTextsDetails").detach().appendTo(".product-detail-content table .common-container:first");
            $("#customTextsDetails").show();
        }
    };

    var Prices = function () {
        var prices = $(".large_price").parent().html();

        var a = prices.indexOf("Retail: ");

        var b = prices.toLowerCase().lastIndexOf("<br>");

        var retailPrice = prices.substring(a + "Retail: ".length, b);

        if (retailPrice == $(".large_price").html()) {
            prices = prices.substring(0, a) + prices.substr(b + "<br>".length);
        } else {
            //prices = prices.replace(new RegExp("<br>Retail: ", "gi"), "<span id='retailPrice'>");
            //prices = prices.replace(new RegExp("<br>", "gi"), "</span><br/>");
            prices = FixPrices(prices);
        }

        $(".large_price").parent().html(prices);
    };

    var FixPrices = function (prices) {
        var retailPriceRegExp = new RegExp("<br>.+<br>");

        var retailPrice = prices.match(retailPriceRegExp)[0];

        prices = prices.replace(retailPriceRegExp, "<br/>");
        prices = prices.substr("Price: ".length);

        var retailLength = "<br>Retail: ".length;

        prices = "Price: <span id='retailPrice'>" +
                    retailPrice.substr(retailLength, retailPrice.length - retailLength - "<br>".length) +
                    "</span>" +
                    prices;

        return prices;
    };

    var FixAddedToCart = function () {
        if ($(".added_to_cart")) {
            $(".added_to_cart td:last").after("<td><a href='/servlet/Cart' id='ProductDetailsProceedToCheckout'>Proceed To Checkout >></a></td>");
            $("#ProductDetailsProceedToCheckout").button();
        }
    };

    return {

        Initialize: function () {
            $("input[type=submit]").button();

            SwitchManufacturerToPublisher();

            $("#imgtable + div").height(0);

            FixReturnToProductsLink();

            $("#ages").ConvertAges("#agesDisplay");

            $("#playingTime").ConvertPlayingTime("#playingTimeDisplay");

            $("#numberOfPlayers").ConvertNumberOfPlayers("#numberOfPlayersDisplay");

            HideCustomTextsColumnsIfNeeded();

            CustomTexts();

            Prices();

            $("input[name='qty']").addClass("qty");

            FixAddedToCart();
        },

        ConvertAgesToDisplay: function (ages) {

            var lowerValue = null, upperValue = null;

            if (ages.length === 1) {
                lowerValue = ParseInt(ages[0]);
                if (lowerValue === 14) {
                    lowerValue = lowerValue.toString() + "+";
                }
            } else if (ages.length === 2) {
                lowerValue = ParseInt(ages[0]);
                upperValue = ParseInt(ages[1]);

                if (upperValue === 14) {
                    upperValue = upperValue.toString() + "+";
                }
            }

            return new tuple(lowerValue, upperValue);
        },

        ConvertPlayingTimeToDisplay: function (times) {

            var lowerValue = null, upperValue = null;

            if (times.length === 1) {
                lowerValue = ConvertPlayingTime(ParseInt(times[0]));
            } else if (times.length === 2) {
                lowerValue = ParseInt(times[0]);

                upperValue = ConvertPlayingTime(ParseInt(times[1]));
            }

            return new tuple(lowerValue, upperValue);
        },

        ConvertNumberOfPlayersToDisplay: function (players) {

            var lowerValue = null, upperValue = null;

            if (players.length === 1) {
                lowerValue = ParseInt(players[0]);
            } else if (players.length >= 2) {
                lowerValue = ParseInt(players[0]);
                upperValue = ParseInt(players[1]);
            }

            return new tuple(lowerValue, upperValue);
        }
    };
})();

BHG.SetElementValues = function (id, val) {
    if (val.lowerValue !== null) {

        if (val.upperValue === null) {
            $(id)[0].innerHTML = val.lowerValue;
        } else {
            $(id)[0].innerHTML = val.lowerValue + " to " + val.upperValue;
        }
    }
};

BHG.SplitDiv = function (jqueryDiv) {

    var div = $(jqueryDiv)[0];

    return div.innerHTML.split('-');
};

(function ($) {

    $.fn.ConvertAges = function (displayId) {
        return this.each(function () {

            var ages = BHG.SplitDiv(this);

            var val = BHG.ProductDetails.ConvertAgesToDisplay(ages);

            BHG.SetElementValues(displayId, val);
        });
    },

    $.fn.ConvertPlayingTime = function (displayId) {
        return this.each(function () {

            var times = BHG.SplitDiv(this);

            var val = BHG.ProductDetails.ConvertPlayingTimeToDisplay(times);

            BHG.SetElementValues(displayId, val);
        });
    },

    $.fn.ConvertNumberOfPlayers = function (displayId) {
        return this.each(function () {

            var number = BHG.SplitDiv(this);

            var val = BHG.ProductDetails.ConvertNumberOfPlayersToDisplay(number);

            BHG.SetElementValues(displayId, val);
        });
    }

})(jQuery);

var tracking = location.pathname.match("/Tracking$");
var trackingInvoice = location.search.match("^\\?invoice=");
if (tracking != null && tracking[0]==="/Tracking" && trackingInvoice != null && trackingInvoice[0]==="?invoice=") {
    $(function () {
        $("input[type='submit']").button();
        $("#content").css("width", "940px");
        $("#content-left").css("padding-right", "20px");
        $("input[type='submit']").css("margin-top", "10px");
        $("input[type='submit']").css("margin-bottom", "10px");
    });
}
