
;(function($) {
    /* ########################
    pgo = PrisGuide Object
    ########################*/
    try {
        pgo = {
            _length: function(obj) {
                //Get length of associative arrays 
                if (typeof(obj) == "undefined") return null;
                if (typeof(obj.length) != "undefined") return obj.length;
                var count = 0;
                for (var x in obj) {
                    count ++;
                }
                return count;
            },
            pglog: function(msg) {
                if ($j.browser.msie) {
                    //alert(msg);
                }
                else {
                    try {
                        console.log(msg);
                    }
                    catch(err) {}
                }
            },
            pgstack: function() {
                try{please.fail+=0}
                catch(err) {
                    try {
                        console.log(err.stack);
                    }
                    catch(err) {}
                    return err;
                }
                
            },
            win: $(window),
            doc: $(document),
            productId: null,
            shopId: null,
            safe_url: null, //Remove modifications on url by auth tek (?errors=wrong password) and other stuff. JS should use this only. Not location.href
            selectedStar: 0,
            overlay: function() {
                return $("<div class=\"pg-overlay\" />")
                            .css({
                                opacity: .7,
                                height: $("body").height()
                            }).appendTo("body");
            },

            
            //Set up stars event.
            attachPGStarsEvt: function (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");
                        pgo.selectedStar = that.addClass("pg-selected");
                    })
                    .parents(".pg-stars")
                        .hover(
                            function() {
                                $(this).find(".pg-selected").removeClass("pg-selected");
                            },
                            function() {
                                if (pgo.selectedStar.length)
                                    pgo.selectedStar.addClass("pg-selected");
                            }
                        );
            },
            product: {
                onload: function() {
                    /**
                     * Product page
                     *
                     */
                    var productPage = $("#pg-product");
                    // 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"),
                            img = $("#pg-product-image-container img"),
                            nav = $("#pg-product-images-nav a"),
                            thumbnails = $("#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.delegate("a", "click", function(e) {
                            e.preventDefault();
                            var id = this.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);
                        });
                        
                        pgo.doc.keydown(function(e) {
                            var state;
                            if (e.keyCode == 37)
                                state = "prev";
                            else if (e.keyCode == 39)
                                state = "next";

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

                    $("#pg-zoom").click(function(e) {
                        //e.preventDefault();
                        var o = pgo.overlay(),
                                zoomNode = $(this).addClass('pg-none'),
                                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.removeClass('pg-none');
                                }).appendTo(imageContainer); 
                                pgo.doc.keyup(function(e) {
                                    if (e.keyCode == 27)
                                        close.click();
                                });
                            $("#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").delegate('dt, dd', 'hover', function(e) {
                            var t = $(e.target)
                                et = e.type,
                                state = {
                                    'cl': 'addClass',
                                    'tr': 'next'
                                };
                            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").delegate('input', "change", function (ev) {
                        $("#pg-price-filter").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
                    //function initPriceAlertForm() {
                    $("body").delegate("div.pg-price-alert form button", "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", form), '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) {
                                var msg = "Prisvarsling registert";
                                notice('success', msg, button, 'after')
                                        .css({
                                            marginLeft: 20
                                        });
                            });
                        }
                    });
                    
                    // Price alert popup 
                    $('#pg-price-alert-popup-link').click(function(e) {
                        e.preventDefault();
                        pgo.popup.html('#pg-price-alert-popup');
                        pgo.popup.toggleBG(true, " Bestill prisvarsling");
                        pgo.popup.show.lightbox();
                    });
                    
                }
            },
            //Generic popup box. Located pre <tns/analytics></body>
            popup: {
                defaultCss: {},
                eTarget: {}, //On some popups we need to store the target clicked in order to remove pg-selected on close.
                
                // Get PopupBox object
                getBox: function() {
                    //Get Cached PopupBox Object. If !exists fetch it.
                    if (this.popupBox && this.popupBox.length) return this.popupBox;
                    var box = $('#pg-default-popup');
                    if (box.length) {
                        box.find(".pg-popup-close, .pg-popup-close-x").click(function(e) {
                            e.preventDefault();
                            e.stopPropagation();
                            pgo.popup.hide();
                        });
                        $("#pg-popup-overlay").click(function(e) {
                            pgo.popup.hide();
                        });
                        this.popupBox = box;
                        return box;
                    }
                    pgo.pglog("pgo.popup.getBox() - Unable to find box!");
                    return false;
                },
                //Show loading symbol (usable for ajax calls). Using pgo.popup.html() will auto hide the loading - since we expect html() to be called on ajax success.
                loading: {
                    show: function() {
                        pgo.popup.getBox().find('.pg-loading-container').show();
                    },
                    hide: function() {
                        pgo.popup.getBox().find('.pg-loading-container').hide();
                    }
                },
                
                //Stores original css values based on array keys of the new css.
                //Each time you supply a new css property it will be stored. defaultCss will gradually be filled with more and more default properties.
                //Run this before setting any css.
                resetCss: function(newCss) {
                    if (newCss) {
                            var box = pgo.popup.getBox();
                            if (typeof(newCss) == "object") { 
                                $.each(newCss,function(item,value) {
                                    if (typeof(pgo.popup.defaultCss.item) == "undefined")
                                        pgo.popup.defaultCss[item] = box.css(item); //Store default values for all the items newCss will overwrite.
                                });
                            }
                            box.css(pgo.popup.defaultCss); //Reset css.
                    }
                },
                
                //Toggle between white/black template of popup. popup.hide() sets this back to Black.
                toggleBG: function(white,title) {
                    var box = pgo.popup.getBox();
                    //Add white class to popup wrapper
                    if (white) {
                        box.find('.pg-popup-content-wrapper').addClass("pg-rounded-corner");
                        box.addClass("pg-popup-white");
                    }
                    else {
                        box.removeClass("pg-popup-white");
                        box.find('.pg-popup-content-wrapper').removeClass("pg-rounded-corner");
                    }
                    
                    //Set title in rounded corner box on top
                    var objTitle = $('#pg-popup-title');
                    if (typeof(title) != "undefined") {
                        objTitle.find("h2").html(title);
                        objTitle.show();
                    }
                    else objTitle.hide();
                },
                resize: function(width) {
                    if (width) {
                            //Proper resizing. Percentage width (as I started out with) doesn't work well with IE 7
                            var box = pgo.popup.getBox();
                            box.find('div.pg-popup-top-left').width(width-10);
                            box.find('div.pg-popup-bottom-left').width(width-10);
                            box.width(width);
                    }
                },
                adjustBorder: function() {
                    //Opacity border resize accordingly
                    var border = $('#pg-popup-border');
                    var box = pgo.popup.getBox();
                    border.width(box.width() +4);
                    border.height(box.height()+4);
                    offset = box.offset();
                    border.css({
                        top: (offset.top+1),
                        left: (offset.left -2)
                    });
                    border.show();
                },
                show: {
                    //Check if obj is jquery object or event object and return false if neither.
                    //useCurTarget: If true and obj=event return e.currentTarget instead of e.target (used by dropdowns to get correct elem clicked)
                    checkObj: function(e,useCurTarget) {
                        if (!useCurTarget && typeof(e.target) != "undefined") 
                            return $(e.target);
                        else if (typeof(e.currentTarget) != "undefined")  
                            return $(e.currentTarget);                            
                        else if (typeof(e.jquery) != "undefined")
                            return e;
                        pgo.pglog("pgo.popup.show.checkObj: Wrong object type.");
                        return false;
                    },
                    notice: function(e,css,verticalAlign) {
                        pgo.popup.hide(true);
                        var target = this.checkObj(e);
                        var box = pgo.popup.getBox(); 
                        if (!box || !target.length) {
                            pgo.pglog("Unable to find popupbox or !obj.length");
                            return false;
                        }
                        pgo.popup.resize(300); //Reset width
                        pgo.popup.resetCss(css); //Pass new css and use array keys to store original css and reset.
                        this.showTime = new Date().getTime(); //Measure time popup is open. If closed too fast report to pglog.
                        var offset = target.offset(); //Offset is best way to position. Finds e.targets offset according to document.
                        box.css({
                            top: offset.top + target.outerHeight(),
                            left: offset.left-15
                        });
                        pgo.popup.show.docOverlay();

                        if(verticalAlign == 'above') {
                            box.css('top', (offset.top - box.outerHeight()) + 15);
                            box.find('div.pg-arrow').addClass('bottom');
                        }

                        box.find('div.pg-arrow').show();                            
                        if (css) 
                            box.css(css);
                        box.show();
                        pgo.popup.adjustBorder();
                        
                        return true;
                    },
                    lightbox: function(fullwidth,css) {
                        pgo.popup.hide(true);
                        var box = pgo.popup.getBox();
                        box.data('isCentered',true);
                        if (!box) {
                            pgo.pglog("Unable to find popupbox or !obj.length");
                            return false;
                        }
                        this.showTime = new Date().getTime(); //Measure time popup is open. If closed too fast report to pglog.
                        pgo.popup.resetCss(css); //Pass new css and use array keys to store original css and reset.
                        
                        if (fullwidth) pgo.popup.resize(980); //Page width
                        box.center();
                        if (css)
                            box.css(css);
                        pgo.popup.show.overlay();
                        box.show();
                        return true;
                    },
                    dropdown: function(e,align,css,overlay) { //Align = left/center/right relative to position of 'e'. 'Page' sets full page (not screen) width (like categories/shops dropdown)
                        pgo.popup.hide(true);
                        if (typeof(e) == "undefined") {
                            pgo.pglog("pgo.popup.show.dropdown error: Event undefined.");
                            return false;
                        }
                        if (typeof(align) == 'undefined') align = "";
                        var box = pgo.popup.getBox();
                        var elem = this.checkObj(e,true);
                        align = align.toLowerCase();
                        pgo.popup.eTarget = elem;
                        elem.addClass("pg-selected");
                        if (!box) return false;
                        if (css)
                                pgo.popup.resetCss(css); //Pass new css and use array keys to store original css and reset.
                        this.showTime = new Date().getTime(); //Measure time popup is open. If closed too fast report to pglog.
                        
                        var posTarget = $(e.target).offset();
                        if (align == 'right') { //Right-align box to item clicked.
                            var position = {
                                right: pgo.doc.width() - (posTarget.left + $(e.target).outerWidth()),
                                left: 'auto'
                            };
                            if (!$.browser.msie) position.right += -4;
                            else position.right += -22;
                        }
                        else if (align == 'center') {
                            if (css.width) box.width = css.width; //We have to set custom width first because center align uses it
                            var position = {
                                /*      Absolute middle of e.Target             And subtract half of box width */
                                left: (posTarget.left + (elem.outerWidth()/2)) - (box.width/2),
                                right: 'auto'
                            };
                        }
                        else if (align == 'page') {
                            if (css && css.width) pgo.pglog('pgo.popup.dropdown: Overriding custom width due to align "page"');
                            pgo.popup.resize(980);
                            css.width = 980;
                            var position = {
                                left: (pgo.win.width() - box.width()) / 2 + pgo.win.scrollLeft(),
                                right: 'auto'
                            };
                        }
                        else {
                            var position = {
                                left: posTarget.left,
                                right: 'auto'
                            };
                        }
                        position.top = posTarget.top + $(e.target).outerHeight() -5;
                        if (position)
                            box.css(position);
                        if (css)
                            box.css(css);
                        
                        //Use overlay or document for additional hide()? 
                        if (overlay) pgo.popup.show.overlay(true);
                        else pgo.popup.show.docOverlay();
                        box.show();
                        return true;
                    },
                    overlay: function(transparent) {
                        var overlay = $("#pg-popup-overlay");
                        if (transparent)
                            overlay.removeClass("pg-overlay-bg");
                        else
                            overlay.addClass("pg-overlay-bg");
                            
                        overlay.show();
                    },
                    //Create onclick event for document that closes box without disabling other links outside popup.
                    docOverlay: function(isDelayed) {
                        //Sometimes document.click() triggers automatically (without stopPropagation). Delaying assigment of event to document solves the problem.
                        if (!isDelayed) 
                            var timer = setTimeout('pgo.popup.show.docOverlay(1);',20);
                        else {
                            pgo.doc.click(function(e) {
                                e.stopPropagation();
                                var tmp = $(e.target);
                                //Traverse all parent items of e.target until none. If id=popupbox then don't hide.
                                while (tmp.length) {
                                    if (!tmp.length) break;
                                    if (tmp.attr('id') == 'pg-default-popup') {
                                        return;
                                    }
                                    tmp = tmp.parent();
                                }
                                pgo.popup.hide();
                            });
                        }
                    }
                },
                autohide: function(ms) { //Autohide popup in x Milliseconds
                    if (!ms) ms = 4000;
                    var timer = setTimeout(function() {
                        pgo.popup.hide();
                        delete timer;
                    },ms);
                },
                //If noClean == true: Used in show.function() to make transition between popups seem smoother
                //noClean is also used to prevent hide() from removing certain settings.
                hide: function(noClean) {
                    var box = pgo.popup.getBox();
                    if (!box) return false;
                    
                    //Measure how long the popup was open. If it was closed in under 100ms then a close event is triggered to fast. (Use stopPropagation()?)
                    var timeOpen = (new Date().getTime())-this.show.showTime;
                    delete this.show.showTime;
                    if (timeOpen > 0 && timeOpen < 100) {
                        pgo.pglog('pgo.popup.hide(): Close event was triggered to fast!');
                    }
                    
                    if (!noClean) {
                        //We're justing hiding before load so don't reset some settings as they're set before show.func()
                        //These settings are reset on popup close anyways so it's no biggy. 
                        pgo.popup.toggleBG(false);
                        pgo.popup.html();
                        pgo.popup.resize(300); //Set default.
                        box.data('isCentered',false);
                        
                        //Clean all events from objects in box. We're having trouble with reassigning events.
                        $('div.pg-popup-content',box).find('*').each(function() {
                           $(this).unbind(); 
                        });
                    }
                    
                    var pg_arrow = box.find('div.pg-arrow');
                    pg_arrow.removeClass('bottom');
                    pg_arrow.hide();
                        
                    if (pgo.popup.eTarget) {
                        $(pgo.popup.eTarget).removeClass('pg-selected');
                        pgo.popup.eTarget = {};
                    }
                    pgo.doc.unbind('click'); //Document onclick hide() event.
                    
                    //Some positioning problems. Reset to auto on hide 
                    box.hide(); //JQuery hide func()
                    $('#pg-popup-overlay').hide();
                    $('#pg-popup-border').hide();
                    return true;
                },
                
                //Send Html-element Id or CacheId and Html to this function. Caches content, deletes html element (to avoid Jquery selector problems) and returns content.
                cacheId: function(Id,html) {
                    var data = $._isCached(Id);
                    if (!data) { //Not cached
                        if (typeof(html) == "undefined") { //If !html: cache contents of html element and then delete it afterwards.
                            var elem = $(Id);
                            if (!elem.length) {
                                pgo.pglog("pgo.popup.cache() - ID: " + Id + " not cached and unable to find html element.");
                                return false;
                            }
                            data = elem.html();
                        }
                        else data = html;
                        
                        $._cache(Id,data);
                        return data;
                    }
                    if (!html) $(Id).remove();
                    return data;
                },
                
                html: function(data) {
                    var box = pgo.popup.getBox();
                        
                    //If first char in data is # then it's a html Id! Fetch element, cache it and delete it!
                    if (typeof(data) == "string" && data.substr(0,1) == "#") {
                        data = pgo.popup.cacheId(data);
                        if (!data) return false;
                    }
                    var content = box.find('div.pg-popup-content');
                    if (!content.length) return false;
                    pgo.popup.loading.hide();
                    if (data)
                        content.html(data);
                    else
                        content.empty();
                        
                    if (box.data('isCentered'))
                        box.center();
                        
                    return true;
                }
            },
            
            // USER MANAGEMENT
            auth: {
                isAuthed: false,

                //Check if user is authed. If not display warning. Return true if you need to auth. Used in restricted events.
                needAuth: function (e, action) {
                    if (!pgo.auth.isAuthed) {
                        pgo.popup.html('#pg-auth-warning-html');
                        $('a.pg-login-show').click(function (e) {
                            e.preventDefault();
                            pgo.auth.show(undefined, undefined, action);    
                        });
                        $('a.pg-register-show').click(function (e) {
                            e.preventDefault();
                            pgo.register.show();
                            
                        });
                        pgo.popup.show.notice(e);
                        return true;
                    }
                    return false;
                },
                //Load Login template and show popup.
                show: function(e, message, action, wrapper) {
                    pgo.popup.loading.show();
                    if (!e)
                        pgo.popup.show.lightbox();
                    else
                        pgo.popup.show.dropdown(e,'right');

                    if( (typeof(action) == 'undefined') || (action == null) ) {
                        action = '';
                    }

                    //Check if login form is cached. If so then just reinsert that into popup.
                    var form = $._isCached('pgo-login-form'); //Returns cache value
                    if (!form) {
                        $.ajax({
                            url: '/service?module=PGAuth&service=getTemplate&referer='+ encodeURIComponent(pgo.safe_url + action), 
                            success: function(resp) {
                                pgo.popup.html(resp);
                                if (message) {
                                    var msgbox = $('#pg-login-message');
                                    msgbox.html(message);
                                    msgbox.addClass("pg-login-error");
                                }
                                var box = $(wrapper);
                                if (message && box.length) {
                                    box.addClass('pg-userform-error');
                                    box.find('div.pg-user-form-input-right').addClass('pg-userform-error');
                                }
                                
                                
                                $('#pg-login-form').submit(function(e) {
                                    var remember = $('#pg-remember:checked');
                                    var that = $(this);
                                    if (that.length && remember.length) {
                                        var referer = that.find('input[name=referer]');
                                        referer.val(referer.val() + "&remember=true");
                                    }
                                });
                                
                                
                                $._cache('pgo-login-form',resp);
                                $("#pg-new-password").click(function (e) {
                                    e.preventDefault();
                                    $("#pg-login-form").hide();
                                    $("#pg-new-password-form").removeClass("pg-none");
                                    $("#pg-new-password-hide").click(function(e) {
                                        e.preventDefault();
                                        $("#pg-new-password-form").addClass("pg-none");
                                        $("#pg-login-form").show();
                                    });
                                });
                            }
                        });
                    }
                    else {
                        pgo.popup.html(form);
                        $("#pg-new-password").click(function (e) {
                            e.preventDefault();
                            $("#pg-login-form").hide();
                            $("#pg-new-password-form").removeClass("pg-none");
                            $("#pg-new-password-hide").click(function(e) {
                                e.preventDefault();
                                $("#pg-new-password-form").addClass("pg-none");
                                $("#pg-login-form").show();
                            });
                        });
                        
                        $('#pg-login-form').submit(function(e) {
                            var remember = $('#pg-remember:checked');
                            var that = $(this);
                            if (that.length && remember.length) {
                                var referer = that.find('input[name=referer]');
                                referer.val(referer.val() + "&amp;remember=true");
                            }
                        });
                                
                        var box = $(wrapper);
                        if (message && box.length) {
                            box.addClass('pg-userform-error');
                            box.find('div.pg-user-form-input-right').addClass('pg-userform-error');
                        }
                    }
                },
                //Query for auth info with callback.
                info: function(callback) {
                    $.getJSON('/service?module=PGAuth&service=info', function(resp) {
                        if (resp.ok) pgo.auth.isAuthed = true;
                        else pgo.auth.isAuthed = false;
                        if (typeof(callback) == 'function') callback(resp);
                    });
                },
                //Logout
                logout: function() {
                    //This function should contain path filter for pages you don't want to return to.. like pages where you need to be logged in.
                    document.location = "https://auth.tek.no/migrate/?action=logout&referer=" 
                    + encodeURIComponent(document.location.protocol 
                        + document.domain 
                        + document.location.pathname 
                        + "?module=PGAuth&service=logout" 
                    );
                }
            },
            
            register: {
                show: function(e) {
                    //Load html into popup.
                    pgo.popup.loading.show();
                    pgo.popup.toggleBG(true,'Registrer deg');
                    pgo.popup.resize(500);
                    pgo.popup.show.lightbox();
                    
                    $.ajax({
                        url: "/profil/registrer?module=PGRegister&service=getTemplate&referer=" + encodeURIComponent(pgo.safe_url),
                        success: function(resp) {
                            pgo.popup.html(resp);
                            
                            /* Register Events start */
                            var box = pgo.popup.getBox();
                            $("#pg-username").focus();
                            
                            //Password help
                            $('#pg-register-pwdinfo').click(function(e) {
                                e.preventDefault();
                                $('#pg-register-pwdinfo-html').toggleClass("pg-none");
                            });
                            
                            //Password validation hints
                            $("#pg-register-password").keyup(function(e) {
                                var that      = $(this),
                                    tip       = that.parent().next("div.pg-tooltip"),
                                    val       = that.val(),
                                    minLength = 6,
                                    strength  = 1,
                                    bgColor   = "#b72727";
                                
                                if (typeof(passwordInfo) == 'undefined')
                                    passwordInfo = tip.text();
                               
                                if (val.length >= minLength) {
                                    if (/[a-z]/.test(val)) strength++;
                                    if (/[A-Z]/.test(val)) strength++;
                                    if (/[0-9]/.test(val)) strength++;
                                    if (/[$%:`´^¨~<>;.,$#£&\-\[\]@!|§}{+\-?=\/\\]/.test(val)) strength++;
                                    if (strength > 2) bgColor = "#ffff00";
                                    if (strength > 3) bgColor = "#ffb84e";
                                    if (strength > 4) bgColor = "#62b045";
                                    
                                    var c = $("<div class=\"pg-relative\" />")
                                            .css({
                                                height: 11,
                                                width: 60,
                                                backgroundColor: "#eee"
                                            }),
                                        l = $("<div class=\"pg-absolute\" />")
                                            .css({
                                                top: 0,
                                                left: 0,
                                                height: 11,
                                                width: 20 * strength + "%",
                                                backgroundColor: bgColor
                                            });
                                    tip.html(c.append(l));
                                }
            
                                var current = minLength - (val.length || 0);
                                if ( current == minLength ) 
                                    tip.text( passwordInfo );
                                else if ( current > 0 )
                                    tip.text("Du mangler " + current + " tegn");
                                
                            });
                            
                            //Submit button event
                            $("#pg-register-form", box).find('.pg-button-submit').click(function(e) {
                                e.preventDefault();
                                pgo.register.send();
                            }); 
                            /* Register Events end */
                        }
                    });
                                       
                },
                send: function() {
                    $("#pg-register-form").ajaxForm({
                        url:"/profil/registrer?module=PGRegister&service=register", 
                        dataType: "json",
                        beforeSend: function() {
                            $("#pg-register-form").find(".pg-button-submit").html("Sender..");
                        },
                        success: function(response) {
                            var box = pgo.popup.getBox();
                            $("#pg-register-form").find(".pg-button-submit").html("LAG PROFIL");
                            if (response.errors != undefined) {
                                for (var error in response.errors) {
                                    //Find Error-Tooltip and insert every error
                                    var elem = $("#pg-user-form-error-" + error);
                                    
                                    elem.html(response.errors[error]);
                                    elem.removeClass("pg-none");
    
                                    //Set red gfx to input box
                                    $("input[name=" + error + "]",box).parent(".pg-user-form-input").addClass("pg-userform-error");
                                    $("input[name=" + error + "]",box).next(".pg-user-form-input-right").addClass("pg-userform-error");
    
                                    //Hide default tooltip if any.
                                    $("#pg-user-form-error-" + error).prev(".pg-tooltip").addClass('pg-none'); 
                                }
                            }
                            else {
                                $("#pg-register-form").html("<div><h2 class=\"pg-color-green-1\">Brukerregistreringen var vellykket.</h2><p>Du vil snart motta en epost til " + response.userData.email + " med en aktiveringsnøkkel.</p></div>");
                            }
                        }
                    });
                    $('#pg-register-form').submit();
                }
            },
            profile: {
                save: function(e) {
                    var form = $('#pg-form-update-profile');
                    pgo.popup.loading.show();
                    pgo.popup.toggleBG(true,'Din Profil: Lagrer endringer...');
                    pgo.popup.show.lightbox();
                    form.ajaxForm({
                        url:'/service?module=PGProfile&service=save',
                        dataType: 'json',
                        success: function(resp) {
                            if (resp.ok) {
                                var form = $('#pg-form-update-profile');
                                var span = form.find('input').parent('span.pg-userform-error');
                                span.each(function() {
                                    var that = $(this);
                                    that.removeClass('pg-userform-error');
                                    that.find('span.pg-user-form-input-right').removeClass('pg-userform-error');    
                                });
                                
                                var html = "";
                                if (resp.reactivate) {
                                    html = "<h2>Du har endret epost:<br/>Din konto må reaktiveres.<br/>Du vil motta en epost med lenke til aktivering.</h2><br/>";
                                }
                                if (!pgo._length(resp.failed)) {
                                    html += '<p>Endringer lagret. Du kan nå lukke denne boksen.</p>';
                                }
                                else {

                                    html += '<p><strong class="pg-color-red">Følgende informasjon ble ikke lagret:</strong><br/>';
                                    for(var key in resp.failed) {
                                        var field;
                                        span = form.find('input[name=' + key + ']').parent('span');
                                        span.addClass('pg-userform-error');
                                        span.find('span.pg-user-form-input-right').addClass('pg-userform-error');

                                        // FIXME: Make into a switch loop 
                                        if (key == 'email') field = "Epost";
                                        else if (key == 'name') field = "Navn";
                                        else if (key == 'username') field = "Brukernavn";
                                        else if (key == 'zipcode') field = "Postnummer";
                                        else if (key == 'yearOfBirth') field = "Fødselsår";
                                        else if (key == 'sex') field = "Kjønn";
                                        html += field + " (" + resp.failed[key] + ")" + "<br/>";
                                    }
                                }
                                pgo.popup.html(html);
                                
                            }
                            else {
                                pgo.popup.html('Beklager! En feil har oppstått. Prøv igjen senere.');
                            }    
                        }
                    });
                    form.submit();
                }
            },
            
            //SHOPPINGLISTS
            list: {
                changeDesc: function(listId, desc, e) {
                    $.getJSON("/service?module=PGLists&service=changeDesc&listId="+listId+"&desc="+desc,function(resp) {
                        if (resp.ok) {
                            pgo.popup.html('Beskrivelse for listen er nå satt.');
                        }
                        else {
                            pgo.popup.html('Feil: Beskrivelse for listen ble ikke satt.');
                        }
                        pgo.popup.show.notice(e);
                    });
                },
                product: {
                    add: function(e,productId,listId) {
                        if (!productId.length || !listId.length)
                            return false;
                        var result = $.ajax({
                            url: '/service?module=PGLists&service=add&listId='+listId+'&id='+productId,
                            dataType: 'json',
                            success: function(resp) {
                                $._cache('pgo.mylists',null);
                                pgo.list.product.visualAdd($(e.target), resp.title);
                                updateHeader();
                                pgo.popup.hide();
                            }
                        });
                        return true;
                    },
                    remove: function(e,productIds,listId,callback) {
                        if (typeof(productIds) == "undefined" || !productIds.length || !listId.length) {
                            pgo.pglog("Unable to remove products from list. Missing id(s).");
                            return false;
                        }
                        if (isNaN(productIds)) {
                            alert(productIds);
                            var ids = productIds.join(',');
                        }
                        else
                            var ids = productIds;
                        $.getJSON('/service?module=PGLists&service=delete&listId='+listId+'&ids='+ids, function(resp) {
                            if (resp.ok) {
                                $._cache('pgo.mylists',null);
                                //In Profile/Lists: Previously we just removed the item with js. We need to reload because it's too itensive to redo all prices in both list and shipping.
                                if (typeof(callback) != "function") {
                                    location.assign(location.pathname); //Use pathname just in case there are some funky get params
                                    pgo.popup.html('Produkt fjernet.<br/>Siden lastes p&aring; nytt.');
                                    pgo.popup.show.notice(e);
                                }
                                else callback(e);
                            }
                            else {
                                pgo.popup.html('Et problem har oppst&aring;tt ved fjering av produkt. Pr&oslash;v p&aring; nytt.');
                                pgo.popup.show.notice(e);
                            }
                        });
                        return true;
                    },
                    changeQuantity: function(e,productId,listId,quantity) {
                        if (quantity == 0 || !quantity) {
                            //Delete product
                            pgo.popup.html("Vennligst benytt slette funksjonen om du &oslash;nsker fjerne et produkt.");
                            pgo.popup.show.notice(e);
                        }
                        else {
                            $.getJSON("/service?module=PGLists&service=changequantity&productId="+productId+"&listId="+listId+"&quantity="+quantity,function(resp) {
                                if (resp.ok) {
                                    $._cache('pgo.mylists',null);
                                    pgo.popup.html('Antallet er oppdatert. Siden laster n&aring p&aring; nytt.');
                                    var obj = $('#pg-list-quantity-box-' + productId);
                                    pgo.popup.show.notice(obj);
                                    location.reload();
                                }
                                else {
                                    pgo.popup.html('En feil har oppst&aring;tt. Vennligst pr&oslash;v senere. (' + resp.messages[0] + ')');
                                    pgo.popup.show.notice(e);
                                }
                            });
                        }
                    },
                    //Visualize Add - Popupbox that floats up to "List"-button in header. Call after adding product.
                    visualAdd: function(visualizedNode,title, selector) {
                        var listNode = $(selector != undefined ? selector : "#pg-nav-lists li.pg-lists"),
                            prevNotification = $(".pg-notification"),
                            notification = $("<div class=\"pg-notification\" />")
                                .css({
                                    position: 'absolute',
                                    backgroundColor: "#fbca91",
                                    top: visualizedNode.offset().top,
                                    left: listNode.position().left,
                                    zIndex: 200
                                })
                                .appendTo("body").click(function() {
                                    close.click();
                                }),
                            close = $("<a href=\"#\">Lukk</a>") 
                                .css({
                                    position: 'absolute',
                                    top: 0,
                                    right: 0
                                })
                                .click(function(e) {
                                    e.preventDefault();
                                    notification.remove();
                            }),
                            marginTop = listNode.outerHeight() + "px";
                        
                        if (prevNotification.length > 0) {
                            var tmp = 0;
                            for (var i = 0; i < prevNotification.length; i++) {
                                tmp = tmp + $(prevNotification).outerHeight();
                            }
                            marginTop = listNode.outerHeight() + tmp;
                        }
                        
                        notification.text('Lagt til i "'+title+'"').append(close);
                        notification.addClass("pg-rounded-corner")
                        
                        notification.animate(
                            {backgroundColor: "#000"},
                            800,
                            null,
                            function() {
                                $(this).animate(
                                    {
                                        top: listNode.position().top,
                                        marginTop: marginTop
                                    },
                                    500,
                                    null,
                                    function() {
                                        $(this).animate(
                                            {opacity: 0},
                                            2000,
                                            null,
                                            function() {
                                                $(this).remove();
                                            }
                                        );
                                    }
                                );
                            }
                        );
                    },
                    /* AddToList Popup: Load list contents and show it */
                    showAdd: function(e) {
                        e.preventDefault();
                        var that = $(e.target);
                        //shopListItems are the different lists, not the items in the lists.
                        //shopListItems are cached in order to prevent several calls to ajax. Especially since the popup is reusable by other parts of the system.
                        //Fetch all my lists.
                        pgo.popup.loading.show();
                        pgo.popup.show.notice(e);
                        pgo.list.lists.get(function(resp) {
                            //Count amount of lists in resp. In case there's only one list we also need to remember that ID since we auto-insert.
                            delete(resp.html);
                            var listCount = 0;
                            for (var i in resp) { var listId = i; listCount ++; }
                            
                            //If only 1 list - auto insert item into that list.
                            if (listCount <= 1) { 
                                productId = that.attr('href').split('#')[1];
                                //Insert item by ajax.
                                pgo.list.product.add(e,productId,listId);
                            }
                            else {
                                var html = '<h3>Legg til i liste</h3>';
                                html += '<ul class="pg-add-to-list">';
                                for(listId in resp) {
                                    var list = resp[listId];
                                    html += '<li><a href="#' + listId + '">' + list.title + '</a></li>';
                                }
                                html += "</ul>";
                                pgo.popup.html(html);
                                
                                $('ul.pg-add-to-list li a').click(function(event) {
                                    event.preventDefault();
                                    //Fetch listId from the A element
                                    if (!that.length) {
                                        pgo.pglog("Error adding item to list. Unable to find A item");
                                        return false;
                                    }
                                    var listId = $(this).attr('href').split('#')[1];
                                    //Fetch productId from the UL element
                                    var productId = that.attr('href').split('#')[1];
                                    pgo.list.product.add(e,productId,listId);
                                    return true;
                                });
                                //pgo.popup.show.notice(e);
                            }
                        });  
                    }
                },
                lists: {
                    //Delete one or more lists. Supply array or single id.
                    remove: function(e,deleteIds) {
                        if (typeof(deleteIds) == "undefined" || !deleteIds.length) {
                            pgo.pglog("Unable to delete list. Missing id(s).");
                            return false;
                        }
                        if (isNaN(deleteIds) && deleteIds != "min") var ids = deleteIds.join(',');
                        else ids = deleteIds;
                        $.getJSON('/service?module=PGLists&service=deleteLists&listIds='+ids, function(resp) {
                            //If location.pathname contains listId we need to go back to /profil/lister/
                            if (location.pathname != '/profil/lister' && location.pathname != '/profil/lister/') {
                                if(resp.ok)
                                    pgo.popup.html("Listen er n&aring; slettet.<br/>Siden lastes p&aring; nytt.");
                                else
                                    pgo.popup.html("Et problem har oppst&aring;tt. Pr&oslash;v p&aring; nytt senere.");
                                    
                                pgo.popup.show.notice(e);
                                location.assign('/profil/lister');                    
                            }
                            //We're in list overview so just remove the html item
                            else {
                                if (resp.ok) {
                                    var item = $('input:checked').parent('div').parent('li.pg-shopping-list-item');
                                    //Realtime remove html item from list
                                    if (item) item.remove();
                                    //Unable to remove, reload page instead
                                    else location.assign('/profil/lister');                    
                                }
                                else {
                                    pgo.popup.html("Et problem har oppst&aring;tt. Pr&oslash;v p&aring; nytt senere.");
                                    pgo.popup.show.notice(e);
                                }
                            } 
                        });
                        return true;
                    },
                    add: function(name,callback) {
                        $.getJSON('/service?module=PGLists&service=addList&title='+encodeURI(name), function(resp) {
                            $._cache('pgo.mylists',null);
                            callback(resp);
                        });
                    },
                    //Fetch shopping list. 
                    get: function(callback,template) {
                        if (typeof(template) == "undefined") template = 0;
                        var result = $.ajax({
                            url: '/service?module=PGLists&service=mylists', 
                            dataType: 'json',
                            success: function(resp) {
                                callback(resp);
                            }
                        });
                    },
                    
                    showManage: function(e) {
                        pgo.popup.loading.show();
                        pgo.popup.show.dropdown(e,'left');
                        var cache = $._isCached('pgo.mylists');
                        if (!cache) {
                            pgo.list.lists.get(function(resp) {
                                $._cache('pgo.mylists',resp.html);
                                pgo.popup.html(resp.html);
                                
                                var thisEvent = e;
                                //Product Delete Event
                                $('.pg-lists-item-remove',pgo.popup.getBox()).click(function(e) {
                                    e.preventDefault();
                                    var productId = $(this).attr('href').split('#')[1];
                                    
                                    var listId = $(this).parent('li').parent('ul.pg-lists-items').attr('title').replace("#",'');
                                    pgo.list.product.remove(thisEvent,productId,listId,function(e) {
                                        pgo.list.lists.showManage(e);
                                    });
                                   
                                });
                                
                                //List Expand/Collapse event
                                $('.pg-list-view').click(function(e) {
                                    var that = $(this);
                                    if (that.hasClass('pg-list-expand')) {
                                        that.removeClass('pg-list-expand');
                                        that.addClass('pg-list-collapse');
                                        that.nextAll('ul.pg-lists-items.pg-none').removeClass('pg-none');
                                    }
                                    else {
                                        that.addClass('pg-list-expand');
                                        that.removeClass('pg-list-collapse');
                                        that.nextAll('ul.pg-lists-items').addClass('pg-none');
                                    }
                                });
                                
                                //Create List button
                                $('#pg-lists-dropdown span.pg-user-form-input a.pg-button').click(function(e) {
                                    //Fetch list name
                                    var name = $('#pg-lists-dropdown span input[name=new-list-name]').val();
                                    //Error handling on missing name
                                    if (typeof(name) == "undefined" || name == "") {
                                        var border = $('#pg-lists-dropdown').find('span.pg-user-form-input.pg-f-left');
                                        border.addClass('pg-userform-error');
                                        border.find('span.pg-user-form-input-right').addClass('pg-userform-error');
                                        var tooltip = $('#pg-lists-dropdown').find('span.pg-user-form-input.pg-tooltip');
                                        tooltip.addClass('pg-tooltip-error');
                                        tooltip.find('a.pg-button span.pg-button-name').text('LAG NY LISTE');
                                    }
                                    //Reset errors and rename button to show progress
                                    else {
                                        var border = $('#pg-lists-dropdown').find('span.pg-user-form-input.pg-f-left');
                                        border.removeClass('pg-userform-error');
                                        border.find('span.pg-user-form-input-right').removeClass('pg-userform-error');
                                        var tooltip = $('#pg-lists-dropdown').find('span.pg-user-form-input.pg-tooltip');
                                        tooltip.removeClass('pg-tooltip-error');
                                        tooltip.find('a.pg-button span.pg-button-name').text('Lager liste...');
                                    }
                                    pgo.list.lists.add(name,function(resp) {
                                        if (resp.id) {
                                            pgo.popup.html();
                                            pgo.list.lists.showManage(thisEvent);
                                        }
                                        else
                                            pgo.popup.html('En feil har oppstått. Kan ikke opprette liste. Prøv på nytt senere.');
                                        
                                    });
                                });
                            });
                        }
                        else {
                            pgo.popup.html($._isCached('pgo.mylists'));
                        }
                    }
                }
            },
            
            //REVIEWS
            reviews: {
                edit: {
                    load: function(e,id) {
                        pgo.popup.loading.show();
                        pgo.popup.show.lightbox(false,{"width": 385});
                        $.getJSON('/service', {
                            module: 'PGReview', 
                            service: 'edit', 
                            id: id
                        }, function (resp) {
                            if (resp.ok) {
                                pgo.popup.toggleBG(true,'Hva synes du om ' + resp.title + '?');
                                pgo.popup.html(resp.html);
                                
                                //Event handling for form and stars
                                if (resp.type == 'shop')
                                    pgo.reviews.shop.setEvents(id, true);
                                else
                                    pgo.reviews.product.setEvents(true);
                            }
                            else {
                                pgo.popup.html(resp.messages);
                                pgo.popup.show.notice(e);
                            }
                        });
                    },
                    save: function(data) {
                        pgo.popup.loading.show();
                        $.ajax({
                            url: '/service?module=PGReview&service=edit&action=save',
                            data: data, 
                            dataType: 'json',
                            success: function (resp) {
                                if (resp.ok) {
                                    pgo.popup.html('Endringer lagret! Siden lastes på nytt!');
                                    location.reload();
                                }
                                else {
                                    pgo.popup.html('Noe gikk galt! Prøv igjen senere.');
                                }
                            }
                        });
                    }
                },
                remove: function(e,id) { //e(vent) for where to show popup. remove is the same for both kinds of reviews... delete id and ratings on that id.
                    pgo.popup.html('Sletter omtale... vennlist vent.');
                    pgo.popup.show.notice(e);
                    $.getJSON('/service', {
                            module: 'PGReview', 
                            service:'delete', 
                            id: id
                        }, function(resp) {
                            if (resp.ok) {
                                $('.pg-review-wrapper[title=' + id + ']').remove();
                                pgo.popup.hide();
                            }
                            else {
                                pgo.popup.html('En feil har oppstått. Prøv igjen senere.');
                                pgo.popup.show.notice(e);
                            }
                        }
                    );
                },
                shop: {
                    show: function(id) {
                        if (!id) id = pgo.shopId;
                        if (!id) {
                            pgo.pglog("Error reviews.product.show: Missing ID.");
                            pgo.popup.html("Feil! Mangler produktId. Kan ikke vise skjema for omtaler.");
                            pgo.popup.show.lightbox();
                            return false;
                        }
                        pgo.popup.loading.show();
                        pgo.popup.toggleBG(true,"Hva synes du om " + $('#pg-shop-title').html() + "?");
                        pgo.popup.show.lightbox(null,{width:382});

                        $.getJSON('/service', {
                            module: 'PGReview', 
                            service:'add', 
                            type:'shop',
                            id:id
                        }, 
                        function(resp) {
                            //Load html into popup
                            pgo.popup.html(resp.html);
                            pgo.reviews.shop.setEvents(id);
                        });
                        return true;
                    },
                    setEvents: function(id, editMode) {
                        //Set up events
                        var shopForm = $("#pg-add-shop-review>form");
                        if (shopForm.length > 0) {
                            var desc = [];
                                desc[1] = 'Veldig dårlig opplevelse';
                                desc[2] = 'Dårlig opplevelse';
                                desc[3] = 'Helt middels';
                                desc[4] = 'God opplevelse';
                                desc[5] = 'Ekstra god opplevelse';
                                
                            // Smiley event handle
                            $("ul.pg-set-smiley").find('a.pg-rating').click(function(e) {
                                e.preventDefault();
                                var that = $(this);
                                var rating = that.text();
                                var inputname = that.attr('title'); //Smileys store the "name" of the input field it belongs to
                                
                                //Remove pg-selected from smiley
                                $("a.pg-selected[title='" + inputname + "']").removeClass("pg-selected");
                                //Add pg-selected to this smiley
                                that.addClass("pg-selected");
                                //Set rating to the hidden Input element.
                                $('input[name='+inputname+']').val(rating);
                                
                                //Update the smiley description
                                var id = inputname.substr(inputname.length-2,1);
                                $('#pg-smiley-desc_' + id).html(desc[rating]);
                            });
                            
                            if (!editMode) {
                                //Set default description
                                $("ul.pg-set-smiley").find('a.pg-rating-smiley-small-3').each(function() {
                                    $(this).click();
                                });
                            }
                            
                            //Submit event
                            $('.pg-button-submit',shopForm).click(function(e) {
                                e.preventDefault();
                                var form = $('.pg-add-review-form');
                                var ratings1 = form.find('input[name=rating[1]]').val();
                                var ratings2 = form.find('input[name=rating[2]]').val();
                                var ratings3 = form.find('input[name=rating[3]]').val();
                                var parentId = form.find('input[name=parentId]').val();
                                var id = form.find('input[name=id]').val();
                                var parentId = form.find('input[name=parentId]').val();

                                var data = {
                                    type: 'shop',
                                    ratings1: ratings1,
                                    ratings2: ratings2,
                                    ratings3: ratings3,
                                    summary: $('#pg-review-summary').val(),
                                    anonymous: $j('#pg-review-anonymous').is(':checked')
                                };
                                if (id > 0) data.id = id;
                                if (parentId > 0) data.parentId = parentId;
                                
                                if (editMode) {
                                    pgo.reviews.edit.save(data);
                                }
                                else
                                    pgo.reviews.shop.add(data);

                            });
                        }
                        else {
                            pgo.pglog("Error pgo.reviews.shop.setEvents()! ShopForm length 0!");
                        }  
                    },
                    add: function (data) {
                        $.post('/service?module=PGReview&service=save', data, 
                            function(resp) {
                                if (resp.ok)
                                    pgo.popup.html("Din omtale er mottatt. Den vil bli synlig om ca 60 minutter.");
                                else {
                                    pgo.popup.html("En feil har oppst&aring;tt. Pr&oslash;v p&aring; nytt senere.");
                                }
                            },
                        'json');
                    }
                },
                product: {
                    show: function(id) { //Load popup html from ajax and show popup.lightbox
                        if (!id) id = pgo.productId;
                        if (!id) {
                            pgo.pglog("Error reviews.product.show: Missing ID.");
                            pgo.popup.html("Feil! Mangler produktId. Kan ikke vise skjema for omtaler.");
                            pgo.popup.show.lightbox();
                            return false;
                        }
                        pgo.popup.loading.show();
                        pgo.popup.toggleBG(true,"Hva synes du om " + $('#pg-product-title').html() + "?");
                        pgo.popup.show.lightbox(null,{width:382});
                        
                        //Fetch template modified by productId
                        $.getJSON('/service', {
                            module: 'PGReview', 
                            service:'add', 
                            type: 'product',
                            id: id
                        }, function(resp) {
                            pgo.popup.html(resp.html);
                            pgo.reviews.product.setEvents();
                        });
                        return true;
                    },
                    //setEvents is a function since used by both AddReview and EditReview
                    setEvents: function(editMode) {
                        
                        //Set up event handlers
                        var form = $('div.pg-add-review-form');
                        var data = {}, rating = 0;
                        var id =  $('#pg-review-main').attr('title').replace('#id_','');
                         
                        //Make stars work
                        $("ul.pg-stars a", form).click(function() {
                            $('ul.pg-stars',form).css("border","0");
                            pgo.reviews.product.rating = $(this).text();
                            var ratingPreview = $("div.pg-stars", form).empty();
                            ratingPreview.append("<div class=\"pg-star-" + rating + " pg-selected pg-f-left\" />");
                        });
                        
                        //Submit button event
                        $(".pg-button-submit", form).click(function(e) {
                            e.preventDefault();

                            var data = {
                                rating: pgo.reviews.product.rating/2,
                                summary: $('#pg-review-summary').val(),
                                proText: $('#pg-review-pros').val(),
                                conText: $('#pg-review-cons').val(),
                                anonymous: $j('#pg-review-anonymous').is(':checked')
                            };
                            var id = form.find('input[name=id]').val();
                            var parentId = form.find('input[name=parentId]').val();
                            if (id > 0) data.id = id;
                            if (parentId > 0) data.parentId = parentId;
                            
                            if (editMode) {
                                pgo.reviews.edit.save(data);
                            }
                            else
                                pgo.reviews.product.add(data,form);
                        });
                    },
                    add: function(data,form) { //Data = ajax data object
                        //VALIDATE: Rating
                        if (!pgo.reviews.product.rating) {
                            var objStar = $('ul.pg-stars',form);
                            if (objStar.length) {
                                objStar.css("border","2px solid #FF0000");
                                return false;
                            }
                            else return false;
                        }
                        
                        var button = $(this);
                        var regx = /\S+\n\S+/;
                        $("#pg-review-main :input", form).each(function(key,node) {
                            var item = $(this),
                                value = 0;
                            if (item.not(":password")) {
                                if (item.is(":checkbox"))
                                    value = item.attr('checked') ? 1 : 0;
                                else {
                                    if (regx.test(value))
                                        value = item.val();
                                    else
                                        value = item.val().split(",").join("\n");
                                }
                                data[node.name] = value;
                            }
                        });
                        
                        //Calculate rating and populate Ajax data
                        data.rating = Math.floor(pgo.reviews.product.rating / 2);
                        data.module = 'PGReview';
                        data.service = 'save';
                        if (data.rating < 1) {
                            form.find('.pg-stars')
                        }
                        $.post('/service?module=PGReview&service=save', data, 
                            function(resp) {
                                if (resp.ok)
                                    pgo.popup.html("Din omtale er mottatt. Den vil bli synlig om ca 60 minutter.");
                                else {
                                    pgo.popup.html("En feil har oppst&aring;tt. Pr&oslash;v p&aring; nytt senere.");
                                }
                            },
                        'json');
                        return true;
                    }
                }
            }
        }
        
        //Make safe URL. Remove unwanted additions to url made by auth.tek and others. Use pgo.safe_url only in all js files.
        var href = location.href;
        href = href.replace(/(\?|&)errors=wrong_password/g,''); // Use /g for one or more matches. 
        href = href.replace(/(\?|&)errors=no_such_user/g,'');
        href = href.replace(/(\?|&)ssoAction=logout/g,'');
        href = href.replace(/(\#).*/g,'');
        pgo.safe_url = href; //Store a safe URL to use in all ajax calls and location changes in PGO.
        
        //Load pagewide variables into PGO. I.e. productId or shopId.
        
        //Get productId
        var match = href.match('(?:/produkt/)([0-9]*)(?:/)?');
        if (match && match.length==2) pgo.productId = match[1];
        //Get shopId
        match = href.match('(?:/butikker/)([0-9]*)(?:/)?');
        if (match && match.length==2) pgo.shopId = match[1];

        
    } catch(err) {
        pgo.popup.show.lightbox();
        pgo.popup.html(
            '<h1>Ooops! En feil har oppstått!</h1><br/>' +
            'Hvis du ønsker kan du si ifra om dette på vårt <a href="http://feedback.tek.no/forums/31374-prisguide">feedback forum</a>'
        );
        pgo.pglog(err);
    }
    /* ##############
    End of Pris Guide Object
    ############### */

    function bodyLoaded() {
        var body = $("body");
        // Hook: Show Login
        body.delegate('#pg-login-link, .pg-login-link', 'click', function(e) {
            e.preventDefault();
            e.stopPropagation();
            pgo.auth.show(e);
        });
        
        // Hook: Logout link
        body.delegate('#pg-logout-link, .pg-logout-link', 'click', function(e) {
            e.preventDefault(); 
            pgo.auth.logout();
        });
        
        // Hook in register form
        body.delegate('#pg-register-link, .pg-register-link', 'click', function (e) {
            e.preventDefault();
            pgo.register.show(e);
        });

        body.delegate("div.pg-add-review-form", "click", function(e) {
            pgo.attachPGStarsEvt(this);
        });

    };

    $(window).bind("bodyLoaded", bodyLoaded);
    
    /*###################
      CUSTOM EXTENDS
    ##################*/
    
    // jQuery core
    $.extend({
        unserialize: function(str) {
            var s = str.split("&"), a, b = [];
            for (var i = 0; i < s.length; i++) {
                a = s[i].split("=");
                b.push({ name: a[0], value: a[1].replace('+',' ') }); 
            }
            return b;
        },
        Carousel: function(data) {
            $.Carousel.prototype.data = data;
            $.Carousel.prototype.current = 0;
            $.Carousel.prototype.move = function(pos) {
                var len = this.data.length;
                return this.data[Math.abs(this.current = (this.current + (pos ? 1 : len - 1)) % len)];
            }
            $.Carousel.prototype.next = function() {
                return this.move(1);
            }
            $.Carousel.prototype.prev = function() {
                return this.move(0);
            }
            $.Carousel.prototype.getCurrent = function() {
                return this.data[this.current];
            } 
        }
    });

    // jQuery node
    $.fn.extend({
        scrollTo: function(time) {
            time = time || time == 0 ? time : 2000;
            $("html, body").animate({
                scrollTop: this.offset().top
            }, time);

            return this;
        },
        reverse: Array.prototype.reverse,
        alternateText: function(alternate) {
            var text = this.data('originalText');
            if (text == undefined) {
                this.data('originalText', this.text());
                var text = this.data('originalText');
            }
            if (this.text() == text)
                this.text(alternate);
            else
                this.text(text);
            return this;
        },
        lazyload: function(show) {
            // Simple lazyload of images
            for (var i = 0; i < this.length; i++) {
                var self = $(this[i]);
                if (!show) {
                    self.data('original', self.attr('src'));
                    self.removeAttr('src');
                }
                else {
                    self.attr('src', self.data('original'));
                    self.removeData('original');
                }
            }
            return this;
        },
        center: function () {
            var node = this;
            return node.css({
                    position: 'absolute',
                    top: (pgo.win.height() - node.height()) / 2 + pgo.win.scrollTop() + "px",
                    left: (pgo.win.width() - node.width()) / 2 + pgo.win.scrollLeft() + "px"
                });
        },
        overlay: function(content, spinner) {
            var self = this,
                top = self.offset().top,
                left = self.offset().left,
                width = self.outerWidth(),
                height = self.outerHeight(),
                overlay, 
                close = function() {
                    oContent.remove();
                    overlay.remove();
                    self.data('pgOverlay', null);
		            $('body').css( 'overflow', 'auto' );
                };

            if (content) {
                var oContent = $("<div class=\"pg-overlay-content\" />");
                oContent.html(content);
                oContent.css({
                    position: 'absolute',
                    left: "50%",
                    top: 20,
                    width: 980,
                    backgroundColor: "#fff",
                    zIndex: 10004
                });
                oContent.appendTo("body");
                oContent.css({
                    marginLeft: "-" + oContent.width() / 2 + "px"
                });
                $("<a class=\"pg-close\" href=\"#\">Lukk</a>").click(function(e) {
                    e.preventDefault()
                    close();
		    $('body').css( 'overflow', 'auto' );
                })
                    .css({
                        position: 'absolute',
                        top: 4,
                        right: 4,
                        fontWeight: 'bold'
                    })
                    .appendTo(oContent);
            }
            if (self.data('pgOverlay')) {
                overlay = self.data('pgOverlay').overlay;
                oContent = self.data('pgOverlay').overlayContent;
                overlay.remove();
                oContent.remove();
		        $('body').css( 'overflow', 'auto' );
                self.data('pgOverlay', null);
            }
            else {
                overlay = $("<div class=\"pg-overlay\" />")
                            .css({
                                opacity: .7,
                                height: height,
                                width: width,
                                top: top,
                                left: left
                            });

                overlay.click(close);

                if (spinner)
                    overlay.append("<div class=\"pg-loading\"></div>");

                self.data('pgOverlay', {
                    overlay: overlay,
                    overlayContent: oContent
                });
                overlay.appendTo("body");
 
                pgo.doc 
                    .one('keyup', function(e) {
                        if (e.keyCode == 27) {
                            close();
                        }
                    });
            }
            return oContent ? oContent : self;
        }
    });
    
    
    /* ##############
        AUTORESPONSES ETC
    ################## */
    pgo.doc.ready( function() {
        //Init popupbox. IE7 has problems with corners popup.notice on first show.
        pgo.popup.resize(300);
        
        //Parse URL. Create a safe url for use in referer. (Safe != error params)
        //Check URL for login errors and show login box if true
        var url     = location.href;
        var matched = url.match( /(\?|&)errors=(\w+)/g );
        var action = url.match( /\#([a-z-]+)/g );
        if ( matched ) {
            var splited = matched[0].split( '=' );
            var message = '';
            if ( splited[1] == 'wrong_password' ) {
                message = 'Feil passord.';
                var wrapper = '#pg-password-wrapper';
            }
            else if ( splited[1] == 'no_such_user' ) {
                message = 'Bruker ikke funnet.';
                var wrapper = '#pg-email-wrapper';
            }
           
            if ( message != '' ) {
                if (pgo.auth.isAuthed == false) {
                    var e = {
                        currentTarget: $('#pg-login-link'),
                        target: $('#pg-login-link')
                    };
                    pgo.auth.show(e,message,action,wrapper); //Load the login form into popup and show it.
                }
            }
        } else {
            if(action) {
                switch(action[0]) {
                    case '#add-reviews':
                        var id = $('a.pg-reviews-add').attr('id').replace('add_review_', '');
                        if (location.href.match(/butikker/)) {
                            pgo.reviews.shop.show(id);
                        }
                        else
                            pgo.reviews.product.show(id);
                        break;
                    case "#sammenligne":
                        var pids = decodeURI(location.href);
                        pids = pids.split('&');
                        delete(pids[0]);
                        var url = "";
                        for(key in pids) {
                            if (url) url += ",";
                            url += pids[key].replace('pids[]=','');
                        }
                        $.cookie('compare',url);
                        updateHeader();
                        $('a.pg-compare').click();
                        break;
                }
            }
        }
    });
    
})(jQuery);


/* ######################
  Put eventhooks here. 
######################## */

$j(function($) {
    try {
        
        //Category megadropdown
        $("#pg-category-nav-item").click(function(e) {
            e.preventDefault();
            e.stopPropagation();
            if ($(this).data('selected')) {
                $(this).data('selected', false);
                pgo.popup.hide();
            }
            else {
                $(this).data('selected', true);
                pgo.popup.html('#pg-categories-html');
                pgo.popup.show.dropdown(e,'page',false,false);
            }
        });
        
        //Shop megadropdown
        $("#pg-shops-nav-item").click(function(e) {
            e.preventDefault();
            e.stopPropagation();
            if ($(this).hasClass('pg-selected'))
                pgo.popup.hide();
            else {
                pgo.popup.html('#pg-shops-html');
                pgo.popup.show.dropdown(e,'page',false,false);
            }
        });
    
        //RSS popup
        $("#rssToggle").click(function(e) {
            e.preventDefault();
            e.stopPropagation();
            if ($(this).hasClass('pg-selected'))
                pgo.popup.hide();
            else {
                pgo.popup.html('#rssPopup');
                pgo.popup.show.notice(e, {"margin-left": "20px"}, 'above');
            }
        });
            
        $("#pg-nav-lists-show").click(function(e) {
           e.preventDefault();
           pgo.list.lists.showManage(e);
        });
  
        $("#pg-content").delegate("a.pg-lists-add", "click", function(e) {
            e.preventDefault();
            pgo.list.product.showAdd(e);
        });
        
        //Shop info
        $("a.pg-shop-comment-link").click(function(e) {
            e.preventDefault();
            e.stopPropagation();
            var that = $(this);
            if(that.attr('title') == '') {
                that.attr('title', that.data('title'));
            } else {
                that.data('title', that.attr('title'));
            }
            
            pgo.popup.html(that.attr('title'));
            that.attr('title', '');
            pgo.popup.show.notice(e, {"margin": "6px 0 0 4px"});
        });      

        //Save amount inputbox.
        $('a.pg-list-product-quantity-save').click(function(e) {
            e.preventDefault();
            //e.stopPropagation();
            var id = $(this).attr('href').split('#amount_')[1];
            if (!id) {
                pgo.pglog("En feil har oppstått. Fant ikke antallet du ønsket å endre til.");
                return;
            }
            var quantity = $('#pg-list-quantity-box-' + id).val();
            pgo.list.product.changeQuantity(e,id,$('#listId').val(),quantity);    
            
            //var totalPrice = parseFloat($('span#pg-list-sum', content).html()) - tmpTotalPrice; //New total price for list
            //$('#pg-list-sum', content).html(totalPrice);
        });
        
        /**
        * Import old list
        */
            
        //decline
        $('#pg-import-lists-decline-link').click(function(e) {
            e.preventDefault();
            $.getJSON('/service?module=PGListImport&service=decline', function(resp) {
                if(resp.isAuthed) {
                    $('#pg-import-lists-message').remove();
                } else {
                    notice('error', 'Du må være innlogget for å utføre dette valget.', $('#pg-import-lists-message'));
                }
            });
        });
        
        //import
        $('#pg-import-lists-link').click(function(e) {
            e.preventDefault();
            
            pgo.popup.html('#pg-import-lists');
            box = pgo.popup.getBox();
            box.find('#pg-import-lists-button').click(function(e){

                var user = box.find('#pg-import-list-form-name').attr('value');
                var pass = box.find('#pg-import-list-form-password').attr('value');
                var status = 'error';
                var message = '';

                e.preventDefault();
                $.getJSON('/service?module=PGListImport&service=auth&username='+user+'&password='+pass, function(resp) {
                    if(resp.userFound) {
                        if(resp.lists > 0) {
                            //Auth successful and lists imported
                            status = 'success';
                            message = 'Vi fant ' + resp.lists + ' lister med totalt ' + resp.items + ' produkter som nå er importert.';
                        } else {
                            //Auth successful, no lists found
                            status = 'info';
                            message = 'Vi fant ingen lister på denne brukeren. Dersom du tror du kan ha en annen bruker, kan du forsøke med den.';
                        }
                    } else {
                        //Auth failed
                        status = 'error';
                        if(resp.isAuthed) {
                            message = 'Feil kombinasjon av brukernavn og passord.';    
                        } else {
                            message = 'Du må være innlogget for å kunne importere handlevogner.';
                        }
                        
                    }
                    
                    if(resp.isLimited) {
                        message = 'Du har gjort for mange mislykkede forsøk på kort tid. Vennligst forsøk igjen om 15 minutter.';
                    }
                    
                    var msg = box.find('#pg-import-lists-button');
                    box.find('.pg-notice').remove();

                    if(status == 'success') {
                        box.find('#pg-import-lists-form').remove();
                        box.find('.pg-popup-content').eq(0).prepend("<div class=\"pg-message pg-success pg-rounded-corner\">" + message + "</div>");
                        $('#pg-import-lists-message').remove();
                    } else {
                        notice(status, message, msg, 'before');
                        box.find('.pg-notice').css('left', '100px');
                    }
                    
                }); //ajax request
            }); //submit button event
            pgo.popup.toggleBG(true,'Importer lister');
            pgo.popup.show.lightbox();
        }); //yes button event

        //List delete: Product(s) or list(s).
        $(".pg-delete").click(function(e) {
            e.preventDefault();
            var listId = $("#listId").val(),
                deleteIds = [],
                mode = $(this).attr('title');
                
            //Find all checkboxes that are checked and make an array of Ids out of it
            $(".pg-shopping-list").find("input:checked").map(function() {
                deleteIds.push(
                    $(this).attr('name')
                        .replace('item[','')
                        .replace(']','')
                );
            });
            
            //What are we deleting?
            if (mode == 'products')
                pgo.list.product.remove(e,deleteIds,listId);
            else {
                //It's lists then...
                if (deleteIds.length)
                    //Delete ids based on checkboxes
                    pgo.list.lists.remove(e,deleteIds);
                else
                    //Delete the listId same as in url.
                    pgo.list.lists.remove(e,listId);
            }
        });
        
        $("#pg-content").delegate("a.pg-reviews-add", "click", function(e) {
            e.preventDefault();
            if (!pgo.auth.needAuth(e, '#add-reviews')) {
                var id = $(this).attr('id').replace('add_review_', '');
                if (location.href.match(/butikker/)) {
                    pgo.reviews.shop.show(id);
                }
                else
                    pgo.reviews.product.show(id);
            }
        });
         
        $(".pg-gravatar-link").click(function(e) {
           e.preventDefault();
           pgo.popup.html('#pg-gravatar-info');
           pgo.popup.show.notice(e);
        });
        
        $('#pg-form-new-password-button').click(function(e){
           e.preventDefault();
           $('#pg-form-new-password').submit();
        });
        
        $('#pg-form-update-profile-button').click(function(e) {
            e.preventDefault();
            pgo.profile.save(e);
        });
        
        
        //Profile->My Reviews sorting events
        
        $('#pg-reviews-nav-product').click(function(e) {
            e.preventDefault();
            $(this).addClass('pg-selected');
            $('#pg-reviews-nav-shop').removeClass('pg-selected');
            $('#pg-reviews-nav-showall').removeClass('pg-selected');
            
            $('.pg-review-product').parent('.pg-review-wrapper').each(function() {
                $(this).removeClass('pg-none');
            });
            $('.pg-review-shop').parent('.pg-review-wrapper').each(function() {
                $(this).addClass('pg-none');
            });
        });
        
        $('#pg-reviews-nav-shop').click(function(e) {
            e.preventDefault();
            $(this).addClass('pg-selected');
            $('#pg-reviews-nav-product').removeClass('pg-selected');
            $('#pg-reviews-nav-showall').removeClass('pg-selected');
            
            $('.pg-review-product').parent('.pg-review-wrapper').each(function() {
                $(this).addClass('pg-none');
            });
            $('.pg-review-shop').parent('.pg-review-wrapper').each(function() {
                $(this).removeClass('pg-none');
            });
        });
        
        $('#pg-reviews-nav-showall').click(function(e) {
            e.preventDefault();
            $(this).addClass('pg-selected');
            $('#pg-reviews-nav-shop').removeClass('pg-selected');
            $('#pg-reviews-nav-product').removeClass('pg-selected');
            
            $('.pg-review-product').parent('.pg-review-wrapper').each(function() {
                $(this).removeClass('pg-none');
            });
            $('.pg-review-shop').parent('.pg-review-wrapper').each(function() {
                $(this).removeClass('pg-none');
            });
        });
        //END Profile->My Reviews sorting events
        $("a.pg-more-proscons").one("click", function(e) {
            e.preventDefault();
            var that = $(this);
            that.parent()
                .siblings("li.pg-none").removeClass("pg-none")
                .end().remove();
        });
        // Show more reviews
        $("#pg-more-user-reviews").click(function(e) {
            e.preventDefault();
            var that = $(this);
            var data = that.attr('href').split('#')[1].split(',');
            var offset = data[1],
                pid = data[0],
                count = 20;
            // Append loading div
            var loading = $("<div class=\"pg-loading\" />");
            var type;
            if (document.URL.match(/butikker/)) type = "shop";
            else type = "product";
            
            that.before(loading);
            $.get('/service', {
                'module': 'PGReviews',
                'service': 'reviews',
                'type': type,
                'id': pid,
                'offset': offset,
                'count': count 
            }, function(resp) {
                // Put response into ul
                if (resp) {
                    var reviews = $('#pg-reviews-list');
                    $(resp).appendTo(reviews);
                    that.attr('href', '#'+pid+','+(Number(offset)+Number(count)));
                }
                else {
                    $("#pg-more-user-reviews").attr('href',pgo.safe_url);
                    $("#pg-more-user-reviews").unbind('click');
                    $("#pg-more-user-reviews").html('Ingen fler å vise. Gå til toppen');
                }
                    
                    
                loading.remove();
                // Update link
                
                //Show full review, not just truncated.
                $(".pg-review-show-full").click(function(e) {
                    e.preventDefault();
                    var id = $(this).attr('name');
                    $(this).hide();
                    $('#pg-review-short-summary-' + id).addClass('pg-none');
                    $('#pg-review-full-summary-' + id).removeClass('pg-none');
                });            
            });
        });
            
        $(".pg-review-give-thumbs").click(function(e) {
            //Add a thumbs up.
            e.preventDefault();
            $(this).html("Vennligst vent...");
            
            $.getJSON('/service', {
                'module': 'PGReviews',
                'service': 'vote',
                'id': $(this).attr('id'),
                'thumbsup': true
            }, function(resp) {
                $("#shop_review_" + resp.id).replaceWith("<span>Takk for din tilbakemelding!</span>");
                $("#shop_review_" + resp.id + "_thumbs").html(parseInt($("#shop_review_" + resp.id + "_thumbs").html()) + 1);
            });
            
            
        });
        
        //Show full review, not just truncated.
        $(".pg-review-show-full").click(function(e) {
            e.preventDefault();
            var id = $(this).attr('name');
            $(this).hide();
            $('#pg-review-short-summary-' + id).addClass('pg-none');
            $('#pg-review-full-summary-' + id).removeClass('pg-none');
        });
        
        //MY REVIEWS: Buttons
        $('.pg-review-actions .pg-review-action-edit').click(function(e) {
            e.preventDefault();
            var id = $(this).attr('href').split('#id_')[1];
            pgo.reviews.edit.load(e,id);
        });
        
        $('.pg-review-actions .pg-review-action-delete').click(function(e) {
            e.preventDefault();
            pgo.popup.html('#pg-review-actions-confirmation'); //Load delete confirmation into pgo popup. 
            
            //Set up cancel event
            $('.pg-review-action-delete-cancel').click(function(e) {
                e.preventDefault();
                pgo.popup.hide();
            });
            //Set up confirm button ID and confirm event
            var btnConfirm = $('.pg-review-action-delete-confirm');
            btnConfirm.attr('href',"#id_" + $(this).attr('href').split('#id_')[1]);
            btnConfirm.click(function(ev) {
               ev.preventDefault();
               pgo.reviews.remove(e,$(this).attr('href').split('#id_')[1]);
            });
            pgo.popup.show.notice(e);
        });
        
        $('.pg-review-actions .pg-review-action-share').click(function(e) {
            e.preventDefault();
            pgo.popup.html('Dele mulighet kommer snart.');
            pgo.popup.show.notice(e);
        });
                                  
        //END MY REVIEWS: Buttons        
        
        $('.pg-question-mark').click(function(e) {
            e.preventDefault();
            var contentId = $(this).attr('href');
            pgo.popup.html(contentId);
            pgo.popup.show.notice(e);
            
        });
        
        $('#pg-filter-form-filters').delegate('a.pg-rate-filter', 'click', function(e) {
            e.preventDefault();
            var data = $(this).attr('href').split('#')[1];
            if (!data) {
                pgo.popup.show.notice(e);
                pgo.popup.html("Beklager. En feil har oppst&aring;tt. Pr&oslash;v igjen senere.");
                pgo.popup.autohide(1500);
            }
            else {
                $.getJSON('/service?module=PGFilterRating&service=add&' + data,{},
                    function(resp) {
                        pgo.popup.show.notice(e);
                        if (resp.ok) msg = "Takk for din tilbakemelding!";
                        else msg = "Beklager. En feil har oppst&aring;tt. Pr&oslash;v igjen senere.";
                        pgo.popup.html(msg);
                        pgo.popup.autohide(1500);
                });
            }
        });
        
        // Set up search ordering links
        $('#pg-search-sort').change(function(e) {
            e.preventDefault();
            var value = $(this).val();
            if (value.match('-')) {
                value = value.split('-');
                var sort = value[0];
                var order = (value[1]) ? value[1] : "asc";
            }
            else {
                var sort = value;
                var order = "asc";
            }
            if (!sort) return;
            var filterForm = $('#pg-filter-form');
            filterForm.find("input[name=sort]").val(sort);
            filterForm.find("input[name=order]").val(order);
            filterForm.submit();
        });
        
        $('#shopListCommentSave').click(function(e) {
            e.preventDefault();
            var desc = $('#shopListComment').val();
            var listId = $(this).attr('class').replace('listId_','');
            pgo.list.changeDesc(listId, desc , e);
            
        });
        
        //Remove all empty inputboxes to prevent huuge url.
        $('#pg-filter-form').submit(function(e) {
            $(this).find('input[type=text]').map(function() {
                if (!$(this).val()) $(this).remove();
            });
        });
    }
    catch(err) {
        pgo.pglog("Error loading events: " + err);
    }
});
