var $j = jQuery.noConflict();

/*
 Custom Extends and PrisGuide Object (pgo) here.
 Event hooks and other stuff goes in the OnLoad function further down.
*/
;(function($) {
//    if ($.browser.msie || $.browser.opera)
        var useCorners = false;


    // Global functions


    // Update header
    updateHeader = function() {
        pgo.auth.info(function(resp) {
            if (resp.ok) {
                var reg = $("#pg-nav-register").addClass('pg-none'),
                    login = $("#pg-nav-login").addClass('pg-none'),
                    text = $("#pg-nav-text").addClass('pg-none'),
                    nav = $("#pg-nav ul");
                    
                $("#pg-login-name").text(
                    (resp.name != '') ? resp.name : resp.email);
                
                var avatar = $('#pg-login-avatar');
                if (resp.avatar) {
                    avatar.attr('src',resp.avatar);
                    avatar.removeClass('pg-none');
                }
                else avatar.addClass('pg-none');
                
                $("#pg-logout").removeClass("pg-hide");
            }
            else {
                $(".pg-reviews-guest").removeClass("pg-none");
            }
            
            // List information
            var counter = (resp.lists == 1) ? resp.listProducts : resp.lists;
            if (resp.lists == 1 && resp.email == undefined) {
		var html = 'Liste (<span class="pg-count">' +
		    resp.listProducts + '</span>)<span class="pg-bg-helper"></span>';
            }
            else {
		var html = 'Lister (<span class="pg-count">' +
                    resp.lists + '</span>)<span class="pg-bg-helper"></span>';		
            }
            // Compare list information
            var cake = $.cookie('compare');
            if (cake != null) {
                var compare = "Sammenligne (" + cake.split(',').length + ")";
                $("#pg-nav-lists li.pg-compare>a>span:first-child").text(compare);
            }
            else {
                $("#pg-nav-lists li.pg-compare>a>span:first-child").text('Sammenligne');
            }
            $("#pg-nav-lists li.pg-lists a.pg-user-list").html( html );
        });
    }
   
    
 
    socialShare = function(social, url) {
        if (typeof(url) != 'undefined') {
            // Check if URL is relative. If so, append protocol and host
            if (url.substring(0, 1) == '/')
                url = location.protocol + '//' + location.host + url;
            var encUrl = encodeURIComponent(url);
        }
        else
            var encUrl = encodeURIComponent(location.href);

        var title = encodeURIComponent(document.title);
        switch (social) {
            case 'facebook':
                var shareUrl = 'http://www.facebook.com/share.php?u=' + encUrl + '&t=' + title;
                var popup = 'toolbar=0,status=0,width=965,height=565';
                break;
            case 'nettby':
                if ($('meta').length > 0) {
                    var metas = $('meta');
                    for (var i = 0; i < metas.length; i++) {
                        if (metas[i].name == 'description')
                            var description = encodeURIComponent(metas[i].content);
                    }
                }
                var shareUrl = 'http://www.nettby.no/user/edit_link.php?name=' + title + '&url=' + encUrl + '&description=' + ((description) ? description : title);
                var popup = 'scrollbars=no,width=450,height=430';
                break;
            case 'custom':
                var shareUrl = decodeURIComponent(encUrl);
                var popup = 'toolbar=0,status=0,width=965,height=565';
                break;
            default:
                return false;
        }
        window.open(shareUrl, social, popup);
        return false;
    }
    
    //Open popupbox by clicking .pg-popup-link (supports descendants and siblings, in that order)
    $(".pg-popup-link").live("click",function(e) {
        if (e.target !== this) return true;
        e.preventDefault();
        //Search descendants of .pg-popup-link for Popup box.
        var popup = $(this).find(".pg-popup");
        //Search siblings of .pg-popup-link for Popup box.
        if (!popup.length) popup = $(this).next(".pg-popup-wrapper").find(".pg-popup");
        popup.show();
        return false;
    });

    //Default JS Links for please-login-popup
    $("#pg-review-register").live("click",function(e) {
        e.preventDefault();
        $("#pg-register-link").click();
        $(".pg-popup:visible").hide();
     });
     $("#pg-review-login").live("click",function(e) {
        e.preventDefault();
        //Document.onclick event autocloses login box. Add a slight timer to avoid login box from hiding again.
        var timer = setTimeout(function() {
         pgo.auth.show();
         clearTimeout(timer);
        }, 100);
        $(".pg-popup:visible").hide();
     });
     
    notice = function(type, msg, rootElem, pos) {
        pos = pos ? pos : 'append';
        rootElem = rootElem ? rootElem : $("body");
        var className = "pg-" + type,
            noticeEl = $("<div title='Lukk' class='pg-notice pg-rounded-corner'>" + msg + "</div>").addClass(className);
        
        // console.log(noticeEl);
        noticeEl.css({
            left: rootElem.outerWidth(),
            top: rootElem.position().top + 10,
            marginRight: "-6px",
            cursor: 'pointer'
        });

        rootElem[pos](noticeEl);
        if (useCorners)
            noticeEl.corner();

        return noticeEl.click(function() {
            $(this).remove();
        }).animate({
            opacity: 0
        }, 10000, null, function() {
            $(this).remove();
        });
    }
})(jQuery);

$j(function($) {
    // Set up context
    var header = document.getElementById("pg-header"),
        content = document.getElementById("pg-content"),
        footer = document.getElementById("pg-footer");
    
    // General overlay
    var overlay = function() {
        return $("<div class=\"pg-overlay\" />")
                    .css({
                        opacity: .7,
                        height: $("body").height()
                    }).appendTo("body");
    }
    // Append rounded corners - DISABLED
    if ($.browser.msie || $.browser.opera) {
        var useCorners = false,
            cornerTop = {
                bl: { radius: 0 },
                br: { radius: 0 }
            },
            cornerBottom = {
                tl: { radius: 0 },
                tr: { radius: 0 }
            };
        if (false) { // DISABLE CORNERS FOR NOW
            $(".pg-rounded-corner").corner();
            $(".pg-rounded-corner-top").corner(cornerTop);
            $(".pg-rounded-corner-bottom").corner(cornerBottom);
        }
    }


    $("div.pg-overlay-teaser", content).each(function() {
        var that = $(this),
            width = that.outerWidth(),
            height = that.outerHeight(),
            elem = $("<div class=\"pg-disabled\" />").css({
                height: height + 4,
                width: width,
                opacity: .7
            }).appendTo(that);
    });

    //Init history fix for ajax calls
    $(document).ready(function() {
	$.history.init(callback);
	$("a[rel='history']").click(function(){
	    $.history.load(this.href.replace(/^.*#/, ''));
	    return false;
	});
    });
    
    function callback(hash) {
	if(hash !== 'productImageBig') {
	    $('.pg-overlay').trigger('click');
	}
	// do stuff that loads page content based on hash variable
    }

    var pgSlideShow = function(el) {
      
        var res = $("ol.pg-search-results", content),
            li = res.find("li:first"),
            title = li.find("h2").text(),
            img = li.find("img"),
	    src = li.find("img").attr("src");
	    
            li.data("pgNav", {
                next: li.next("li"),
                prev: li.prev("li")
            });
        
	$.blockUI.defaults.css.cursor = null;
        var block = $.blockUI({
            message: "<div class=\"pg-product\"><h1>" + title + "</h1>" +
                    "<img src=\"" + src + "\" alt=\"" + title+ "\" /></div>"
        });
	
        var next = $("<div class=\"pg-slideshow-nav pg-slideshow-next\">Neste</div>")
                        .click(function(e) {
                            li = li.data("pgNav").next,
                            title = li.find("h2").text(),
                            src = li.find("img").attr("src");
                            li.data("pgNav", { 
                                next: li.next("li"),
                                prev: li.prev("li")
                            });
			    
                            var html = "<h1>" + title + "</h1>" +
                            "<img src=\"" + src + "\" alt=\"" + title+ "\" />";
                            block.find("div.pg-product").html(html);
			    
                        }).appendTo(block);
			
        var prev = $("<div class=\"pg-slideshow-nav pg-slideshow-prev\">Forrige</div>")
                        .click(function(e) {
                            li = li.data("pgNav").prev,
                            title = li.find("h2").text(),
                            src = li.find("img").attr("src");
                            li.data("pgNav", { 
                                next: li.next("li"),
                                prev: li.prev("li")
                            });

                            var html = "<h1>" + title + "</h1>" +
                            "<img src=\"" + src + "\" alt=\"" + title+ "\" />";
                            block.find("div.pg-product").html(html);
                        }).appendTo(block);

    }
    
    if ($.cookie('pgView')) {
        var pgView = $.cookie('pgView');
    }
    function applyPgView(e) {
        var views = [
                'matrix',
                'list'
            ],
            res = $("#pg-search-result-list", content), 
            optionsList = $("#pg-view-options", content);
        if (e) {
            e.preventDefault();
            var target = $(e.target).filter("a"),
                hash = target.attr('href').replace(/^.*#/, ''); 
            
            optionsList.find("a.pg-selected")
                      .removeClass('pg-selected');
            target.addClass('pg-selected');
            
            pgView = hash.replace('pg-view-', '');
            $.cookie('pgView', pgView);
        }
        if (pgView && !res.hasClass("pg-view-" + pgView)) {
            var width, height,
                viewContainer = res.find("div.pg-view-container");
            optionsList.find("a.pg-view-options-" + pgView, content)
                       .addClass("pg-selected");
            for (var i = 0; i < views.length; i++) {
                res.removeClass("pg-view-" + views[i]);
            }
            res.addClass("pg-view-" + pgView);

            if (pgView == "matrix") {
                width = 180;
                height = 130;
                viewContainer.addClass("pg-rounded-corner");
                if (useCorners) 
                    viewContainer.corner();
            }
            else {
                width = 99;
                height = 66;
            }
            var imgs = viewContainer.find("div.pg-view-image img"),
                imageUrl;
            for (var i = 0; i < imgs.length; i++) {
                imageUrl = $.imageParseImageUrl(imgs[i].src).imageGetSizeUrl(width, height);
                imgs[i].src = imageUrl;
            }
        }
    }
     
    $("#pg-view-options", content).live('click', applyPgView);
    
    // Add livesearch
    $("#pg-q", header).livesearch();

    $("a.pg-social-share", content).click(function(e) {
        e.preventDefault();
        var el = $(this).next("ul.pg-social-share")
                .toggleClass("pg-hide");
        el.addClass("pg-rounded-corner")
        if (useCorners)
            el.corner();
    });
    
    //Moving guestList to permanent list: Show "please wait" box and reload page.
    $('#pg-lists-move-guestlist').ajaxForm({
        beforeSubmit: function() {
            $(".pg-list-move-popup").show();
        },
        success: function() {
            window.location.assign("/profil/lister");
        }
    });



    /**
     * Product page
     *
     */
    if ($("#pg-product", content).length > 0) {
        var productPage = $("#pg-product", content);
        if (useCorners)
            productPage.find(".pg-nav li:not(.pg-selected) a").corner();
        else
            productPage.find(".pg-nav li:not(.pg-selected) a").addClass("pg-rounded-corner");

        // Load product images
        $.getJSON("?module=PGProductImages&service=loadImages", function(data) {
            var imgs = [], start = 0, stop = 7, lastCachePoint = 0;
            for (var i in data) {
                imgs.push(data[i]);
            }

            var preload = function(imgs, key, start, stop) {
                for (var i = start; i <= stop; i++) {
                    if (imgs[i] != undefined && !$._isCached(imgs[i][key])) {
                        $.imagePreload(imgs[i][key]);
                        $._cache(imgs[i][key], true);
                    }
                }
            }
            
            var imageContainer = $("#pg-product-images", productPage),
                img = imageContainer.find("#pg-product-image-container img"),
                nav = imageContainer.find("#pg-product-images-nav a"),
                thumbnails = imageContainer.find("#pg-product-images-list"),
                size = 'normal',
                c = new $.Carousel(imgs);

            preload(imgs, size, start, stop); 

            var navHandler = function(state) {
                var src = c[state]()[size];
                // Change image
                img.attr('src', src);
                imageContainer.find("span.pg-current").text(c.current + 1);
                
                thumbnails.find("a.pg-selected").removeClass("pg-selected")
                          .end().find("#pg-product-image-" + c.getCurrent().id)
                                .addClass("pg-selected");

                if (c.current % 5 == 0) {
                    if (state == 'next') {
                        stop = c.current + 7;
                        start = c.current + 2;
                    }
                    else {
                        stop = c.current - 2;
                        start = c.current - 7;
                        if (start < 0)
                            start = c.data.length - start;
                    }
                    preload(imgs, size, start, stop);
                }

            };
            var thumbs = thumbnails.find("img").lazyload();
            thumbnails.click(function(e) {
                e.preventDefault();
                var target = $(e.target);
                // Find closest anchor
                if (!target.is("a")) 
                    target = target.closest("a");

                if (target.is("a")) {
                    var id = target.attr('id').replace("pg-product-image-", "");
                    selectImageById(id);
                }
            });

            var selectImageById = function(id) {
                thumbnails.find("a.pg-selected").removeClass("pg-selected");
                var elem = thumbnails.find("#pg-product-image-" + id).addClass("pg-selected");
                
                for (var i = 0; i < imgs.length; i++) {
                    if (imgs[i].id == id) {
                        c.current = i;
                        break;
                    }
                }
                img.attr('src', elem.attr('href'));
            };
	    
	    img.attr('title', 'Klikk for å vise neste bilde');
	    img.css('cursor','pointer');
	    img.click(function(){
		navHandler('next');
	    });
	    
            nav.click(function(e) {
                e.preventDefault();
                var that = $(this),
                state = that.attr('rel');
                navHandler(state);
            });
            
            $(document).keydown(function(e) {
                var state;
                if (e.keyCode == 37)
                    state = "prev";
                else if (e.keyCode == 39)
                    state = "next";

                if (state)
                    navHandler(state);
            });

            imageContainer.find("#pg-zoom")
                        .click(function(e) {
                            //e.preventDefault();
                            var o = overlay(),
                                zoomNode = $(this).hide(),
                                oldHeight = imageContainer.height(),
                                oldWidth = imageContainer.width();
                            img.hide();
                            size = 'large';
                            preload(imgs, size, start, stop);
			    o.click(function(){
				$(close).click();
			    });
                            var close = $("<a class=\"pg-absolute\" href=\"#\">Lukk</a>")
                                .css({
                                    top: 0,
                                    right: 0
                                })
                                .click(function(e) {
                                    e.preventDefault();
                                    $(this).remove();
                                    o.remove();
                                    size = 'normal';

                                    img.hide();
                                    imageContainer
                                        .animate({
                                            width: oldWidth,
                                            height: oldHeight
                                        }, 500, null, function() {
                                            imageContainer.removeClass("pg-slideshow");
                                            img.attr('src', c.getCurrent()[size])
                                                .load(function() {
                                                    img.show();
                                                });
                                            imageContainer.find("#pg-product-images-list")
                                                          .addClass("pg-none");
                                            imageContainer.find("a.pg-lists-add").addClass("pg-none");
                                        });
                                    zoomNode.show();
                                }).appendTo(imageContainer);
                            $(document)
                                .keyup(function(e) {
                                    if (e.keyCode == 27)
                                        close.click();
                                });
                            imageContainer.find("#pg-product-images-list")
                                          .find("img").lazyload(true)
                                          .end()
                                          .removeClass("pg-none");
                            imageContainer.find("a.pg-lists-add").removeClass("pg-none");
                            img.attr('src', c.getCurrent()[size])
                                .load(function() {
                                    img.show();
                                });
                            imageContainer
                                .addClass("pg-slideshow")
                                .css('height', 'auto')
                                .animate({
                                    width: 952
                                }, 500);
                        });
            if (document.location.pathname.indexOf("&view=images") != -1) {
                var paramObj = $.deparam(document.location.pathname);
                if ('imageId' in paramObj) {
                    var id = paramObj.imageId;
                    imageContainer.find("#pg-zoom").click();
                    selectImageById(id);
                }
            }
        });

        $("#pg-product-info div.pg-details-normal")
            .bind("mouseover mouseout", function(e) {
                var t = $(e.target)
                    et = e.type,
                    state = {
                        'cl': 'addClass',
                        'tr': 'next'
                    };
                if (t.is('dd, dt')) {
                    if (et == 'mouseout')
                        state.cl = 'removeClass';
                    if (t.is('dd'))
                        state.tr = 'prev';
                    var andSelf = t[state.tr]().andSelf();
                    andSelf[state.cl]('pg-hover');
                }
            });


        var priceFilter = $("#pg-price-filter", productPage)
                .bind($.browser.msie ? "click" : "change", function (ev) {
            if ($(ev.target).is("label, input"))
                $("#pg-price-filter", productPage).submit(); 
        });

        priceFilter.ajaxForm({
            url:"?module=PGPrices&service=getPriceTemplate", 
            dataType: "json",
            beforeSend: function() {
                $(".pg-prices", productPage).before("<div class=\"pg-loading\"></div>");
            },
            success: function(response) {
                productPage
                    .find("div.pg-loading").remove()
                    .end()
                    .find(".pg-prices-holder")
                    .replaceWith(response.html)
            }
        });
        // Order price alert
        $("#pg-price-alert form button", productPage).click(function(e) {
            e.preventDefault();
            // Clear out previous errors
            var button = $(this), 
                form = button.parents('form'),
                data = {'module':'PGPriceAlert','service':'add'};
            $("span.error", form).remove();
            $(":input", form).each(function(key, item) {
                if ($(this).is(":checkbox"))
                    data[item.name] = (item.checked) ? 1 : 0;
                else
                    data[item.name] = $(this).val();
            });
            // Error handling
            var errors = false;
            if (!data.email || data.email == '') {
                errors = true;
                notice('error', "Må spesifisere lager eller prisvarsel.", $("#pg-alert-email"), 'before');
            }
            if (!data.stock && (!data.cheaper && !data.price && data.price != '')) {
                errors = true;
                notice('error', "Må spesifisere lager eller prisvarsel.", $("input[name=price]",form), 'before');
            }
            if (!errors) {
                $.getJSON('/service', data, function(resp) {
                    // console.log(resp);
                    var msg = "Prisvarsling registert";
                    notice('success', msg, button, 'after')
                            .css({
                                marginLeft: 20
                            });
                });
            }
        });
    }
    //List events
    
    // Change privacy state of product list
    $("input#pg-private, input#pg-public", content).click(function(event) {
        if (pgo.auth.needAuth(event)) {
            event.preventDefault();
            return false;
        }
        var node = $(this), service;
        if (node.attr('id') == 'pg-public')
            service = 'public';
        else
            service = 'private';
        var listId = node.parents('form').find('input[name=listId]').val();
        $.getJSON('/service',
            {module: 'PGLists', service: service, listId: listId},
            function(resp) {
                // Set selected
                if (!node.hasClass('pg-true')) {
                    node.next('label').addClass('pg-true');
                    node.parent().siblings('li').find('label').removeClass('pg-true');
                }
            }
        );
    });
    
    // Change title of list
    $("#pg-list-edit-title, div.pg-view-box h2", content).click(function(event) {
        if (pgo.auth.needAuth(event)) {
            event.preventDefault();
            return;
        }
        event.preventDefault();
        var self = $(this), container = self.parent(), h2, a;
        // Find h2 and change into input
        if (self.is("a")) {
            h2 = self.prev('h2');
            a = self;
        }
        else {
            h2 = self;
            a = self.next('a');
        }
        var name = h2.text();
        h2.hide();
        var listId = a.attr('href').replace('#list=','');
        var changer = $('<input id="list_'+listId+'" type="text" name="list_title" value="'+name+'" />')
                .prependTo(container);
        changer.focus();
        changer.blur(function(event) {
            var that = $(this);
            name = that.val();
            listId = that.attr('id').replace('list_',''),
            $.getJSON('/service', {module: 'PGLists',
                    service: 'changeName',
                    listId: listId,
                    name: name
                }, 
                function(resp) {
                    // Set new name in h2
                    if (resp.messages[0]) name = resp.messages[0];
                    else {
                        pgo.popup.html('Det oppstod en feil ved endring av navnet på listen.');
                        pgo.popup.show.notice($('#pg-list-edit-title'));
                    }
                    h2.text(name);
                });
            changer.remove();
            h2.show();
        });
    });        
    // Create new list
    $("#pg-lists-add-new", content).click(function(event) {
        event.preventDefault();
        var that = $(this),
            link = that.hide(),
            container = that.parent(),
            nodes = $('<input type="text" name="title" value="Huskeliste" />'+
            '<input type="submit" value="Lagre" />').appendTo(container);
        $(nodes[1]).click(function(event) {
            event.preventDefault();
            var val = $(this).prev('input').val();
            $.getJSON('/service',
                {module: 'PGLists', service: 'addList', title: val},
                function(resp) {
                    // Create a new li node by copying an existing one
                    // TODO, what happens if none is found?
                    link.show();
                    nodes.remove();
                    var ul = link.parent().prev('ul');
                    var node = $("#list_item_template",content).clone();
                    node.attr('id', "item_" + resp.id);
                    node.find('input[type=checkbox]').attr("name", "item[" + resp.id + "]");
                    node.find('h3').find('a').attr('href', '/profil/lister/'+resp.id).text(val)
                    node.find('p.pg-list-total-price').text('0,-');
                    node.find('p.pg-desc').text('');
                    node.find('ul').remove();
                    node.appendTo(ul).hide();

                    node.show('blind', {}, 500);
                    // Finally update users cache
                    $.getJSON('/service?module=PGAuth&service=updateCache');
                }
            );
        });
    });
    //End of List Events

    // ShowAll for PriceListsSearch
    $("#pg-pricelist-showall", content).click(function(e) {
        e.preventDefault();
        $("#pg-search-pricelists", content).load("/service?module=PGSearchPricelists&showall=1&service=search&" + document.location.search.substr(1));
    });

     // Show more expert reviews
     $("#pg-more-expert-reviews", content).click(function(e) {
        e.preventDefault();
        var that = $(this);
        var data = that.attr('href').replace('#','').split(',');
        var offset = data[1],
            productId = data[0],
            count = 20;
	var getParameters = {
	    'module': 'PGArticleList',
	    'service': 'articles',
	    'type': 'product',
	    'id': productId,
	    'offset': offset,
	    'count': count * 2
	};

	//Show loading indicator
        var loading = $("<div class=\"pg-loading\" />");
	that.before(loading);

        //Get new set of reviews
	$.get('/service', getParameters, function(resp) {
	    var resultCount = Math.max($(resp).siblings('li').length - count, 0);

	    //If there are more review update the button to say so, otherwise remove it
	    if(resultCount > 0) {
		that.attr('href', '#' + productId + ',' + (Number(offset) + Number(count)));		
	        that.html('Vis ' + resultCount + ' flere ekspertomtaler<span class="pg-button-left"><!----></span><span class="pg-button-right"><!----></span>');
	    } else {
		that.remove();
	    }
	    
	    loading.remove();

	    var t = $(resp).filter('li').slice(0, count).appendTo($("#pg-articles-list", content));

        }); //end 1st get
    }); 

    // Send error suggestion
    $("a.pg-suggest", content).click(function(e) {
        e.preventDefault();
        var addSuggestionDialog;
        // Render form
        $.getJSON('/service', {
                module: 'PGSuggestion', 
                service:'form', 
                suggestion:'product'
            }, 
            function(resp) {
                addSuggestionDialog = $(resp.html).dialog({
                    modal: true,
                    width: 500,
                    resizable: false,
                    title: resp.title
                });
                if (useCorners)
                    $(".pg-rounded-corner", addSuggestionDialog).corner();
                // Attach handler
                var data = {
                    'module': 'PGSuggestion',
                    'service': 'add'
                };
                $("button[name=submit]", addSuggestionDialog).click(function(e) {
                    e.preventDefault();
                    $(":input", addSuggestionDialog).each(function(key, item) {
                        data[item.name] = $(this).val();
                    });
                    $.getJSON('/service', data, function(response) {
                        if (response.ok) {
                            // We've posted our suggestion
                            addSuggestionDialog.dialog('destroy');
                            addSuggestionDialog = undefined;
                            // console.log('Suggestion sent:');
                            notice('success', "Takk for tipset", $("a.pg-suggest"), 'before');
                        }
                        else {
                            notice('error', "Kunne ikke lagre tips", $(this), 'after');
                            // console.log('Failed to add suggestion:');
                        }
                        // console.log(data);
                    });
                });
            }
        );
    });
    

    // Stars
    var selectedStar;
    function attachPGStarsEvt(context) {
        $("ul.pg-stars a", context ? context : false)
            .click(function(e) {
                e.preventDefault();
                var that = $(this);
                that.parents(".pg-stars")
                    .find(".pg-selected")
                    .removeClass("pg-selected");
                selectedStar = that.addClass("pg-selected");
            })
            .parents(".pg-stars")
                .hover(
                    function() {
                        $(this).find(".pg-selected").removeClass("pg-selected");
                    },
                    function() {
                        selectedStar.addClass("pg-selected");
                    }
                );
    }
    
    function hashChangeCompareCb(qs) {
        // Build pid array
        var url = '/service?module=PGProductCompare&service=compare';
        for (var i in qs) {
            if (qs[i].name == 'pids[]')
                url = url + '&ids[]=' + qs[i].value;
        }
        compareProducts(url);
    }
    function hashChangeCb(e, onload) {
        if ($.param.fragment() != '') {
            var qs = $.unserialize(decodeURIComponent($.param.fragment())), elem, name, val;
            if (qs.length > 0) {
                if (qs[0].name == 'sammenligne') {
                    hashChangeCompareCb(qs);
                }
                else {
                    if (filterForm) {
                        for (var i = 0; i < qs.length; i++) {
                            name = qs[i].name;
                        val = qs[i].value;
                            elem = filterForm.find('input[name="' + name + '"]');
                            if (elem.is(":checkbox, :radio")) {
                                elem.filter('input[value="' + val + '"]')
                                    .attr('checked', true);
                            }
                            else {
                                elem.val(val);
                            }
                        }
                        filterForm.submit();
                    }
                }
            }
        }
    };
    var searchReplace = $(document.getElementById("pg-search-replace"));
    if (document.getElementById("pg-filter-form")) var filterForm = $(document.getElementById("pg-filter-form"));

    // Set up search ordering links
    function searchOrdering(e) {
        e.preventDefault();
        var t = $(e.target);
        // Update filter form
        if (t.is("a")) {
            var sort = t.attr('href').match(/sort=([a-z]+)/)[1];
            filterForm.find("input[name=sort]").val(sort);
            filterForm.submit();
        }
    }
    function setUpPagination() {
       function paginationCb(e) {
            e.preventDefault();
            var el = $(e.target);
            if (!el.is("a")) {
                el = el.closest("a");
            }
            if (el.is("a")) {
                var n = el.attr('href').match(/n=([0-9]+)/)[1];
                searchReplace.scrollTo(0);

                filterForm.find("input[name=n]").val(n);
                filterForm.submit();
            }
        }
        $("ol.pg-paginator", searchReplace).click(paginationCb);

    }
    function searchEvents(e) {
        var self = $(e.target);
        if (self.is("span, strong")) {
            self = self.closest("a");
        }
        if (self.hasClass("pg-add-compare")) {
            e.preventDefault();
            var pid = self.attr('href').replace('#','');
            self.find('span').html('X');
            self.parent('div').parent('div.pg-view-container').parent('li').addClass('pg-selected');
            self.parent('div').parent('div.pg-view-container').addClass('pg-selected');
            addToCompare(pid);
            pgo.list.product.visualAdd(self, 'Lagt i sammenligning', '#pg-nav-lists li.pg-compare');
        }
    }
    if (searchReplace.length > 0)
        setUpPagination();

    function setUpFilterForm() {
        if ($.browser.msie && $.browser.version == "7.0") {
            filterForm.click(function(e) {
                if ($(e.target).is("button")) {
                    filterForm.submit();
                }
            });
        }
        filterForm.ajaxForm({
            url: '?module=PGSearch&service=search',
            beforeSend: function(data) {
                // Split price into max/min
                searchReplace.append(
                $("<div class=\"pg-loading\" />")
                    .css({
                        left: "77%"
                    })
                ).css('position', 'relative');
                $(window).unbind('hashchange');
                document.location.hash = filterForm.serialize();
            },
            beforeSubmit: function(data) {
                for (var i in data) {
                    var name = data[i].name,
                        value = data[i].value,
			pricelistHits = $('#pg-pricelist-hit-count').attr('value');
                    if (name == 'price') {
                        var price = data[i].value.split('-');
                        data.push({'name': 'price_min', 'value': price[0]});
                        data.push({'name': 'price_max', 'value': price[1]});
                        data.push({'name': 'price_group', 'value': price[2]});
			data.push({'name': 'pricelistHits', 'value': pricelistHits});
                    }
                }
            },
            success: function (response) {
                // Reload filters
                if (response.length < 100) {
                    // Netsprint died :(
                    searchReplace.find("div.pg-loading").replaceWith(response).css('position', 'relative');
                }
                else {
                searchReplace.empty();
                searchReplace[0].innerHTML = response;

                if (useCorners)
                    $("div.pg-rounded-corner, a.pg-rounded-corner", searchReplace).corner();

                // Set up event handlers
                setUpPagination();
                $(window).bind('hashchange', hashChangeCb);
            }
        }
    });
    }
    searchReplace.find("#pg-search-result-list").live('click', searchEvents);
    
 
    if ($.param.fragment() != '') {
        $(window).bind("hashchange", hashChangeCb);
        $(window).trigger("hashchange", [true]);
    }

    // Search sorting
    $("#pg-search-ordering", searchReplace).live('click', searchOrdering);
    
    function filterEvents(e) {
        var self = $(e.target);
        if (self.is("h4")) {
            self.toggleClass("pg-selected")
                .next("div.pg-filter-box")
                .toggleClass("pg-hide");
        }
        else if (self.is("a.pg-text-toggle")) {
            e.preventDefault();
            var elems = self.closest("ul").children("li").not(".pg-no-hide");
            if (self.data("pg-toggled")) {
                self.text("Vis alle ...");
                self.data("pg-toggled", false);
                elems.filter(".pg-show")
                     .removeClass("pg-show")
                     .addClass("pg-hide");
            }
            else {
                self.text("Skjul alle ...");
                self.data("pg-toggled", true);
                elems.filter(".pg-hide")
                     .addClass("pg-show")
                     .removeClass("pg-hide");
            }
        }
    }

    if (filterForm) {
        setUpFilterForm();
        filterForm.bind("click", filterEvents);
    }
    
    // Normal sliders
    $(".pg-slider", searchReplace).each(function() {
        var that = $(this), min, max, id;
        min = that.find(".pg-slider-value-min").val();
        max = that.find(".pg-slider-value-max").val();
        id = that.find(".pg-slider-value-min").attr("id").replace("pg-detail-min-", "");
        that.slider({
            range: "min",
            min: min,
            max: max,
            slide: function(e, ui) {
                that.parent().find(".pg-slider-visible-value").text(ui.value);
            },
            change: function(e, ui) {
                var value;
                if (that.hasClass("pg-slider-exact"))
                    value = id + "(" + ui.value + ")";
                else if (that.hasClass("pg-slider-min"))
                    value = id + "(" + min + "," + ui.value + ")";
                else
                    value = id + "(" + ui.value + "," +  max + ")";
                that.find("input[name=detailId]").val(value);
                filterForm.change();
            }
        });
    });

    // Thumbs up to a review
    $("a.pg-is-useful", content).click(function(e) {
        e.preventDefault();
        var that = $(this);
        var id = that.attr('href').replace('#thumbs_up_', '');
        var url = '/service?module=PGReview&service=thumb&id=' + id;
        $.getJSON(url, function(resp) {
            if (resp.ok) {
                that.animate({
                    backgroundColor: 'grey'
                }, 750);
            }
            else {
                // Display some error message
                // console.log(resp.messages);
            }
        });
    });   
    
    if ($("input.pg-datepicker").length > 0) {
        $("input.pg-datepicker").datepicker({
            dateFormat: 'yy-mm-dd'});
    }
    
    // Shop search
    function setUpShops() {
        var form = $("#pg-shop-filters form", content),
            container = $("#pg-shop-list", content);
        form.ajaxForm({
            success: function(resp) {
                container.html(resp);
            }
        });
        form.change(function(e) {
            $(this).submit();
            return false;
        });
        var ratings = form.find('.pg-shop-rating-filter').find('a');
        ratings.click(function(e) {
            e.preventDefault();
            var rat = $(this).attr('href').split('rating=')[1];
            if (rat == undefined)
                rat = 0;
            form.find('input[name=rating]').val(rat);
            form.submit();
        });
    }
    setUpShops();

    /**
    * EU model info-popup for product prices
    */
    $('#pg-eu-model').dialog({
	autoOpen: false,
	title: $('#pg-eu-model').find('h2'),
	minWidth: 530,
	width: 530,
	minHeight: 465,
	height: 465,
	modal: true,
	draggable: false
    });
    
    $('#pg-eu-model').removeClass('pg-hide');
    
    $("a.pg-eu-model-link").click(function(e) {
	e.preventDefault();
	$('#pg-eu-model').dialog('open');
	
	// Close overlay on click
	$('div.ui-widget-overlay').click(function() {
	    $('#pg-eu-model').dialog('close');
	});

    });

    /**
     * Compare products
     *
     */
    function compareProducts(url) {
        var hidden = [];
        $.ajax({
            url: url,
            dataType: 'html',
            success: function(data) {
                var context = $(data);
                var elem = $("body").overlay(context).corner();
                var headerHeight = $("thead", context).height(),
                    overlayHeight = $(window).height() - 50,
                    width = context.width(),
                    elements = $._cache('compare')['count'];
		
		context.parent().css('overflow', 'hidden');
		$('body').css( 'overflow', 'hidden' );

                var leftPos = "-" + (elem.width() / 2) + "px";
		var topPos = ($(window).scrollTop() + 20) + 'px';

		elem.css({
		  'marginLeft': leftPos,
		  'top': topPos
		});

                // How many products can we show?
                for (var i = 6; i <= elements+1; i++) {
                    $("#pg-compare-products-table tr>:nth-child("+i+")", context).
                        css('display','none');
                }

		if ($.browser.msie && $.browser.version.substr(0,1)<=7) {
		    scrollElement = "div.pg-scrolltable-container";
		} else {
		    scrollElement = "tbody";
		}
		
		headerHeight = Math.max(headerHeight, 127);
		
                context.find(scrollElement).eq(0).css({
                        'height':(overlayHeight - headerHeight - 80) + "px"
                });
		
		$("#pg-compare a.pg-lists-add").click(function(e) {
		    e.preventDefault();
		    that = $(this);
		    var ids = that.attr('href').match(/([0-9,]+)/)[1];
		    console.log(ids );
		    
		    ids = ids.split(',');
		    console.log(ids);
		
		    $(ids).each(function(i) {
			pgo.list.product.add(e,ids[i],listId); //listid!?
		    });
		    
		    
		});
        
		
                // Update what products show in compare
                function comparePaginate(start) {
                    var start = Number(start);
                    var end = Number(start + 4);
                    // Hide current, show requested
                    $("#pg-compare-pagination span.pg-selected").removeClass("pg-selected");
                    for (var i = 0; i < elements; i++) {
                        if (i >= start && i < end) {
                            var display = 'table-cell';
                            // Set span as selected
                            $("#pg-compare-pagination span.pg-"+(i)).addClass('pg-selected');
                        }
                        else
                            var display = 'none';
                        var current = Number(i) + 2;
                        //$("#pg-compare-products-table tr>:nth-child("+current+")", context).css('display',display);
                    }
                    // Update next/prev handlers
                    var prev = $("#pg-compare-pagination a.pg-prev").attr('href','#');
                    var next = $("#pg-compare-pagination a.pg-next").attr('href','#');
                    if (start > 0)
                        prev.attr('href', '#'+(start-1));
                    if (end < elements)
                        next.attr('href', '#'+(start+1));
                }
                // Event handlers
                $("a.pg-remove-compare", context).click(function(e) {
                    e.preventDefault();
                    var that = $(this);
                    var pid = that.attr('id').replace('pg-c-','');
                    // Find offset in tr)
                    var c = Number(that.attr('href').replace('#',''));
                    var k = that.parents('th').prevAll('th').length + 1;
                    // Remove from dom
                    $("table tr>:nth-child("+k+")", context).remove();
                    $("#pg-compare-pagination span.pg-"+c, context).remove();
                    // Remove from cookie
                    removeFromCompare(pid);
                    comparePaginate(0);
                });
                $("#pg-compare-pagination a",context).click(function(e) {
                    e.preventDefault();
                    // Remove all selected paginations
                    var href = $(this).attr('href');
                    if (href != '#') {
                        var start = Number(href.replace('#',''));
                        comparePaginate(start);
                    }
                });
                $("a#pg-show-unequal", context).click(function(e) {
                    e.preventDefault();
                    $("tbody tr.pg-detail-equal", context).toggleClass("pg-hide");
                    $("tbody tr", context)
                        .removeClass("pg-odd")
                        .removeClass("pg-even")
                        .not(".pg-hide, .pg-detail-section")
                            .filter(":odd").addClass("pg-odd")
                        .end()
                            .filter(":even").addClass("pg-even");
                    
		    var element = $(this);
                    element.toggleClass('pg-selected');
		    element.html().match( /vis bare ulike produktdetaljer/i ) ?
		      element.html( 'vis alle egenskaper' ) :
		      element.html( 'vis bare ulike produktdetaljer' );
                });
                context.find("tbody")
                        .click(function(e) {
                            $(e.target).filter("tr:not(.pg-detail-section) td").closest("tr").toggleClass("pg-selected");
                        });
            }
        });
    }
    $("a.pg-compare", header).click(function(e) {
        e.preventDefault();
        //compareProducts("/service?module=PGProductCompare&service=compare&ids[]=111269&ids[]=111297");
        // Find product ids in cookie
        var pids = $.cookie('compare');
        if (pids != null) {
            pids = pids.split(',');
            var url = "/service?module=PGProductCompare&service=compare";
            for (var i in pids) {
                url = url + "&ids[]=" + pids[i];
            }
            compareProducts(url);
        }
    });
    $("div.pg-list-compare button.pg-compare", content).click(function(e) {
        e.preventDefault();
        var pids = $(this).attr('id');
        var pid = pids.replace(',', '&ids[]=', 'g');
        compareProducts("/service?module=PGProductCompare&service=compare&ids[]="+pid);
    });
    // Add to compare list
    function addToCompare(pid) {
        // Append in cookie
        pid = String(pid);
        var cake = $.cookie('compare');
        if (cake == null)
            cake = [];
        else
            cake = cake.split(',');
        if ($.inArray(pid, cake) == -1) {
            cake.push(pid);
            $.cookie('compare', cake, {path:'/'});
            // Update header
            updateHeader();
        }
    }
    function removeFromCompare(pid) {
        // Append in cookie
        var pid = String(pid);
        var cake = $.cookie('compare');
        if (cake != null) {
            cake = cake.split(',');
            var newCake = [];
  
//            if (cake.indexOf(pid) != -1) {
	      if($.inArray(pid, cake) != -1) {
		for (i in cake) {
                    if (cake[i] != pid)
                        newCake.push(cake[i]);
                }
                if (newCake.length == 0)
                    newCake = null;
                $.cookie('compare', newCake, {path:'/'});
                // Update header
                updateHeader();
            }
        }
    }
    function inCompare(pid) {
        // Append in cookie
        var pid = String(pid);
        var cake = $.cookie('compare');
        if (cake != null) {
            cake = cake.split(',');
            if ($.inArray(pid, cake))
                return true;
        }
        return false;
    }
    var productAddCompare = $("#pg-product a.pg-add-compare",content);
    if (productAddCompare.length > 0) {
        // Is selected all ready?
        if (inCompare($._cache('productId'))) {
            productAddCompare.addClass('pg-selected');
        }
        productAddCompare.click(function(e) {
            // Get product id from cache
            e.preventDefault();
            var self = $(this);
            if (!self.hasClass('pg-selected')) {
                pgo.list.product.visualAdd(self, 'Lagt i sammenligning', '#pg-nav-lists li.pg-compare');
                // Set selected
                self.addClass('pg-selected');
                addToCompare($._cache('productId'));
            }
        });
    }
    
});
