﻿$(document).ready(function () {

    var timeout = 1000;
    var closetimer = 0;
    var activeMenuItem;

    //Top menu - 2nd level slide down
    $("#topmenu>ul>li").hover(
        function () {
            if (closetimer) {
                window.clearTimeout(closetimer);
                closetimer = null;
                if (activeMenuItem && activeMenuItem != this)
                    $("#topmenu").find("li ul").hide();
            }
            var $ul = $("ul", this);
            $ul.fadeIn(250);
            activeMenuItem = this;
        },
        function () {
            closetimer = window.setTimeout(function () {
                $("#topmenu").find("li ul").hide();
            }, timeout);
        }
    );

    $(".emailinput").keypress(function (e) {
        if (e.which == 13) {
            submitNewsletter(e);
        }
    });

    //Newsletter signup
    $(".signupbutton").click(function (e) {
        submitNewsletter(e);
    });

    $(".inputlabel").click(function (e) {
        $(this).hide();
        $(this).siblings(".bglabel").focus();
    });

    $(".searchinput").keypress(function (e) {
        if (e.which == 13) {
            searchProducts(e);
        }
    });

    $(".searchbutton").click(function (e) {
        searchProducts(e);
    });

    //Newsletter signup
    $("a.iframe").fancybox({
        'width': 432,
        'height': 245,
        'type': 'iframe',
        'autoScale': 'false',
        'transitionIn': 'none',
        'transitionOut': 'none'
    });

    // Placeholder for input(s)
    $(".bglabel").focus(function (e) {
        $(this).addClass("active");
    }).blur(function (e) {
        if ($(this).val() === "") {
            $(this).removeClass("active");
            $(this).siblings(".inputlabel").show();
        }
    }).each(function () {
        var $this = $(this);
        if ($this.val() !== "")
            $this.addClass("active");
    });

    // Thumbnails left click
    $(".mylist-wrapper").delegate(".left", "click", function () {
        var imageWidth = $(".thumbs > li:first").outerWidth(true);
        if ($(".thumbs").position().left < 0 && !$(".thumbs").is(":animated")) {
            $(".thumbs").animate({ left: "+=" + imageWidth + "px" });
        }
        return false;
    });

    // Thumbnails right click
    $(".mylist-wrapper").delegate(".right", "click", function () {
        var totalImages = $(".thumbs > li").length,
                    imageWidth = $(".thumbs > li:first").outerWidth(true),
                    totalWidth = imageWidth * totalImages,
                    visibleImages = Math.round($(".thumbslider").width() / imageWidth),
                    visibleWidth = visibleImages * imageWidth,
                    stopPosition = (visibleWidth - totalWidth);

        if ($(".thumbs").position().left > stopPosition && !$(".thumbs").is(":animated")) {
            $(".thumbs").animate({ left: "-=" + imageWidth + "px" });
        }
        return false;
    });

    $(".teaser-content").click(function () {
        var articleLink = $(this).closest('.wysiwyg-block').find('.readmore').attr('href');
        if (articleLink)
            location.href = articleLink;

        return false;
    });

    if (!IsInEditMode()) {
        var shopResp = $.cookie('pp');
        if (!shopResp) {
            // There is no cookie from shop.peakperformance.com,
            // so check if we have our own cookie.
            var resp = $.JSONCookie('userinfocookie');

            if (!resp.d) {
                getUserInfo(); //Get cookie if it has not been set
            }
            else {
                setUserInfoOrRedirect(resp);
            }
        }
        else {
            // There is a cookie from shop.peakperformance.com.
            // Check if we have our own cookie.

            var resp = $.JSONCookie('userinfocookie');

            if (!resp.d) {
                getUserInfo(); //Get cookie if it has not been set
            }
            else {
                // Parse the shop-cookie to find country
                var shopRespElements = shopResp.split('|');
                var shopCountryISO = "";
                var shopCountryISORegEx = /^ciso=(.+)/;
                $.each(shopRespElements, function (index, value) {
                    var match = shopCountryISORegEx.exec(value);
                    if (match) {
                        shopCountryISO = match[1];
                    }
                });

                if (resp.d.CountryISOCode !== shopCountryISO) {
                    getUserInfo(); // Get new userinfo cookie, if it doesnt match the shop-country
                }
                else {
                    setUserInfoOrRedirect(resp);
                }
            }

        }
    }

    // Add separator line above the comment container
    (function () {
        var $blogcomments = $(".blog-body > .comment-container");
        if ($blogcomments.length > 0) {
            var $sep = $("<div />").
                            css("borderTop", "1px solid #8f8e90").
                            css("borderBottom", "1px solid #8f8e90").
                            css("paddingTop", "4px").
                            css("marginLeft", "-145px").
                            css("marginBottom", "15px");
            $sep.insertBefore($blogcomments);
        }
    })();
});
// END DOCUMENT READY

var getUserInfo = function () {
    $.ajax({
        url: '/Custom/Services/PeakPerformance/UserInfo.svc/GetUserInfo',
        dataType: 'json',
        type: 'GET',
        contentType: "application/json; charset=utf-8",
        success: function (resp) {
            $.JSONCookie('userinfocookie', resp, { path: '/' });
            setUserInfoOrRedirect(resp);
        },
        error: function () {
        }
    });
}

var setUserInfoOrRedirect = function (resp) {

    // Get EPiServer content-language
    var contentLanguage = $("meta[http-equiv=content-language]").attr("content");

    if (resp.d.LanguageISOCode !== contentLanguage) {
        // The current page does not match the language specified in our own cookie,
        // so we must redirect to another language version of this page.

        var postData = {};
        postData.redirectParameters = {};
        postData.redirectParameters.currenturl = window.location.pathname;
        postData.redirectParameters.languagecode = resp.d.LanguageISOCode;

        $.ajax({
            url: '/Custom/Services/PeakPerformance/UserInfo.svc/GetRedirectInfo',
            data: JSON2.stringify(postData),
            dataType: 'json',
            type: 'POST',
            contentType: "application/json; charset=utf-8",
            success: function (resp) {
                if (resp.d.NeedsRedirect) {
                    window.location = resp.d.RedirectUrl;
                }
            },
            error: function () {
            }
        });
    }

    var loginLink = $("#login_link");
    loginLink.text(resp.d.LoginText);
    loginLink.attr('title', resp.d.LoginText);
    loginLink.attr('href', resp.d.LoginLink);

    var bagLink = $("#bag_link");
    bagLink.html(resp.d.ShoppingBagText);

    bagLink.attr('href', resp.d.ShoppingBagLink);
    bagLink.attr('title', resp.d.ShoppingBagText);

    $("#country_link strong").text(resp.d.CountryText);

    if (resp.d.IsLoggedIn)
        $("#loggedin").show();
    else
        $("#loggedin").hide();
}

var submitNewsletter = function (e) {
    e.preventDefault();
    $("form").attr("action", "http://shop.peakperformance.com/newsletter");
    $("form").submit();
}

var searchProducts = function (e) {
    e.preventDefault();
    $("form").attr("action", "http://shop.peakperformance.com/search/?f_default=" + $(".searchinput").val());
    $("form").submit();
}

var IsInEditMode = function () {
    if ((window.location.search.indexOf('idkeep') !== -1) || (window.location.pathname.indexOf('/admui/') === 0)) {
        return true;
    }
    return false;
}
