﻿$(document).ready(function() {

    // page bottom shopping cart:

    $(function() {
        var wHeight = $(window).height();
        var wWidth = $(window).width();
        var cHeight = ($("#newCart").height() + 30);
        var cWidth = ($("#newCart").width() + 30);
        var cTop = ((wHeight - cHeight) + "px");
        var cLeft = (((wWidth - cWidth) / 2) + "px");
        $("#newCart").css("left", cLeft);
        $("#newCart").animate({ bottom: 0 }, 1000);
    });

    //CDI brands nav

    $(function() {
        $("#btnShppingEqBilling").click(function() {

            var firstName = $("#BillingFirstName").val();
            var lastName = $("#BillingLastName").val();
            var phone = $("#BillingPhone").val();
            var company = $("#BillingCompany").val();
            var addrType = $("#BillingResidenceType").val();
            var addr1 = $("#BillingAddress1").val();
            var addr2 = $("#BillingAddress2").val();
            var suite = $("#BillingSuite").val();
            var city = $("#BillingCity").val();
            var country = $("#BillingCountry").val();
            var state = $("#BillingState").val();
            var zip = $("#BillingZip").val();



            $("#ShippingFirstName").val(firstName);
            $("#ShippingLastName").val(lastName);
            $("#ShippingPhone").val(phone);
            $("#ShippingCompany").val(company);
            $("#ShippingResidenceType").val(addrType);
            $("#ShippingAddress1").val(addr1);
            $("#ShippingAddress2").val(addr2);
            $("#ShippingSuite").val(suite);
            $("#ShippingCity").val(city);
            $("#ShippingCountry").val(country);
            $("#ShippingState").val(state);
            $("#ShippingZip").val(zip);

            return false;
        });
    });

    $(function() {
        $("#cdiNav > li > a.brandLink").hide();
        function brandsOver() {
            var liContents = $(this).children("a.brandLink").html();
            var href = $(this).children("a.brandLink").attr("href");
            $(this).append("<a id='brandLinkHover' href='" + href + "'>" + liContents + "</a>");
            $("a#brandLinkHover").fadeIn(500);
        };
        function brandsOut() {
            $("a#brandLinkHover").remove();
        };
        $("#cdiNav > li").hoverIntent(brandsOver, brandsOut);

    });

    //Brand categories menu
    $(function() {
        $("li:has(div.catListContainer),li:has(div.catListContainerRight)").mouseover(function() {
            $(this).addClass("hover");
        });
        $("li:has(div.catListContainer),li:has(div.catListContainerRight)").mouseout(function() {
            $(this).removeClass("hover");
        });
        $("div.catListContainer, div.catListContainerRight").hide();
        $("li:has(div.catListContainer),li:has(div.catListContainerRight)").hoverIntent(function() {
            var div = $(this).children("div.catListContainer,div.catListContainerRight");

            if (div.is(":animated")) {
                div.stop()
                   .css("height", "auto")
                   .slideDown(200);
            }
            else {
                div.css("display", "none");
                div.slideDown(200);
            }
        },
        function() {
            var div = $(this).children("div.catListContainer,div.catListContainerRight");

            if (div.is(":animated")) {
                div.stop()
                .css("height", "auto")
                .slideUp(40);
            }
            else {
                div.slideUp(40);
            }

        });
    });

    //FAQ accordion




    $(function() {
        $(".faq > div, .faq > div > div").hide();
        $(".faq > h3, .faq > div > h4").click(function() {
            $(this).siblings().removeClass("selected");
            if ($(this).hasClass("selected")) {
                $(this).removeClass("selected");
            }
            else {
                $(this).addClass("selected");
            }

            var $nextDiv = $(this).next("div");
            var $toggleVisDiv = $nextDiv.siblings("div:visible");

            if ($toggleVisDiv.length) {

                $toggleVisDiv.slideUp("200", function() {
                    $nextDiv.slideToggle("200");
                });
            }
            else {
                $nextDiv.slideToggle("200");
            }
        });
    });



    //    $(function() {
    //        runOnLoad(function() {
    //            var leftColHeight = $("#productLeftCol").height();
    //            var rightColHeight = $("#productRightCol").height();

    //            if (leftColHeight > rightColHeight) {

    //                $("#productRightCol").height(leftColHeight + "px").css("margin-bottom", "0")
    //            };
    //        });
    //    });

    $(function() {
        runOnLoad(function() {
            var leftColHeight = $("#productLeftCol").height();
            var rightColHeight = $("#productRightColSeries").height();

            if (leftColHeight > rightColHeight) {

                $("#productRightColSeries").height(leftColHeight + "px").css("margin-bottom", "0")
            };
        });
    });

    $(function() {
        var panelHeight = $("div#description").height();
        if (panelHeight < 150) {
            panelHeight = (150);
            $("div#description").height("150px");
        };
        var specHeight = $("div#specs").height();
        if (specHeight > panelHeight) {
            $(".specChart").width("440px");
        };
        $("#specs,#moreInfo,#awards").height(panelHeight);
    });

    $(function() {
        $(".searchBox").click(function() {
            $(this).attr("value", "");
        });
    });


    $(function() {
        var linkWidth = $(".purchaseOptionLink:first").width();
        function setLinkWidth() {
            linkWidth = ((linkWidth - 12) / 2);
            $("#purchaseOptionsArrow").css("left", linkWidth + "px");
        };
        $(".purchaseOptionLink:first").append("<span id='purchaseOptionsArrow'></span>");
        setLinkWidth();

        $(".purchaseOptionLink").click(function() {
            var EventName = $(this).attr("href");
            var IPAddress = $("#IPAddress").val();
            var CustomerID = $("#CustomerID").val();
            var VariantID = $("#VariantID").val();
            $.ajax({
                type: "POST",
                url: "http://cascadedesigns.com/showproduct.aspx/LogEvent",
                data: "{'variantID':'" + VariantID + "', 'customerID':'" + CustomerID + "', 'ipAddress':'" + IPAddress + "', 'eventName':'" + EventName + "'}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function(msg) {
                    // Do something interesting here.
                }
            });
            $("#purchaseOptionsArrow").remove();
            linkWidth = $(this).width();
            $(this).append("<span id='purchaseOptionsArrow'></span>");
            setLinkWidth();
        });
    });


    //Buy Online
    function buyOnline() {
        var boList = ("<ul id='buyOnlineTabs'><li><a href='#us'>U.S. Retailers</a></li><li><a href='#can'>Canadian Retailers</a></li><li><a href='#eur'>European Retailers</a></li></ul>");
        var multiSKU = $("div#purchaseSKU").find("select");
        var IPAddress = $("#IPAddress").val();
        var customerID = $("#CustomerID").val();
        var locale = $("#Locale").val();
        if (multiSKU.length == 0) {
            $("#USTemplate").html("");
            var SKU = $("#VariantID").val();
            var dealerType = 1;

            $.ajax({
                type: "POST",
                url: "http://cascadedesigns.com/cdi_ajaxservice.asmx/GetBuyOnlineString",
                data: "{'VariantID':'" + SKU + "', 'CustomerID':'" + customerID + "', 'IPAddress':'" + IPAddress + "', 'LogEvent':'0', 'locale':'" + locale + "'}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function(msg) {
                    $("#USTemplate").append(boList + msg.d);
                    $("#buyOnlineTabs").idTabs(function(id, list, set) {
                        $("a", set).removeClass("selected").filter("[href='" + id + "']", set).addClass("selected");
                        for (i in list)
                            $(list[i]).hide();
                        $(id).fadeIn();
                        return false;
                    });
                },
                error: function(msg) {
                    $("#USTemplate").append("<p>No online retailers could be found for this product.</p>");
                }
            });
        }
        else {
            $("#VariantID").change(function() {
                var tabSelected = 0;
                if ($("#purchaseOnline").is(':visible')) {
                    tabSelected = 1;
                }
                $("#USTemplate").html("");
                var SKU = $("#VariantID").val();
                if (SKU == "-1") {
                    alert(chooseSKU)
                }
                var dealerType = 1;

                $.ajax({
                    type: "POST",
                    url: "http://cascadedesigns.com/cdi_ajaxservice.asmx/GetBuyOnlineString",
                    data: "{'VariantID':'" + SKU + "', 'CustomerID':'" + customerID + "', 'IPAddress':'" + IPAddress + "', 'LogEvent':'" + tabSelected + "', 'locale':'" + locale + "'}",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function(msg) {
                        $("#USTemplate").append(boList + msg.d);
                        $("#buyOnlineTabs").idTabs(function(id, list, set) {
                            $("a", set).removeClass("selected").filter("[href='" + id + "']", set).addClass("selected");
                            for (i in list)
                                $(list[i]).hide();
                            $(id).fadeIn();
                            return false;
                        });
                    },
                    error: function(msg) {
                        $("#USTemplate").append("<p>No online retailers could be found for this product.</p>");
                    }
                });
            });
        }

    }

    // Dealer Locator:
    $(function() {
        var searchType = "";
        var searchText = "";
        var SKU = "";
        var distance = "";
        var productPage = "true";
        $("div.newForm > input.dealerRadio").click(function() {
            if ($(this).siblings("input").attr("checked", "checked")) {
                $(this).siblings("input").removeAttr("checked");
            }
            var radioVal = $(this).val();
            var distanceLbl = $(this).parent().children("label.distanceMiles");
            var distanceSel = $(this).parent().children("select");
            if (radioVal == "Zip") {
                distanceLbl.show();
                distanceSel.show();
            }
            else if (radioVal == "State") {
                distanceLbl.hide();
                distanceSel.hide();
            }
            else {
                distanceLbl.hide();
                distanceSel.hide();
            }
            $(this).attr("checked", "checked");
        });


        // $("div.newForm > input.findDealers").click(function() {
        function locateDealer(searchText, distance) {
            SKU = $("#VariantID").val();
            //searchText = $(this).parent().children(".searchText").val();
            //distance = $(this).parent().children("select").val();
            if (distance == null) {
                distance = 0;
            }
            ipAddress = $("#IPAddress").val();
            customerID = $("#CustomerID").val();
            locale = $("#Locale").val();


            function makeTheCall() {

                if ($(".includeNon").attr("checked") == true) {
                    SKU = 0;
                }
                if ($("#noSKU").val() == 0) {
                    SKU = 0;
                    productPage = "false";
                    $("#locatorResultsContainer").remove();
                    $('#dealerLocator').append("<div id='locatorResultsContainer'></div>");
                    $('#locatorResultsContainer').append("<div id='locatorResults' style='display:none'></div>");
                    $('#locatorResultsContainer').append("<div id='locatorResultsLoading'></div>");
                }
                else {
                    tb_show("", "TB_inline?&amp;width=900&amp;height=450");
                    $("#locatorResults").remove();
                    $('#TB_ajaxContent').append("<div id='locatorResults' style='display:none'></div>");
                    $('#TB_ajaxContent').append("<div id='dealerLocatorLoading'></div>");
                }
                $.ajax({
                    type: "POST",
                    url: "http://cascadedesigns.com/cdi_ajaxservice.asmx/GetDealerString",
                    data: "{'searchType':'" + searchType + "', 'searchValue':'" + searchText + "', 'distance':'" + distance + "', 'isProductPage':'" + productPage + "', 'variantID':'" + SKU + "', 'customerID':'" + customerID + "', 'ipAddress':'" + ipAddress + "', 'locale':'" + locale + "' }",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function(msg) {
                        var dealerResponse = JSON.parse(msg.d);
                        if (dealerResponse.results == "true") {

                            $('#locatorResults').append("<p>" + dealerResponse.message + "</p>");
                            $('#locatorResults').append("<ul id='locatorResultsList'></ul>");
                            var i = 0;
                            for (i = 0; i < dealerResponse.dealers.length; i++) {
                                var iter = dealerResponse.dealers[i];

                                var csz = (iter.city + ", " + iter.state + " " + iter.zip);
                                if (iter.address2 != "") {
                                    var addr2 = ("<br />" + iter.address2 + "<br />");
                                }
                                else {
                                    var addr2 = ("<br />");
                                }
                                if (iter.phone != "") {
                                    var phone = ("<br />" + iter.phone);
                                }
                                else {
                                    var addr2 = ("<br />");
                                }
                                if (iter.url != "") {
                                    var website = ("<br /><a href='" + iter.url + "' target='_new'>" + iter.website + "</a>");
                                }
                                else {
                                    var website = "";
                                }

                                $("#locatorResultsList").append("<li><strong>" + iter.name + "</strong><br /><a href='" + iter.googleaddress + "'>" + iter.mappable + "</a><br />" + iter.address1 + addr2 + csz + "<br/>" + iter.country + phone + website + "</li>")
                            }
                            if ($("#noSKU").val() == 0) {
                                $("#locatorResultsLoading").remove();
                            }
                            else {
                                $("#dealerLocatorLoading").remove();
                            }
                            $('#locatorResults').show();

                        }
                        else {
                            $('#locatorResults').append("<p>" + dealerResponse.message + "</p>");

                            var onlineRetailerHTML = $("#purchaseOnline").html();
                            if (dealerResponse.headers != null) {
                                $('#locatorResults').append("<div id='refineSearch'><h2 class='hMedMarg'>" + dealerResponse.headers[0] + "</h2><br /></div><div id='chooseOnline'><h2 class='hMedMarg'>" + dealerResponse.headers[1] + "</h2><br /></div>");
                            }
                            $('.newForm').clone(true).appendTo('#refineSearch');
                            $('#chooseOnline').append(onlineRetailerHTML);
                            if (dealerResponse.headers != null) {
                                $('#refineSearch > .newForm > .findDealers').before('<input type="checkbox" name="includeNon" class="includeNon" /><label>' + includeNonPurchasers + '</label><br />');
                            }
                            if ($("#noSKU").val() == 0) {
                                $("#locatorResultsLoading").remove();
                            }
                            else {
                                $("#dealerLocatorLoading").remove();
                            }
                            $('#locatorResults').show();

                        }
                    },
                    error: function(msg) {
                        alert(ajaxError);
                    }

                });
            }


            if (SKU == "-1") {
                alert(chooseSKU)
            }
            else {
                $(".dealerRadio").each(function(i) {
                    if ($(this).attr("checked")) {
                        searchType = $(this).val();
                    }
                });
                if (searchType == "Zip") {
                    //alert("zip required");
                    var re_Zip = /(^\d{5}(-\d{4})?$)|(^[ABCEGHJKLMNPRSTVXY]{1}\d{1}[A-Z]{1} *\d{1}[A-Z]{1}\d{1}$)/.test(searchText);
                    if (!re_Zip) {
                        alert(alertZip)
                    }
                    else {
                        makeTheCall();
                    }
                }
                else if (searchType == "State") {
                    if (searchText.length != 2) {
                        alert(alertState);
                    }
                    else {
                        makeTheCall();
                    }
                }
                else if (searchType == "Country") {
                    var re_Country = /[a-zA-Z]/.test(searchText);
                    if (!re_Country) {
                        alert(alertCountry);
                    }
                    else {
                        makeTheCall();
                    }
                }
                else {
                    var re_City = /[a-zA-Z]/.test(searchText);
                    if (!re_City) {
                        alert(alertCity);
                    }
                    else {
                        makeTheCall();
                    }
                }
                return false;

            }
        }

        $('#theForm').submit(function() {
            return false;
        });

        $('.searchText').keyup(function(event) {
            if (event.keyCode == 13) {
                searchText = $(this).val();
                distance = $(this).parent().children("select").val();
                $(this).blur();
                locateDealer(searchText, distance);
                return false;
            }
        });
        $(".findDealers").click(function() {
            searchText = $(this).parent().children(".searchText").val();
            distance = $(this).parent().children("select").val();
            locateDealer(searchText, distance);
            return false;
        });





    });

    // Add to Cart:
    $(function() {
        function addToCart() {
            //var url = $("#goToCart").attr("href");

            var SKU = $("#VariantID").val();
            if (SKU == "-1") {
                alert(chooseSKU)
            }
            else {
                var quantity = $("#Quantity").val();
                var cartType = $("#CartRecID").val();
                var productID = $("#ProductID").val();
                var inv = "sku" + SKU;
                var inventory = this[inv][0];
                var item = this[inv][1];
                var re_Quantity = /^\d+$/.test(quantity);
                var IPAddress = $("#IPAddress").val();
                var CustomerLevel = $("#CustomerLevel").val();
                if (!re_Quantity || quantity == 0) {
                    alert("Please specify the quantity you want to add to your cart");
                }
                else if (inventory == 0) {
                    alert("We are currently out of stock on the " + item + ". \nPlease try another another product or choose either the\nBuy From An Authorized Local Store or\nBuy From An Authorized Online Store options.");
                }
                else if (quantity > inventory) {
                    alert("Your quantity exceeds our stock on hand. The maximum \nquantity that can be added for the\n" + item + " is " + inventory);
                }
                else {
                    $.ajax({
                        type: "POST",
                        url: "http://cascadedesigns.com/cdi_ajaxservice.asmx/AddToCart",
                        data: "{'CustomerGuid':'" + cst + "', 'ProductID':'" + productID + "', 'VariantID':'" + SKU + "', 'Quantity':'" + quantity + "', 'intCartType':'" + cartType + "', 'ipAddress':'" + IPAddress + "', 'CustomerLevel':'" + CustomerLevel + "'}",
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        success: function(msg) {
                            $("#cartNumItems").text(msg.d);
                            $("#cdiCart > ul").addClass("notice");
                            var productName = $("#VariantID :selected").text();
                            if (productName == "") {
                                productName = $("#purchaseSKU").text();
                            };
                            var productName = ('<p class="smallerText">' + quantity + ' <span>' + productName + '</span> has been added to your cart.</p><p class="smallerText"><a id="continueShop" href="#">Continue Shopping</a>&nbsp;&nbsp;or&nbsp;&nbsp;<a href="' + $("#goToCart").attr("href") + '">Check out</a></p>');
                            $("#purchaseCDI").append('<div id="cartContents">' + productName + '</div>');

                            $("#cartContents").fadeIn(600);

                            function removeCart() {
                                $("#cartContents").remove();
                            };

                            $("#continueShop").click(function() {
                                removeCart();
                                return false;
                            });

                            $("#cartContents").animate({ top: "10px" }, { duration: 4000 });
                            $("#cartContents").fadeOut(600, removeCart);
                        },
                        error: function(msg) {
                            alert("There was an error adding this item to your cart.");
                        }
                    });
                }
            };
        }

        $(".AddToCartButton").click(function() {
            addToCart();
            return false;
        });
        $('#Quantity').keyup(function(event) {
            if (event.keyCode == 13) {
                addToCart();
                return false;
            }
        });


    });




    if ($('#USTemplate').length) {
        buyOnline();
    };

    // Get Distributor
    function getDistributor(country) {
        var locale = $("#Locale").val();
        $("#locatorResultsContainer").remove();
        $("#international").append("<div id='locatorResultsContainer'></div>");
        $('#locatorResultsContainer').append("<div id='locatorResults' style='display:none'></div>");
        $('#locatorResultsContainer').append("<div id='locatorResultsLoading'></div>");
        $.ajax({
            type: "POST",
            url: "http://cascadedesigns.com/cdi_ajaxservice.asmx/GetDistributorString",
            data: "{'Country':'" + country + "', 'locale':'" + locale + "'}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(msg) {
                $("#locatorResults").append(msg.d);
                $("#locatorResultsLoading").remove();
                $('#locatorResults').show();
            },
            error: function(msg) {
                $("#locatorResults").append("<p>No distributors could be found for this country.</p>");
                $("#locatorResultsLoading").remove();
                $('#locatorResults').show();
            }
        });
    };

    $("#frmLocators").submit(function() {
        var country = $("#drpCountries").val();
        getDistributor(country);
        return false;
    });


    $(function() {
        var padWidth = ((960 - $(".brandCatNav").width()) / 2);
        $(".brandCatNav").css("padding-left", padWidth);
    });

    $(function() {
        $("#langContainer > ul").hide();
        $("#langContainer > ul").css("top", "16px");
        $("#currentLang").click(function() {
            $("#langContainer > ul").slideToggle(200);
        });
    });


    // Sub-series accordion
    $(function() {

        var heights = [];
        var l = $('.catPageProductList').length;
        $('.catPageProductList').each(function(index) {
            heights[index] = $(this).height();
            var h = 0;
            $(this).children("li").each(function(index) {
                if (index < 3) {
                    if ($(this).height() > h) {
                        h = ($(this).height() + 5)
                    }
                }
            });
            $(this).height(h);
            heights[index + l] = h;
        });

        $('.moreSeries').live("click", function() {
            var n = $(".moreSeries").index(this);


            $('.moreSeries').each(function(index) {
                if ($(this).parent("div").hasClass("activeSeries")) {
                    $(this).parent("div").children("ul").animate(
                    {

                        height: heights[index + l]

                    }, 500
                    );
                    $(this).parent("div").removeClass("activeSeries");
                }
            });

            $(this).parent("div").addClass("activeSeries");


            //            $('.moreSeries').parent('div:not(.activeSeries)').each(function(index) {
            //                if ($(this).find(".fader").length == 0) {

            //                    $(this).append("<div class='fader'>&nbsp;</div>");

            //                }
            //            });

            //            $(this).parent("div").remove(".fader");

            $('.fader').each(function(index) {
                $(this).animate(
                        {
                            height: heights[index + l],
                            opacity: .3
                        }, 1
                    );
            });

            var s = heights[n];

            $(this).parent("div").children("ul").animate(
                {
                    height: s
                }, 500
            );

            return false

        });


    });





});


