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 (0)');
            }
            $("#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;
    }
    
    //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();
        });

    }
})(jQuery);

$j(function($) {
    // Set up context
    var header = document.getElementById("pg-header"),
        content = document.getElementById("pg-content"),
        footer = document.getElementById("pg-footer");

    $("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);
    });
    
    
    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 = $(this),
                hash = target.attr('href'); 
            if (hash) hash = hash.replace(/^.*#/, '');
            else hash = 'list';
            
            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");
                res.removeClass("pg-border-gray");
                res.removeClass('pg-rounded-corner');
            }
            else {
                res.addClass('pg-rounded-corner');
                res.addClass("pg-border-gray");
                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;
                imgs[i].style.height = height + "px";
            }
        }
    }
     
    $("#pg-view-options").delegate('a', 'click', applyPgView);
    
    // Add livesearch
    $("#pg-q", header).livesearch();

    //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");
        }
    });



    //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=PGSearch&showall=1&service=searchPricelist&" + 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
                });
                // 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");
                    }
                );
    }
    
    var searchReplace = $(document.getElementById("pg-search-replace"));
    if (document.getElementById("pg-filter-form")) var filterForm = $(document.getElementById("pg-filter-form"));

    
    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();

    
    searchReplace.find("#pg-search-result-list").live('click', searchEvents);

    
    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) {
        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), elem = $("body").overlay(context),
                    headerHeight = $("thead", context).height(),
                    overlayHeight = pgo.win.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 = (pgo.win.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();
                    var that = $(this), ids = that.attr('href').match(/([0-9,]+)/)[1];
                    
                    ids = ids.split(',');
                
                    $(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));
                }
                function removeCompareElement(elem) {
                    var that = $(elem);
                    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);
                }
                // Event handlers
                $("a.pg-remove-compare", context).click(function(e) {
                    e.preventDefault();
                    removeCompareElement(e.target);
                });
                $("a.pg-remove-compare-all", context).click(function (e) {
                    e.preventDefault();
                    $("#pg-compare-products-table a.pg-remove-compare").each(function (i, e) {
                        removeCompareElement(e);
                    });
                    $("#pg-search-result-list .pg-selected").removeClass("pg-selected");
                    $("body").overlay();
                });
                $("#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);
        } else {
	    notice('error', 'Du har ikke lagt til noen produkter for sammenligning', $('#pg-compare-notice'), 'after');
	    //alert('NEINEINEI!!! Du kan ikke se sammenligning av produkter uten å ha lagt til noen produkter....!! GAAAH');
	}
    });
    $("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?
        
        productAddCompare.click(function(e) {
            // Get product id from cache

            e.preventDefault();
	    var self = $(e.target);
	    if (self.is("span, strong")) {
		self = self.closest("a");
	    }            
	    addToCompare($._cache('productId'));
            pgo.list.product.visualAdd(self, 'Lagt i sammenligning', '#pg-nav-lists li.pg-compare');

        });
    }
    
});
