/// <reference path="jquery-1.3.1-vsdoc.js" />
/// <reference path="swfobject-vsdoc.js" />
/// <reference path="sifr-vsdoc.js" />


function test()
{
 document.location = 'http://www.vg.no';
}

$(document).ready(function() {

    /*
    * FLASH DETECTION  
    * Uses jQuery for adding elements. Displays a modal dialog box over a semi-transparent background if 
    * flash version too old. 
    * 
    * Todo: Perhaps store in cookies that user has already pressed "ok" to avoid showing message on every load.
    */
    /*
    if (!swfobject.hasFlashPlayerVersion("9.0.0")) {
    var message = "<b>Flash Player 9 required</b><br />This site requires flash player 9.0.0 or newer. Please <a href='http://www.adobe.com/products/flashplayer/'>download here</a><br/><br/><input type=\"button\" style=\"float:right\" onclick=\"JavaScript:$('#__flashversion').remove();\" value=\"OK\" />";
    var bgcolor = "#FFFFFF";    // color of background
    var msg_width = "200";      // pixels
    var msg_height = "80";      // pixels
    var opacity = 80;           // background per cent visible

    $("body").append("<div id='__flashversion'></div>");
    var flash = $("#__flashversion");
    flash.append("<div id='__flashversion_bg' style=\"position:absolute;background:" + bgcolor + ";-khtml-opacity:." + opacity + "; -moz-opacity:." + opacity + "; -ms-filter:'alpha(opacity=" + opacity + ")'; filter:alpha(opacity=" + opacity + "); opacity:." + opacity + ";left:0;top:0;width:100%;height:100%;\"></div>");
    flash.append("<div style='position:absolute;margin-left:-" + (msg_width / 2) + "px;margin-top:-" + (msg_height / 2) + "px;background:" + bgcolor + ";width:" + msg_width + "px;height:" + msg_height + "px;left:50%;top:50%;padding:20px;text-align:left;border:1px solid #aaaaaa;'>" + message + "</div>");
    }
    */

	// only replace if we have correct version of flash player
	if (swfobject.hasFlashPlayerVersion("9.0.0")) {
		// attach flash version of About-document's menu
		var att = { data: "swf/DocMenu.swf", width: "876", height: "61" };
		var par = { wmode: "transparent", flashvars: "css=DocMenu.css&menu=" + menu };
		var myObject = swfobject.createSWF(att, par, "doc-menu-about");

		// attach flash version of Menu-Top
		var att = { data: "swf/MenuTop.swf", width: "722", height: "61" };
		var par = { wmode: "transparent", flashvars: "css=MenuTop.css&menu=" + menu };
		var myObject = swfobject.createSWF(att, par, "menu-top-inner");
	}

    // used inside c_faq to send wap push links to faq entries
    $(".wap-push-faq").bind("click", function(e) {
        var thisdate = new Date();
        e.preventDefault();
        var id = $(this).attr("alt");
        $.nyroModalManual({
            url: 'c_sms_send.aspx?text=' + escape('www.comfort.no/c_faq_m_single.aspx?id=' + id) + '&type=push&linktext=' + escape("Link til spørsmål og svar hos Comfort.no") + '&time=' + escape(thisdate),
            endShowContent: afterSMS,
            minWidth: 300,
            minHeight: 150,
            showContent: showContent,
            hideContent: hideContent
        });
        return false;

    });

    // attaches to all a tags that have class icon-send-sms
    $(".icon-send-sms").bind("click", function(e) {
        var thisdate = new Date();
        e.preventDefault();
        var text = $(this).attr("alt");
        var type = "sms";
        if ($(this).attr("type") != undefined) type = $(this).attr("type");
        $.nyroModalManual({
            url: 'c_sms_send.aspx?text=' + text + '&type=' + type + '&time=' + escape(thisdate),
            endShowContent: afterSMS,
            minWidth: 300,
            minHeight: 150,
            showContent: showContent,
            hideContent: hideContent
        });
        return false;

    });



    function afterSMS() {
        runAjaxDoneFunction("SMS");
    }
    // style custom form elements ---------------------------------------------------------------------------------------------

    // input boxes of type select ---------------------------------------------------------------------------------------------
    $("select").each(function(i) {
        customSelect($(this));
    });

    function customSelect(obj) {
        $(obj).wrap("<div class='cust-select-container'></div>");

        // width of select box
        var width = $(obj).width() - 32; // 32 is width of .start and .end
        var maxHeight = 150; // max height of drop down element of box

        // this is the hidden box that takes over the place of the select box
        $(obj).parent().append("<input type='hidden' name='" + $(obj).attr("name") + "' value='" + $(obj).val() + "' />");

        $(obj).parent().append("<div class=\"start\">&#160;</div>");
        $(obj).parent().append("<div class=\"mid\"><div style='width:" + width + "px'>" + $(obj).find("option[selected]").text() + "</div></div>");
        $(obj).parent().append("<div class=\"end\">&#160;</div>");

        // calculate height of drop down element
        var totHeight = $(obj).find("option").size() * 24; totHeight -= 2;
        var height = totHeight;
        if (height <= maxHeight) width += 13;
        if (height > 150) height = maxHeight;

        $(obj).parent().append("<ul style=\"width:" + (width + 28) + "px;height:" + height + "px;\">");

        var ul = $(obj).parent().find("ul");
        var len = $(obj).find("option").size();


        // for each option, add a li
        $(obj).find("option").each(function(i) {

            var li = $(ul).append("<li alt='" + $(this).val() + "'><div>" + $(this).text() + "</div></li>");

            if ($(this).attr("selected") == true) $(ul).find("li:last").addClass("selected");

            $(ul).find("li").hover(function() {
                $(this).addClass("focus");
            }, function() {
                $(this).removeClass("focus");
            });

        });
        $(ul).find("li:last").addClass("last");


        $(obj).parent().append("</ul>");
        $(obj).parent().append("</div>");

        $(ul).wrap("<div class=\"scroll\"></div>");

        // custom scrollpane
        if (totHeight > maxHeight) {
            $(ul).jScrollPane({
                showArrows: true,
                scrollbarWidth: 13
            });
        } else {
            $(obj).parent().find("ul").wrap("<div></div>");
            $(obj).parent().find(".scroll").addClass("scroll-alone");
        }

        $(obj).parent().find("div.scroll").css("display", "none");

        // show on click
        $(obj).parent().find('.start,.mid,.end').bind('click', function(event) {
            // stop click on body from stopping this action
            event.stopPropagation();

            // hide any other that are visible
            $(".cust-select-container .scroll").each(function() {
                if ($(this).css("display") == "block") {
                    var s = $(this).parent().find("div.scroll");
                    s.fadeOut("fast");
                    cust_select_hide($(this).parent());
                }
            });

            // show me
            var s = $(this).parent().find("div.scroll");
            if (s.css("display") != "block") {
                s.fadeIn("fast");
                cust_select_show($(this).parent());
            }
            else {
                s.fadeOut("fast");
                cust_select_hide($(this).parent());
            }
        })

        // hide on blur
        $("body").bind('click', function() {
            var s = $(this).find("div.scroll").fadeOut("fast");
            $(".cust-select-container").each(function() {
                cust_select_hide($(this));
            });
        })

        // don't hide when click on dragbar or buttons
        $(".jScrollPaneTrack, .jScrollPaneDrag, .jScrollArrowUp, .jScrollArrowDown").bind('click', function(event) {
            event.stopPropagation();
        })

        // select value and hide on li click
        $(ul).find("li").bind('click', function() {

            var orig = $(this).parent().parent().parent().parent();

            // set hidden value
            $(orig).find("input").setValue($(this).attr("alt"));

            // set visible text value
            $(orig).find(".mid div").html($(this).text());

            // hide dropped down elements
            var s = $(this).find("div.scroll").fadeOut("fast");

            // broadcast event
            $(orig).find("input").trigger("updatehidden", $(this).attr("alt"));
        });

        // fix width
        $(ul).css("width", width + 15);

        // in the end, delete select box
        $(obj).remove();
    }

    // set obj over all other select boxes
    function cust_select_show(obj) {
        $(obj).css("z-index", "10");
    }
    function cust_select_hide(obj) {
        $(obj).css("z-index", "1");
    }


    // input boxes of type text -------------------------------------------------------------------------------------------
    $("input[type='text']").each(function(i) {

        // base class
        var base = "cust-text";
        if ($(this).hasClass("cust-text-search")) base = "cust-text-search";
        if ($(this).hasClass("cust-text-search-black")) base = "cust-text-search-black";

        // wrap in html
        $(this).wrap("<div class=\"mid\"></div>").parent().wrap("<div class='" + base + "-container'></div>");
        var cust = $(this).parent().parent();
        $(cust).prepend("<div class=\"start\">&#160;</div>");
        $(cust).find(".mid").after("<div class=\"end\">&#160;</div>");

        // correct width
        $(cust).find("input").width($(cust).find("input").width() - 40);

        // bind focus and blur
        $(cust).find("input").bind(
            'focus',
            function() {
                $(this).parent().parent().addClass(base + "-container-focus");
                return false;
            }
        )
        $(cust).find("input").bind(
            'blur',
            function() {
                $(this).parent().parent().removeClass(base + "-container-focus");
                return false;
            }
        )
    });

    // input boxes of type textarea -----------------------------------------------------------------------------------------
    $("textarea").each(function(i) {

        // base class
        var base = "cust-textarea";

        // wrap in html
        $(this).wrap("<div class=\"mid\"></div>").parent().wrap("<div class='" + base + "-container'></div>");
        var cust = $(this).parent().parent();
        $(cust).prepend("<div class=\"start\">&#160;</div>");
        $(cust).find(".mid").after("<div class=\"end\">&#160;</div>");
        $(cust).find(".end").after("<div class=\"clearer\">&#160;</div>");

        // correct width
        $(cust).find("input").width($(cust).find("input").width() - 40);

        // bind focus and blur
        $(cust).find("textarea").bind(
            'focus',
            function() {
                $(this).parent().parent().addClass(base + "-container-focus");
                return false;
            }
        )
        $(cust).find("textarea").bind(
            'blur',
            function() {
                $(this).parent().parent().removeClass(base + "-container-focus");
                return false;
            }
        )
    });

    // input boxes of type checkboxes ----------------------------------------------------------------------------------------
    $("input[type='checkbox']").custCheckBox({ wrapperclass: "checkbox-container" });

    // submit and button -----------------------------------------------------------------------------------------------------
    $("input[type='submit'], input[type='button']").each(function(i) {

        // base class
        var base = "cust-button";
        if ($(this).hasClass("cust-button-black")) base = "cust-button-black"

        // hide button
        $(this).css({ position: 'absolute', top: '-2000px' });

        // add class so we'll find the button again
        $(this).addClass(base + "-replaced");

        // make id
        var id = "custom_button" + i;

        // add wrapper for custom_button
        $(this).wrap("<span class='" + base + "' id='" + id + "'><div class='" + base + "-left'></div><div class='" + base + "-mid'>" + $(this).attr("value") + "</div><div class='" + base + "-right'></div></span>");
        var bt = $(this).parent().parent();

        // hover
        $(bt).hover(function() {
            $(this).addClass(base + "-hover");
        },
        function() {
            $(this).removeClass(base + "-hover");
        });

        // click handler. trigger click/submit on button
        var f = this.form;
        if ($(this).attr("type") == "submit") {
            $(bt).bind(
                'click',
                function() {
                    try {
                        // if validate_submit() exists, we run it. Else we just submit form.
                        validate_submit()
                    }
                    catch (a) {
                        $(f).trigger("submit");
                    }
                    return false;
                }
            )
        } else {
            $("#" + id).bind(
                'click',
                function() {
                    $(this).find("." + base + "-replaced").trigger('click');
                    return false;
                }
            )
        }

    });

    // fix line under images with a href
    $("a>img").each(function() {
        $(this).parent().css("border", "none");
    });


    // Replace images on default document with alt overlay
    $(".image-left-container img").each(function() {
        if ($(this).attr("alt")) {
            $(this).wrap("<div class='outer'></div>");
            $(this).parent().append("<div class='overlay image-text'>" + $(this).attr("alt") + "</div>");
        }
    });
    $(".image-left-container img:last").css("margin-top", "16px");

    // Bli inspirert flash
    $(window).bind('resize', WindowResize);
    WindowResize();

    // General accordion used throughout the site ----------------------------------------------------------------------------
    $(".cust-accordion").each(function(i) {

        // loop both levels and get hold of original height and then resize
        $(this).parent().find(".cust-accordion>li").each(function() {
            
            $(this).find(">ul>li").each(function() {

                // store original height on level 2 header
                $(this).find("h4").attr("orig_height", $(this).find("h4").height());

                // store original height on level 2.
                // however, if has class expanded, we're not supposed to expand level 2. It's always expanded
                $(this).attr("orig_height", $(this).height());
                if (!$(this).hasClass("expanded")) {
                    $(this).css("height", "38px");

                    // then hide read more part of the header
                    $(this).find(".more-indicator").css("display", "inline");
                    $(this).find(".more").css("display", "none");
                }
                else {
                    $(this).find(".more-indicator").css("display", "none");
                    $(this).find(".more").css("display", "inline");
                }

            });

            // store original height on level 1
            // however, if has class expanded, we're not supposed to expand level 1. It's always expanded
            $(this).attr("orig_height", $(this).height());
            if (!$(this).hasClass("expanded")) {
                $(this).css("height", "36px");
            }


        });

        // toggle show/hide contents on level 1
        $(this).find("li h3 a").bind('click', function() {

            // fetch object
            var li = $(this).parent().parent();
            //$(this).css("cursor", "default");
            //$(this).append($(li).attr("orig_height"));

            //if (!li.hasClass("expanded")) {

            // expand or contract?
            if ($(li).css("height") == "36px") {

                // expand
                $(li).addClass("focus");
                $(li).animate({ height: $(li).attr("orig_height") }, 400, "swing");
            }
            else {

                // contract
                $(li).removeClass("focus");
                $(li).animate({ height: "36px" }, 400, "swing");

                // contract all children that are expanded
                $(this).parent().parent().find("ul>li").each(function() {
                    //alert("yo");
                    if ($(this).hasClass("focus")) {
                        $(this).find("h4>a").click();
                    }
                });
            }
            // }

            // don't follow href
            return false;
        });

        // toggle show/hide contents on level 2
        $(this).find("li>ul>li>h4>a").bind('click', function() {

            // fetch object
            var li = $(this).parent().parent();

            if (!li.hasClass("expanded")) {

                // expand or contract?
                if ($(li).css("height") == "38px") {

                    // expand level 2
                    $(li).addClass("focus");
                    $(li).animate({ height: $(li).attr("orig_height") }, 400, "swing");

                    // also expand header
                    var headerHeight = $(li).find("h4").attr("orig_height") - 38;
                    $(li).find("h4").animate({ height: 38 + headerHeight }, 400, "swing");

                    // fade in rest of header
                    $(li).find("h4>a>.more-indicator").fadeOut(50);
                    $(li).find("h4>a>.more").fadeIn(200);

                    // also expand level 1 by adding height
                    var addHeight = $(li).attr("orig_height") - 38;
                    var parent = $(li).parent().parent();
                    $(parent).animate({ height: $(parent).height() + addHeight + headerHeight }, 400, "swing");
                }
                else {

                    // contract level 2
                    $(li).removeClass("focus");
                    $(li).animate({ height: "38px" }, 400, "swing");

                    // also contract header
                    var headerHeight = $(li).find("h4").attr("orig_height") - 38;
                    $(li).find("h4").animate({ height: 38 }, 400, "swing", function() { $(this).attr("style", "") });

                    // fade out rest of header
                    $(li).find("h4>a>.more-indicator").fadeIn(50);
                    $(li).find("h4>a>.more").fadeOut(200);

                    // also contract level 1 by removing height
                    var removeHeight = $(li).attr("orig_height") - 38;
                    var parent = $(li).parent().parent();
                    if ($(parent).hasClass("focus")) {
                        $(parent).animate({ height: $(parent).height() - removeHeight - headerHeight }, 400, "swing");
                    }
                }
            }

            // don't follow href
            return false;
        });
    });

    // special behavior on county select box on c_storeoverview
    $("#county input[type='hidden']").each(function(i) {

        $(this).bind("updatehidden", function(a) {

            var county = $(this).val();
            $.ajax({
                type: "POST",
                url: "c_storeoverview_city.aspx",
                data: "county=" + county,
                success: function(result) {
                    $("#city").html(result);
                    customSelect($("#city select"));
                }
            });

        });
    });

    // when we click the different "add to mermo" buttons, fade them out a bit to indicate action.
    $(".icon-add-to-memero").bind("click", function() {
        $(this).fadeTo(250, 0.5);
    });


    // checkboxes with id category-all resets other checkboxes
    $("#category-all").parent().bind("click", function() {
        // iterate through all checkboxes on same level
        if ($(this).find("input[type='checkbox']").attr("checked") == true) {
            $(this).parent().find("input[type='checkbox'].custom").each(function() {
                $(this).parent().find("span").removeClass("cust-checkbox-on").addClass("cust-checkbox-off");
                $(this).attr("checked", false);
            });
        }
    });

    // all the other checkboxes reset the "category-all" checkbox
    $("input[type='checkbox'].custom").parent().bind("click", function() {
        // reset "category-all"
        if ($(this).find("input[type='checkbox']").attr("checked") == true) {
            $("#category-all").each(function() {
                $(this).parent().find("span").removeClass("cust-checkbox-on").addClass("cust-checkbox-off");
                $(this).attr("checked", false);
            });
        }
    });

});


// Used for resizing of window ----------------------------------------------------------------------------------------------
function WindowResize() {
    
    // bli inspirert and comforthjemmet
    var h = $(window).height() - 100;
    if (h < 650) h = 650;
    $('#icontainer').height(h);
   
}

// SIFR Flash Text ----------------------------------------------------------------------------------------------------------

    // replace different tags with flash version (using the fantastic sifr 3)
    var stagBookItalic = { src: 'swf/StagBookItalic.swf' };
    var stagLightItalic = { src: 'swf/StagLightItalic.swf' };
    //sIFR.useDomLoaded = false;
    sIFR.domains = ['*'];
    sIFR.activate(stagBookItalic, stagLightItalic);


    // h1 tags on doc-productsearch
    sIFR.replace(stagLightItalic, {
        selector: '.doc-productsearch h1',
        css: [
                '.sIFR-root { color: #f0f0f0; font-size:30; }',
                'a { text-decoration: underline; }',
                'a:link { color: #f0f0f0; }',
                'a:hover { color: #f0f0f0; }'
            ],
        transparent: true,
        tuneWidth: 10,
        antiAliasType: 'advanced',
        thickness:-140,
        sharpness:-120
    });
    
    // replace ingress tags
    sIFR.replace(stagLightItalic, {
        selector: 'p.ingress',
        css: [
                '.sIFR-root { color: #4a5a5e; font-size:18; leading:3 }',
                'a { text-decoration: underline; }',
                'a:link { color: #ed1c24; text-decoration: underline;}',
                'a:hover { color: #ed1c24; text-decoration: underline;}'                
            ],
        transparent: true,
        antiAliasType: 'advanced'
    });

    // replace white ingress tags
    sIFR.replace(stagLightItalic, {
        selector: 'p.ingress-white, .doc-speak-start h2',
        css: [
                '.sIFR-root { color: #FFFFFF; font-size:18; leading:3 }'
            ],
        transparent: true,
        antiAliasType: 'advanced',
        thickness: -140,
        sharpness: -120
    });    

    // h1 tags on doc-about
    sIFR.replace(stagLightItalic, {
        selector: '.doc-about h1, .doc-comforthome h1',
        css: [
                '.sIFR-root { color: #f0f0f0; font-size:30; }',
                'a { text-decoration: underline; }',
                'a:link { color: #f0f0f0; }',
                'a:hover { color: #f0f0f0; }'
            ],
        transparent: true,
        antiAliasType: 'advanced',
        thickness: -140,
        sharpness: -120
    });
    
    // h1 tags on search result
    sIFR.replace(stagLightItalic, {
        selector: '.doc-storeoverview h1',
        css: [
                '.sIFR-root { color: #f0f0f0; font-size:30; }',
                'a { text-decoration: underline; }',
                'a:link { color: #f0f0f0; }',
                'a:hover { color: #f0f0f0; }'
            ],
        transparent: true,
        antiAliasType: 'advanced',
        thickness: -140,
        sharpness: -120,
        preventWrap: true,
        offsetLeft:-2
    });    

    /* C_STOREOVERVIEW */
    
    // h2 tags
    sIFR.replace(stagBookItalic, {
        selector: '.box-filter h2',
        css: [
                '.sIFR-root { color: #393939; font-size:18; leading:3 }'
            ],
        transparent: true,
        antiAliasType: 'advanced'
    });

    /* doc_speak_start.xsl */

    // h2 tags on ask box
    sIFR.replace(stagLightItalic, {
        selector: '.ask-box h2',  
        css: [
                '.sIFR-root { color: #FFFFFF; font-size:24; leading:3 }'
            ],
        transparent: true,
        antiAliasType: 'advanced',
        thickness: -140,
        sharpness: -120
    });

	// h2 tags on heating-environment-box
    sIFR.replace(stagLightItalic, {
        selector: '.heating-environment-box h2',  
        css: [
                '.sIFR-root { color: #FFFFFF; font-size:24; leading:3 }'
            ],
        transparent: true,
        antiAliasType: 'advanced',
        thickness: -140,
        sharpness: -120
    });
	
	// heating-environment-box middle
    sIFR.replace(stagLightItalic, {
        selector: '.heating-environment-box .spacer-text',  
        css: [
                '.sIFR-root { color: #515457; font-size:16; leading:3;text-align:center; }'
            ],
        transparent: true,
        antiAliasType: 'advanced',
        thickness: -140,
        sharpness: -120
    });

	// heating-environment-box success text
    sIFR.replace(stagBookItalic, {
        selector: '.heating-environment-box .heating-environment-success',  
        css: [
                '.sIFR-root { color: #6a6c6f; font-size:12px; text-align:left; line-height:14px; }'
            ],
        transparent: true,
        antiAliasType: 'advanced'
				
    });

			

	// 
	sIFR.replace(stagLightItalic, {
        selector: '.doc-heating-environment h2',
        css: [
                '.sIFR-root { color: #FFFFFF; font-size:18; leading:3 }'
            ],
        transparent: true,
        antiAliasType: 'advanced',
        thickness: -140,
        sharpness: -120
    });   


    // h3 tag on search-box
    sIFR.replace(stagBookItalic, {
        selector: '.search-params h6',
        css: [
                '.sIFR-root { color: #393939; font-size:14; leading:3 }'
            ],
        transparent: true,
        antiAliasType: 'advanced',
        thickness: -140,
        sharpness: -120
    });    

    // h3 tags on ask box and search box
    sIFR.replace(stagBookItalic, {
        selector: '.ask-left h3, .ask-right h3, .doc-search .box-grey-thin .part h3',
        css: [
                '.sIFR-root { color: #393939; font-size:18; leading:3 }',
                '.red { color: #ed1c24; }',
                'strong { font-weight:bold; }'    
            ],
        transparent: true,
        antiAliasType: 'advanced',
        thickness: -140,
        sharpness: -120
    });

    // h6 tags on product search box
    sIFR.replace(stagBookItalic, {
        selector: '.search-params table h3',
        css: [
                '.sIFR-root { color: #393939; font-size:14; leading:3 }',
                '.red { color: #ed1c24; }',
                'strong { font-weight:bold; }'
            ],
        transparent: true,
        antiAliasType: 'advanced',
        thickness: -140,
        sharpness: -120
    });


	// h2 tags on shopdetails-box
    sIFR.replace(stagLightItalic, {
        selector: '.store-details-box h2',  
        css: [
                '.sIFR-root { color: #FFFFFF; font-size:18; leading:3 }',
                'a { text-decoration: underline; }',
                'a:link { color: #ed1c24; text-decoration: underline;}',
                'a:hover { color: #ed1c24; text-decoration: underline;}'                
            ],
        transparent: true,
        antiAliasType: 'advanced',
        thickness: -140,
        sharpness: -120
    });



	sIFR.replace(stagLightItalic, {
        selector: '.storedetails-left h2',
        css: [
                '.sIFR-root { color: #5c5c5c; font-size:21; leading:3 }',
                'a { text-decoration: underline; }',
                'a:link { color: #ed1c24; text-decoration: underline;}',
                'a:hover { color: #ed1c24; text-decoration: underline;}'                
            ],
        transparent: true,
        antiAliasType: 'advanced'
    });   

	// 
	sIFR.replace(stagLightItalic, {
        selector: '.storedetails-articles',
        css: [
                '.sIFR-root { color: #FFFFFF; font-size:18; leading:3 }'
            ],
        transparent: true,
        antiAliasType: 'advanced',
        thickness: -140,
        sharpness: -120
    });   


// Function to run after modal box load. -----------------------------------------------------------------------------------
    
	function runAjaxDoneFunction(mode)
	{
	    $(document).ready(function() {

	        // repos and resize scrollbar
	        ActivateScrollbarCallback();

	        // h1 tags as flash text
	        sIFR.replace(stagBookItalic, {
	            selector: '#mermowrapper h1',
	            css: [
		                '.sIFR-root { color: #FFFFFF; font-size:24;  }'
		             ],
	            transparent: true,
	            antiAliasType: 'advanced',
	            thickness: -140,
	            sharpness: -120
	        });

	        // h1 tags as flash text
	        sIFR.replace(stagBookItalic, {
	            selector: '.modal-header h1',
	            css: [
		                '.sIFR-root { color: #FFFFFF; font-size:24;  }'
		             ],
	            transparent: true,
	            antiAliasType: 'advanced',
	            thickness: -140,
	            sharpness: -120
	        });

	        var thisdate = new Date();

	        // activate custom text boxes and input boxes
	        $("#mermowrapper input[type='text'], #MermoSavePanel input[type='text']").each(function(i) {

	            // base class
	            var base = "cust-text";
	            if ($(this).hasClass("cust-text-search")) base = "cust-text-search";
	            if ($(this).hasClass("cust-text-search-black")) base = "cust-text-search-black";

	            // wrap in html
	            $(this).wrap("<div class=\"mid\"></div>").parent().wrap("<div class='" + base + "-container'></div>");
	            var cust = $(this).parent().parent();
	            $(cust).prepend("<div class=\"start\">&#160;</div>");
	            $(cust).find(".mid").after("<div class=\"end\">&#160;</div>");

	            // correct width
	            $(cust).find("input").width($(cust).find("input").width() - 40);

	            // bind focus and blur
	            $(cust).find("input").bind(
                'focus',
                function() {
                    $(this).parent().parent().addClass(base + "-container-focus");
                    return false;
                })
	            $(cust).find("input").bind(
                    'blur',
                    function() {
                        $(this).parent().parent().removeClass(base + "-container-focus");
                        return false;
                    }
                )
	        });

	        // submit and button -----------------------------------------------------------------------------------------------------
	        $("#mermowrapper input[type='submit'], #mermowrapper input[type='button'],#MermoSavePanel input[type='submit'], #MermoSavePanel input[type='button']").each(function(i) {

	            // base class
	            var base = "cust-button";
	            if ($(this).hasClass("cust-button-black")) base = "cust-button-black"

	            // hide button
	            $(this).css({ position: 'absolute', top: '-2000px' });

	            // add class so we'll find the button again
	            $(this).addClass(base + "-replaced");

	            // make id
	            var id = "custom_button" + i;

	            // add wrapper for custom_button
	            $(this).wrap("<span class='" + base + "' id='" + id + "'><div class='" + base + "-left'></div><div class='" + base + "-mid'>" + $(this).attr("value") + "</div><div class='" + base + "-right'></div></span>");
	            var bt = $(this).parent().parent();

	            // hover
	            $(bt).hover(function() {
	                $(this).addClass(base + "-hover");
	            },
                function() {
                    $(this).removeClass(base + "-hover");
                });

	            // silly handler for send sms
	            $(bt).bind(
                    'click',
                    function() {
                        if ($(this).find("input").hasClass("SaveSendEmail")) SaveSendEmail();
                        if ($(this).find("input").hasClass("SaveSendSMS")) SaveSendSMS();
                        if ($(this).find("input").hasClass("SendGeneralSMS")) SendGeneralSMS();
                        return false;
                    }
                )


	        });

	        function SendGeneralSMS() {
	            $("#second-modal-bg").fadeOut("fast");
	            $("#MermoSavePanel").fadeOut("fast");

	            $.ajax({
	                type: "GET",
	                url: "c_sms_send.aspx",
	                data: "cmd=SEND&mobile=" + $("#MermoPhone").val() + "&linktext=" + escape($("#MermoPhoneLinkText").val()) + "&type=" + $("#MermoPhoneType").val() + "&text=" + escape($("#MermoPhoneText").val()) + "&time=" + escape(thisdate),
	                success: function(result) {
	                    $("#sms_send").fadeOut("fast");
	                    $("#sms_sent").fadeIn("fast");
	                }
	            });
	        }

	        // activate remove buttons
	        $(".mermoRemoveButton").each(function() {
	            $(this).bind('click', function() {
	                RemoveFromMermo($(this).attr('docid'), $(this).attr('doctype'));
	            });
	        });


	        // add clickevent to email button
	        $("#btnActivateEmailSave").bind('click', function() {

	            $("#second-modal-bg").fadeIn("fast");
	            $("#MermoSavePanel").fadeIn("fast");

	            $("#SMSArea").fadeOut("fast");
	            $("#EmailArea").fadeIn("fast");

	            sIFR.replace(stagBookItalic, {
	                selector: '.mermo_header h1',
	                css: [
			            '.sIFR-root { color: #d2d2d2; font-size:24; font-weight:normal; }'
			        ],
	                transparent: true,
	                antiAliasType: 'advanced',
	                thickness: -140,
	                sharpness: -120
	            });

	        });

	        // add clickevent to sms button
	        $("#btnActivateSMSSave").bind('click', function() {

	            $("#second-modal-bg").fadeIn("fast");
	            $("#MermoSavePanel").fadeIn("fast");

	            $("#SMSArea").fadeIn("fast");
	            $("#EmailArea").fadeOut("fast");

	            sIFR.replace(stagBookItalic, {
	                selector: '.mermo_header h1',
	                css: [
			            '.sIFR-root { color: #d2d2d2; font-size:24; font-weight:normal;  }'
			            ],
	                transparent: true,
	                antiAliasType: 'advanced',
	                thickness: -140,
	                sharpness: -120
	            });

	        });

	        // add clickevent to close button on sms and email input box
	        $(".MermoSavePanelClose").bind('click', function() {
	            $("#second-modal-bg").fadeOut("fast");
	            $("#MermoSavePanel").fadeOut("fast");
	        });

	        // add clickevent to sms send button
	        function SaveSendSMS() {

	            $("#second-modal-bg").fadeOut("fast");
	            $("#MermoSavePanel").fadeOut("fast");

	            $("#MermoControlPanelAjaxMessages").load("Mermo.aspx?action=save&phone=" + $("#saveMermoFormPhone").val() + "&time=" + escape(thisdate), function() {
	                $("#MermoControlPanelAjaxMessages .ok").animate({ backgroundColor: '#8dff6a' }, 50).animate({ backgroundColor: '#8dff6a' }, 500).animate({ backgroundColor: '#FFF' }, 3000);
	                $("#MermoControlPanelAjaxMessages .error").animate({ backgroundColor: 'Red' }, 50).animate({ backgroundColor: 'Red' }, 500).animate({ backgroundColor: '#FFF' }, 3000);
	            });

	        }

	        // add clickevent to email send button
	        function SaveSendEmail() {

	            $("#second-modal-bg").fadeOut("fast");
	            $("#MermoSavePanel").fadeOut("fast");


	            $("#MermoControlPanelAjaxMessages").load("Mermo.aspx?action=email&email=" + $("#saveMermoFormEmail").val() + "&time=" + escape(thisdate), function() {
	                $("#MermoControlPanelAjaxMessages .ok").animate({ backgroundColor: '#8dff6a' }, 50).animate({ backgroundColor: '#8dff6a' }, 500).animate({ backgroundColor: '#FFF' }, 3000);
	                $("#MermoControlPanelAjaxMessages .error").animate({ backgroundColor: 'Red' }, 50).animate({ backgroundColor: 'Red' }, 500).animate({ backgroundColor: '#FFF' }, 3000);
	            });

	        };

	        // override box width for mermo.
	        if (mode == "mermo") {
	            $(".jScrollPaneContainer").css("width", "auto");
	            // $(".mermo_accordion").css("width", "100%"); // 707px
	            //$("#nyroModalWrapper").css("width", "745px");
	            //$("#mermowrapper").css("width", "725px");
	            //$(".mermoscroll").css("width", "725px");
	        }

	        $("#mermowrapper .cust-accordion").each(function(i) {

	            // loop both levels and get hold of original height and then resize
	            $(this).find(">li").each(function() {

	                // store original height on level 1
	                $(this).attr("orig_height", $(this).height());
	                $(this).css("height", "36px");

	            });

	            // toggle show/hide contents on level 1
	            $(this).find("li h3 a").bind('click', function() {

	                // fetch object
	                var li = $(this).parent().parent();

	                // expand or contract?
	                if ($(li).css("height") == "36px") {

	                    // expand
	                    $(li).addClass("focus");
	                    $(li).animate({ height: $(li).attr("orig_height") }, 400, "swing", ActivateScrollbarCallback);

	                }
	                else {

	                    // contract
	                    $(li).removeClass("focus");
	                    $(li).animate({ height: "36px" }, 400, "swing", ActivateScrollbarCallback);

	                }

	                // don't follow href
	                return false;
	            });
	        });

	        // fix width of mermo's .. err whatever they're called
	        ActivateScrollbarCallback();
 
	    });

	}
	
	
	
	// Function used as callback after accordian is toggled
	function ActivateScrollbarCallback()
	{
		$('.mermo_accordion').jScrollPane({showArrows: true, scrollbarWidth: 13,maintainPosition: true});
	}
	
	function RemoveFromMermo(id, type, url)
	{

		$('#ajaxLoadContainer').load("mermo.aspx?action=remove&id=" + id + "&type=" + type);
		$('#li_' + type + '_' + id).animate({height: "0px"}, 400, "swing");
	}
	
//	function AddToMermo(id, type)
//	{
//		var thisdate = new Date();
//		$('#ajaxLoadContainer').load("mermo.aspx?action=add&id=" + id + "&type=" + type + "&time=" + escape(thisdate) );
//	  
//	
//		var style = {};
//		style["background-color"] = "#Df1D32";  
//		$("#huskeliste").animate(style, 400);
//		style["background-color"] = "White"; 
//		$('#huskeliste').animate(style, 400);
//	  
//	}
//	
	function AddToMermo(id, type, title, subtitle, imageUrl, visitUrl) {
	    switch (type) {
	        case "Product":
	            type = 0;
	            break;
	        case "Inspired":
	            type = 1;
	            break;
	        case "FAQ":
	            type = 2;
	            break;
	        case "Shop":
	            type = 3;
	            break;
	        case "Comforthome":
	            type = 4;
	            break;
	    }
	    var thisdate = new Date();
	    var url = "mermo.aspx?action=add&id=" + id + "&type=" + type
	    if (title != undefined) url += "&title=" + escape(title);
	    if (subtitle != undefined) url += "&subtitle=" + escape(subtitle);
	    if (imageUrl != undefined) url += "&imageUrl=" + escape(imageUrl);
	    if (visitUrl != undefined) url += "&visitUrl=" + escape(visitUrl);
	    url += "&time=" + escape(thisdate);
	    
		$('#ajaxLoadContainer').load(url);
		
		$("#huskeliste").parent().animate( { backgroundColor: '#ed1c24' }, 50).animate( { backgroundColor: '#FFF' }, 200).animate( { backgroundColor: '#ed1c24' }, 50).animate( { backgroundColor: '#FFF' }, 200);

	}
	
	// Function to activate modal box on "huskeliste"-click
	$(function() {

			$('#huskeliste').click(function(e) {
			    var thisdate = new Date();
			    e.preventDefault();
			    $.nyroModalManual({
			        url: 'Mermo.aspx?time=' + thisdate,
			        endShowContent: afterMermo,
			        minWidth: 755,
			        minHeight: 480,
			        showContent:showContent,
			        hideContent:hideContent
			    });
			    return false;
			});

	});
    
    // helps nyromodal behave the way we want
	function showContent(elts, settings, callback) {
	    elts.contentWrapper
        .css({ // Reset the CSS at the start position
            marginTop: (settings.marginTop) + 'px',
            marginLeft: (settings.marginLeft) + 'px',
            height: (settings.height) + 'px',
            width: (settings.width) + 'px',
            opacity: 0
        })
        .show()
        .animate({ // Set the height
            opacity: 0
        }, { complete: callback, duration: 1 })       
        .animate({ // Set the height
            opacity: 1
        }, { duration: 300 });
    }


    function hideContent(elts, settings, callback) {
        elts.contentWrapper
        .animate({ // Set the height
            opacity: 0
        }, { complete: callback, duration: 300 })
    }		


	// huskeliste call from flash
	function DisplayMermo() {
	    var thisdate = new Date();

	     $.nyroModalManual({
	        url: 'Mermo.aspx?time=' + thisdate,
	        endShowContent: afterMermo,
	        minWidth: 700,
	        minHeight: 480,
	        showContent: showContent,
	        hideContent: hideContent
	    });
	}

	function afterMermo() {
	    runAjaxDoneFunction("mermo");
	}


    /* Google Maps integration -------------------------------------------------------------------------------------- */
    function AttachGMap(address, infobox, id, form_id) {

        var geocoder = null;
        var map = null;

        if (GBrowserIsCompatible()) {
            map = new GMap2(document.getElementById(id));

            // Add marker for store address
            var geocoder = new GClientGeocoder();
            var point = geocoder.getLatLng(address, function(point) {

                if (!point) {
                    //alert(address + " not found");
                    // address not found, make maps invisible
                    $("#" + id).css("background", "#fff");
                    
                } else {
                    var marker0 = new GMarker(point);
                    marker0.title = "Adressen til trallallallaaa";
                    map.addOverlay(marker0);
                    map.setCenter(point, 13);
                    GEvent.addListener(marker0, "click", function() {
                        // submit to maps.google.no
                        document.getElementById(form_id).submit();
                    });
                }
            });
        }

        // hide copyrightinfo on the bottom. I did this because it was too big and went outside designated area.
        $("#"+id+" .gmnoprint,#"+id+" > div:last").css("display","none");
    }


    /* Soulpolice ------------------------------------------------------------------------------------ */
    
    function browserSize() {
        var myWidth = 0, myHeight = 0;
        if (typeof (window.innerWidth) == 'number') {
            //Non-IE
            myWidth = window.innerWidth;
            myHeight = window.innerHeight;
        } else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
            //IE 6+ in 'standards compliant mode'
            myWidth = document.documentElement.clientWidth;
            myHeight = document.documentElement.clientHeight;
        } else if (document.body && (document.body.clientWidth || document.body.clientHeight)) {
            //IE 4 compatible
            myWidth = document.body.clientWidth;
            myHeight = document.body.clientHeight;
        }
        return [myWidth + '_' + myHeight];
    }
    function getScrollXY() {
        var scrOfX = 0, scrOfY = 0;
        if (typeof (window.pageYOffset) == 'number') {
            //Netscape compliant
            scrOfY = window.pageYOffset;
            scrOfX = window.pageXOffset;
        } else if (document.body && (document.body.scrollLeft || document.body.scrollTop)) {
            //DOM compliant
            scrOfY = document.body.scrollTop;
            scrOfX = document.body.scrollLeft;
        } else if (document.documentElement && (document.documentElement.scrollLeft || document.documentElement.scrollTop)) {
            //IE6 standards compliant mode
            scrOfY = document.documentElement.scrollTop;
            scrOfX = document.documentElement.scrollLeft;
        }
        return [scrOfY];
    }      