﻿
var GMapTypes = {
	"m": G_NORMAL_MAP,
	"k": G_SATELLITE_MAP,
	"h": G_HYBRID_MAP
}

var KL = {
    AfterLoginJSONRequest: null,

    StyleMapView: function(switcher) {

        if (switcher == "on") {
            // category page styling
            $(".mediaview-panel").hide();
        }
        else {
            $(".mediaview-panel").show();
        }
    },

    ZoomLevel: {
        region: 6,
        destination: 12
    },

    Template: {
        parse: function(body, template) {
            return body.replace(/{([^{}]*)}/g, function(a, b) {
                var r = template[b];
                return typeof r === 'string' || typeof r === 'number' ? r : a;
            });
        }
    },

    showOverlay: function(selector) {

        $.blockUI({
            message: $(selector),
            css: {
                width: "550px",
                height: "250px",
                left: "33%",
                textAlign: "left",
                padding: "0",
                border: "0",
                top: "15%"
            }
        });
    },

    closeOverlay: function(selector) {
        $(selector).fadeOut("slow");
        $.unblockUI();
        return false;
    },

    showMapInfoWindow: function(maplink, gmap, marker) {

        if (!maplink.id && !maplink.title)
            return;

        if (!maplink.id && maplink.title) {

            var win = $("<div />");

            $(win).load(KLParams.baseURL + "Vinter/UI/smallMapInfoWindow.htm", function(response) {
                $(this).html(KL.Template.parse($(this).html(), {
                    title: "<a href='" + maplink.href + "'>" + maplink.title + "</a>"
                })
				    );

                marker.openExtInfoWindow(
                    gmap,
                    "small_info_window",
				    $(this).html(),
				    { beakOffset: 3 }
				);

            });

            return;
        }

        $.getJSON(KLParams.baseURL + "JSON/Product.ashx", { method: "get", mid: maplink.id, sp: KLParams.settingsPageId, cp: KLParams.currentPageId }, function(json) {

            var win = $("<div />");
            var mc = gmap.getContainer();
            var product = json.result;

            $(win).load(KLParams.baseURL + "Vinter/UI/mapInfoWindow.htm", function(response) {

                var comment;
                if (product.CommentCount == 0)
                    comment = "<a class='comments icon' href='" + product.URL + "#comments'>0</a>";
                else if (product.CommentCount == 1)
                    comment = "<a class='comments icon' href='" + product.URL + "#comments'>1</a>";
                else
                    comment = "<a class='comments icon' href='" + product.URL + "#comments'>" + $.strFormat(product.CommentCount) + "</a>";

                var like;

                if (product.Liked)
                    like = "<span class='liked icon selected'>" + Translate.liked + "</span>";
                else
                    like = "<a class='like icon product' rel='id:" + maplink.id + "' href='#'>" + Translate.like + "</a>";

                $(this).html(KL.Template.parse($(this).html(), {
                    title: "<a href='" + product.URL + "'>" + product.Name + "</a>",
                    image: (product.HasThumbnail) ? "<img src='" + product.Thumbnail + "' alt='" + product.ThumbnailAlternateText + "' />" : "",
                    comments: comment,
                    like: like,
                    readmore: "<a href='" + product.URL + "'>" + Translate.read_more + " &raquo;</a>",
                    body: product.IntroText
                }));

                marker.openExtInfoWindow(
			      gmap,
			      "custom_info_window",
			      $(this).html(),
			      { beakOffset: 3 }
			    );
            });

        });

    },

    stopFlash: function(p) {
        var o = $("[id^='mediaItemContainer_']:not(div)", p);
        if (o.length == 1) {
            var m = o.get(0);
            if (typeof (m.stopMovie) == 'function') {
                m.stopMovie();
            }
        }
    },

    clearTextBox: function(id, value) {
        $("#" + id).val(value);
    },

    ActivateTab: function(panelId) {

        if (panelId == "#mapWrapper") {
            $.cookie("activetab", "mapview", { expires: 365, path: '/' });
            $(".tabs li:last").addClass("active");
            $(".tabs li:first").removeClass("active");
            $("body").addClass("map-view");
            KL.StyleMapView("on");

            $("#mapWrapper").show();
            var map = new KL.maps(KL.MapOptions)

        }
        else {
            $.cookie("activetab", "normal", { expires: 365, path: '/' });
            $(".tabs li:first").addClass("active");
            $(".tabs li:last").removeClass("active");
            $("body").removeClass("map-view");
            KL.StyleMapView("off");

            $("#mapWrapper").hide();
        }
    },

    validateJSONResponse: function(json, data) {
        if (json && json.error) {
            switch (json.error.code) {
                case -32811:
                    KL.AfterLoginJSONRequest = data.url;
                    KL.showOverlay("#login");
                    break;
                default:
                    KL.AfterLoginJSONRequest = null;
                    break;
            }
        }
        return;
    }
    ,
    getNVC: function(val) {

        var params = {}

        $(val.split("-")).each(function(i, item) {

            if (!item.indexOf(":")) return;

            var arr = item.split(":");
            params[arr[0]] = arr[1];
        });

        return params;
    },

    MapOptions: null,

    BindJSONEvents: function() {

        $("a.like").live("click", function() {

            var elm = $(this);
            var method = elm.hasClass("page") ? "addpage" : "addproduct";

            var newCount = parseInt($(this).text()) + 1;

            $.getJSON(KLParams.baseURL + "JSON/Like.ashx", { method: method, mid: KL.getNVC($(this).attr("rel")).id }, function(json) {
                KL.validateJSONResponse(json, this);

                if (json.result == "ok") {
                    elm.fadeOut("slow", function() {
                        elm.replaceWith($("<span/>").text(newCount).addClass("like icon selected").fadeIn("slow"));
                    });
                }
            });

            return false;
        });
        $("a.favorite").live("click", function() {

            var elm = $(this);
            var method = elm.hasClass("page") ? "addpage" : "addproduct";

            $.getJSON(KLParams.baseURL + "JSON/Favorite.ashx", { method: method, mid: KL.getNVC($(this).attr("rel")).id }, function(json) {
                KL.validateJSONResponse(json, this);

                if (json.result == "ok") {
                    elm.fadeOut("slow", function() {
                        elm.replaceWith($("<span/>").text(Translate.saved_as_favorite).addClass("favorite icon selected").fadeIn("slow"));
                    });
                }
            });

            return false;
        });
        $("a.delete-favorite").live("click", function() {
            var elm = $(this.parentNode);

            $.getJSON(KLParams.baseURL + "JSON/Favorite.ashx", { method: "delete", mid: $(this).attr("rel") }, function(json) {
                KL.validateJSONResponse(json, this);
                if (json.result == "ok") {
                    elm.fadeOut("slow");
                }
            });

            return false;
        });
        $("a.delete-comment").live("click", function() {
            var elm = $(this.parentNode.parentNode);

            $.getJSON(KLParams.baseURL + "JSON/Comment.ashx", { method: "delete", mid: KL.getNVC($(this).attr("rel")).pid, cid: KL.getNVC($(this).attr("rel")).cid }, function(json) {
                KL.validateJSONResponse(json, this);
                if (json.result == "ok")
                    elm.fadeOut("slow");
            });

            return false;
        });
    },

    init: function() {

        /* dropdown main navigation */
        $("#mainNavigation>li").each(function(i, item) {
            if ($("ul", item).length == 1) {
                $("a:first", item).click(function() {
                    $("ul", item).css("width", $(item).width()).slideToggle();
                    return false;
                });
            }
        })

        KL.BindJSONEvents();

        $("fieldset#login").keyup(function(e) {
            if (e.keyCode == 13) {
                $("#loginButton").trigger("click");
            }
        });

        KL.MapOptions = {
            default_zoom: KL.ZoomLevel.region,
            map_container_id: "map_canvas",
            map_link_class: ".map-link",
            parse_page_links: true,
            zoom_to_bounds: false
        }

        // login link
        $("a#loginLink").click(function() {
            KL.showOverlay("#login");
        });

        // close login form
        $("fieldset#login .close-window-link").click(function() {
            KL.closeOverlay("#login");
        });

        // close login form on click outside
        $('body').click(function(e) {
            KL.closeOverlay("#login");
        });

        $('#loginLink, #login').click(function(event) {
            event.stopPropagation();
        });

        // cufon
        Cufon.replace('#shortcuts a, .social-media-links a, .weather-info .temperature, #columnContainer dd h4, #columnContainer dd span.info, #sidebar h3, .login-links-container h4, fieldset#login .login-form h3');

        // initialize media-views

        $(".media-view.start").mediaView({
            oninit: function(m, n, p) {
                n.css("left", 959 - n.width());

                var pa = $(".image-information", p);

                var pl = $("p", pa).text().length;
                var hl = $("h5", pa).text().length;

                if (pl == 0 && hl == 0) {
                    pa.hide();
                }
                else {
                    if (hl == 0) $("h5", pa).hide();
                    if (pl == 0) $("p", pa).hide();
                    pa.css("left", 959 - pa.width()).fadeIn();
                }

                $(m, ".panel").mouseenter(function() {
                    $(".text-content", this).animate({ marginLeft: "0" }, 300);
                }).mouseleave(function() {
                    $(".text-content", this).animate({ marginLeft: "-321" }, 300);
                });

                $(".text-content", m).css("margin-left", -321);

            },
            onpanelprechange: function(c, n, m) {
                $(".image-information", n).hide();
            },
            onpanelchanged: function(c, p, m) {
                var pa = $(".image-information", c);
                var pl = $("p", pa).text().length;
                var hl = $("h5", pa).text().length;

               // console.log(pl);
               // console.log(hl);

                if (pl == 0 && hl == 0) {
                    pa.hide();
                }
                else  {
                    if (hl == 0) $("h5", pa).hide();
                    if (pl == 0) $("p", pa).hide();
                    pa.css("left", 959 - pa.width()).fadeIn();
                }

                KL.stopFlash(p);
            },
            auto_play: true
        });

        $(".media-view.category").mediaView({
            oninit: function(m, n, p) {
                n.css("left", 600 - n.width());
                var p = $(".image-information", p);
                p.css("left", 600 - p.width()).fadeIn();
            },
            onpanelprechange: function(c, n, m) {
                $(".image-information", n).hide();
            },
            onpanelchanged: function(c, p, m) {
                var pa = $(".image-information", c);
                pa.css("left", 600 - pa.width()).fadeIn();
                KL.stopFlash(p);
            },
            auto_play: true
        });

        $(".media-view.product").mediaView({
            oninit: function(m, n, p) {
                n.css("left", 600 - n.width());
                var p = $(".image-information", p);
                p.css("left", 600 - p.width()).fadeIn();
            },
            onpanelprechange: function(c, n, m) {
                $(".image-information", n).hide();
            },
            onpanelchanged: function(c, p, m) {
                var pa = $(".image-information", c);
                pa.css("left", 600 - p.width()).fadeIn();
            },
            auto_play: true
        });

        $(".media-view.small").mediaView({
            auto_play: false,
            fade_speed: 800
        });

        $(".media-view.liked-products").mediaView({
            hide_prev: true,
            hide_next: true,
            fade_speed: 600,
            auto_play: false,
            onnavitemrendered: function(panel, n) {
                n = $(n);
                n.html("<span>" + n.text() + "</span>");
            }
        });

        /* OVERLAYS */

        // add overlay on media-view small image
        $(".media-view.small img").before("<span class='rounded-corners'></span>");

        // add overlay on media-view small image
        $("#mediaContainerLiked.media-view. img").before("<span class='rounded-corners'></span>");

        // add overlay on product images       
        $(".product-image img").before("<span></span>");

        // init calendar/datepicker
        $("#datepicker").datepicker();

        // set active tab        
        if ($.cookie("activetab") == "mapview") {
            KL.ActivateTab("#mapWrapper");
        }
        else {
            KL.ActivateTab("#bodyWrapper");
        }

        // map links        
        $("a.map-link").click(function() {
            KL.ActivateTab("#mapWrapper");
        })

        $($(".tabs li.active a").attr("href")).show();

        $(".tabs a").click(function() {

            if (!$(this).parent().hasClass("active")) {
                var activatePanelID = $(this).attr("href");
                var deActivatePanelID = $(".tabs li.active a").attr("href");

                KL.ActivateTab(activatePanelID);
            }
            return false;
        });

        // add class to last sitemap-item
        if (!$("ul.sitemap li:last-child").hasClass("last"))
            $("ul.sitemap li:last-child").addClass("last");

        // add class top navigation li
        $("#topNavigation li:first").addClass("first");
        $("#topNavigation li:last").addClass("last");
        
        $("#topNavigation li ul li:last").addClass("flag");

        // set active top navigation
        $("#topNavigation li a").each(function(i, o) {
            if (o.href && o.href.toLowerCase() == document.location.href.toLowerCase())
                $(o).parent().addClass("active");
        });
        
        //dropdown topNavigation
        $("#topNavigation>li").each(function(i, item) {
            if ($("ul", item).length == 1) {
                $("a:first", item).click(function() {
                    $(item).toggleClass("first");                    
                    $("ul", item).toggle();
                    return false;
                });
            }
        })        
        
        // expand user terms
        $("#userTermsLink").click(function() {
            $("fieldset.register-user .user-terms").slideToggle("slow");
            return false;
        });

        // expand related products on product page        
        $(".related-products-listing a.show-all").click(function() {
            $(this).fadeOut("slow");
            $(".related-products-listing .all-products").slideToggle("slow");
            return false;
        });

        // expand/collapse product details                          
        $(".collapsible.closed dd").each(function() {
            $(this).hide();
        });
        $(".collapsible.closed p").each(function() {
            $(this).hide();
        });

        $(".collapsible .toggle-collaps").click(function() {

            var c = $(this).parent();

            if ($(this).parent().hasClass("closed")) {
                $(this).parent().removeClass("closed");
                $(c.children(), c).slideDown("slow");
            }
            else {
                $(this).parent().addClass("closed");
                $($(this).siblings()).slideUp("slow");
            }
            return false;
        });

        // stripe table           
        $("table.stripe-me").each(function(i, item) {
            $('tr:odd', item).addClass("alt");
        });

        // report comment
        $(".report-comment-link").click(function() {
            var t = $(this);
            $(".report-comment", this.parentNode.parentNode).
                fadeIn("slow").
                css("top", t.position().top - 170).
                css("left", t.position().left);

            $(".close-report-form").click(function() {
                $(".report-comment", this.parentNode.parentNode).
                fadeOut("slow");
                return false;
            });
            return false;
        });

        // login
        $("#loginButton").click(function() {
            if ($.validate({ fieldset: "#login", messagecontainer: "#loginValidationMsg" })) {
                $.getJSON(KLParams.baseURL + "JSON/User.ashx", { method: "login", username: $("#username").val(), password: $("#password").val(), mid: 0 }, function(json) {
                    KL.validateJSONResponse(json, this);

                    if (json != null && json.error == null) {
                        if (KL.AfterLoginJSONRequest) {
                            $.getJSON(KL.AfterLoginJSONRequest, function() {
                                document.location.reload();
                            });
                        }
                        else
                            document.location.reload();
                    }
                    else {
                        $("#loginValidationMsg").empty();
                        $("#loginValidationMsg").text(Translate.invalid_username_or_password);
                    }
                });
            }
        });

        // profile link
        $("#toolsWrapper .profile").click(function() {
            $(this).toggleClass("active");
        })

        // send comment report via json
        $(".send-report-button").click(function() {
            var container = $(this).parent().parent();
            var i_name = $(".reportername", container).val();
            var i_email = $(".reporteremail", container).val();
            var i_comment = $(".comment", container).val();
            var i_url = $(".link", container).val();
            var i_desc = $("textarea", container).val();

            if (i_name == "") {
                var input = $(".reportername", container);
                var container = $(input).parent();
                $("span.errmsg", container)
                    .fadeIn("slow")
                    .animate({ opacity: 1.0 }, 3000)
                    .fadeOut('slow', function() {
                        $(this).remove();
                    });
                return false;
            }
            if (i_email == "") {
                var input = $(".reporteremail", container);
                var container = $(input).parent();
                $("span.errmsg", container)
                    .fadeIn("slow")
                    .animate({ opacity: 1.0 }, 3000)
                    .fadeOut('slow', function() {
                        $(this).remove();
                    });
                return false;
            }

            var params = {
                method: "report",
                mid: 0,
                sp: KLParams.settingsPageId,
                na: i_name,
                cm: i_comment,
                em: i_email,
                li: i_url,
                de: i_desc
            }

            $.getJSON(KLParams.baseURL + "JSON/Comment.ashx", params, function(json) {
                var confirmationText = "Kommentaren är anmäld."; //translate  
                $(container).html("<h4>" + confirmationText + "</h4>");

                setTimeout(function() {
                    $(container).fadeOut();
                }, 1000);
            });

            return false;
        });



        // initialize map
        if ($("#mapWrapper").css("display") == "block")
            var mainmap = new KL.maps(KL.MapOptions);

        // advanced search        
        $("a.advanced-search-link").click(function() {
            $("div.advanced-search").toggle("slow");
            return false;
        });

        // weather
        $("a.celsius").click(function() {
            var c = this.parentNode.parentNode.parentNode.parentNode;
            $("div.celsius, span.celsius").fadeIn("slow");
            $("div.fahrenheit, span.fahrenheit").hide();
            $("a.celsius", c).addClass("active");
            $("a.fahrenheit", c).removeClass("active");
            $.cookie("temperature", "celsius", { expires: 7, path: '/' });
            return false;
        });

        $("a.fahrenheit").click(function() {
            var c = this.parentNode.parentNode.parentNode.parentNode;
            $("div.celsius, span.celsius", c).hide();
            $("div.fahrenheit, span.fahrenheit", c).fadeIn("slow");
            $("a.celsius", c).removeClass("active");
            $("a.fahrenheit", c).addClass("active");
            $.cookie("temperature", "fahrenheit", { expires: 7, path: '/' });
            return false;
        });

        $("a.expand-forecast").click(function() {
            var c = this.parentNode.parentNode.parentNode;
            $(".weather-forecast", c).slideDown("slow");
            $("a.collapse-forecast", c).show();
            $(this).hide();
            return false;
        });

        $("a.collapse-forecast").click(function() {
            var c = this.parentNode.parentNode.parentNode;
            $(".weather-forecast", c).slideUp("slow");
            $("a.expand-forecast", c).show();
            $(this).hide();
            return false;
        });

        if ($.cookie("temperature") == "fahrenheit")
            $("a.fahrenheit").trigger("click");

        //Handle CategoryFilterDropDown
        $('select[name=category]').bind('change', function() {
            var t = $(this);
            var qs = window.location.search;
            var newQs;
            if (qs.indexOf('cat=') != -1) { //prev cat exists, replace
                if (t.val() == 0)
                    newQs = qs.replace(/(cat=).*\d/, "");
                else
                    newQs = qs.replace(/(cat=).*\d/, 'cat=' + t.val());
            }
            else {
                if (qs != "")
                    newQs = qs + '&cat=' + t.val();
                else
                    newQs = './?cat=' + t.val();
            }
            //fix for duplicate &&
            newQs = newQs.replace('&&', '&');
            document.location = newQs;
        });
    }
}



$().ready(function() {    
	KL.init();       
});