/// <reference path="jquery-1.4.1-vsdoc.js" />
/// <reference path="swfobject-vsdoc.js" />

var sbwidth;
var dots = false;
var closeTimeout;
var gallery = new Array(); // contains product gallery images
var gallery_active = false;
var gallery_current = 0;
var resetMenuTimeout;
var ie;
var lteie8;
var ie6;
var galleryTeaserTimeout;






$(document).ready(function () {

    // browser sniffing
    sniffBrowser();

    // if ie6, get a real browser
    if (ie6) {
        ie6Message();
        return;
    }



    // get scrollbar width
    sbwidth = scrollbarWidth();

	

    // dots present?
    if ($(".bg-dots").length > 0) dots = true;

    // when resizing body do stuff
    $(window).resize(function () { repos() });
    

    // set up menu
    configureMenu();

    // product menu items (level 2)
    if (!lteie8) {
        $(".menu-top-level2-product-active a:not(.active)").css("opacity", 0.75).hover(
            function () { $(this).stop().fadeTo(200, 1) },
            function () { $(this).stop().fadeTo(400, 0.75) }
        );
    }

    // hover on collections and products create popup 
    configurePopup();

    // configure product
    configureProduct();

    // bind keys (gallery navigation) 
    bindKeys();

    // configure memo generator
    configureGenerator();

    // iefix fixes issues with ie
    ieFix();

    // configure popup-text on add/remove memo
    configureMemoToolTip();

    // style custom text fields
    $("input[type='text'].custom").each(function (i) {
        SkinCustomTextField($(this));
    });

	repos();

});

// set variables that indicate which browser we're working with
function sniffBrowser() {

    // is IE
    ie = $("html").hasClass("ie");

    // Less than or equal to IE8
    lteie8 = (!$("html").hasClass("ie9") && ie);

    // beloved ie6?
    ie6 = $("html").hasClass("ie6");

}

function SkinCustomTextField(obj) {
    // base class
    var base = "cust-text";
    var width = 213;  // silly override just for helland

    // wrap in html
    $(obj).wrap("<div class=\"mid\"></div>").parent().wrap("<div class='" + base + "-container'></div>");
    var cust = $(obj).parent().parent();
    $(cust).prepend("<div class=\"start\">&#160;</div>");
    $(cust).find(".mid").after("<div class=\"end\">&#160;</div>");

    // correct width
    $(cust).find("input").width(width - 3);

    // set with on base
    $(cust).width(width + 13);

    // 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;
            }
        )
}


// show tooltip when hovering on memo
function configureMemoToolTip() {

    // add hidden tooltip
    $("#frame").append("<div class='tooltip tooltip-add tooltip-memo-add-" + lang_name + "'></div>");
    $("#frame").append("<div class='tooltip tooltip-remove tooltip-memo-remove-" + lang_name + "'></div>");

    // find every remove-button
    $(".memo-remove, .memo-remove-thumb, .memo-remove-list").each(function () {

        // tell which kind of tooltip to show
        var $t = $(this);
        $t.attr("data-tooltip", ".tooltip-remove");

        // configure mouse enter and mouse leave events
        configureMemoToolTipButton($t);

    });

    // find every add-button
    $(".memo-add").each(function () {

        // tell which kind of tooltip to show
        var $t = $(this);
        $t.attr("data-tooltip", ".tooltip-add");

        // configure mouse enter and mouse leave events
        configureMemoToolTipButton($t);

    });
}

// helper function for configureMemoToolTip. Assigns the actual action to the buttons.
function configureMemoToolTipButton(t) {

    var $t = $(t);

    // when mouse enters, slide up tooltip
    $t.mouseenter(function () {
        memoToolTipMouseEnter(this);
    });

    // when mouse leaves, slide down tooltip
    $t.mouseleave(function () {
        memoToolTipMouseLeave(this);
    });
}

function memoToolTipMouseLeave(t) {
    var $t = $(t);
    var $tip = $($t.attr("data-tooltip"));
    $tip.stop().animate({ height: 0 }, 500, "easeOutExpo", function () { $(this).css("display","none") });
}
function memoToolTipMouseEnter(t) {
    $t = $(t);
    var $tip = $($t.attr("data-tooltip"));

    var pos = $t.offset();
    $tip.css({
        height: 0,
        display:"block",
        left: (pos.left + 11) + "px",
        top: (pos.top - 41) + "px"
    });

    $tip.stop().animate({ height: "36px" }, 500, "easeOutExpo");
}

function configureMenu() {



    // hide any popup when mouse enters menu
    $(".menu-top").mouseenter(
        function () {
            closeTimeout = setTimeout(fnClosePopup, 100);
        }
    );

    $(".menu-top > li:not(.not-menu)").hoverIntent(
        function () { menuTopLevel1MouseEnter(this); },
        function () {
            resetMenuTimeout = setTimeout("resetToCurrentMenu()", 300);
			$(this).removeClass("li-active");
            // also remove active state
            var $a = $(this).find(">a");
            if (!$a.hasClass("menu-top-product-active")) { // regular
                $a.removeClass("active");
                $a.addClass("inactive");
            }
            else if ($a.hasClass("menu-top-product-active")) { // product menu
                $a.removeClass("menu-top-product-active");
                $a.addClass("menu-top-product-inactive");
            }
        }
    );
    /*
    // mouse over menu item slides down submenu if any (in an untracool fancy manner)
    $(".menu-top > li:not(.logo)").mouseenter(function () {
        menuTopLevel1MouseEnter(this);
    });

    // whenever mouse leaves a menu item, set timer that resets menu back to currently active menu
    $(".menu-top > li:not(.logo)").mouseleave(function () {
        resetMenuTimeout = setTimeout("resetToCurrentMenu()", 2000);
    });
    */



}

function menuTopLevel1MouseEnter(t) {

	

    // get hold of submenu if any
    var $t = $(t);
	$t.addClass("li-active");
    var $sub = $t.find("ul");

    // hide any visible submenus
    hideVisibleSubmenus($sub);

    // none? unbind and return
    if ($sub.length == 0) {
        $t.unbind("mouseenter");
        return;
    }

    // add active state class
    var $a = $t.find(">a");
    if ($a.hasClass("inactive")) { // regular inactive
        $a.addClass("active");
        $a.removeClass("inactive");
    }
    else if ($a.hasClass("menu-top-product-inactive")) { // product menu
        $a.addClass("menu-top-product-active");
        $a.removeClass("menu-top-product-inactive");
    }

    // don't slide down if already down
    if ($sub.height() > 0) return;

    // whenever mouse gets over one of these menu items, clear timeout that slides down and marks current menu
    clearTimeout(resetMenuTimeout);

    // first position
    $sub.css("display", "block");
    $sub.height(0);

    var height = "60px";
    var time = 600;
    var ease = "easeOutQuad";

    // regular submenu or product's submenu?
    if ($sub.hasClass("menu-top-level2-product") || $sub.hasClass("menu-top-level2-product-active")) {
        $sub.addClass("menu-top-level2-product-active");
        var height = "140px";
        var time = 500;
        ease = "easeOutExpo";
    }
    else {
        $sub.addClass("menu-top-level2-active");
    }

    // resize menu
    resizeMenu();

    // set above all else
    $(".menu-top > li:not(.not-menu) ul").not($sub).css("z-index", 1);
    $sub.css("z-index", 2);

    // then slide down
    $sub.stop().animate({ height: height }, time, ease);

    // also animate (fade in) submenus (not on ie <= 8)
    if (!lteie8) {
        $sub.find("li").fadeTo(0, 0).each(function (i) {
            //$(this).delay(200 + (i * 50)).fadeTo(100, 1);
            $(this).delay(200 + (i * 50)).stop().animate(
                        {
                            opacity: 1
                        },
                        400,
                        "easeOutSine"
                    );
        });
    }
}

// Resets back to current menu (and submenu if any)
function resetToCurrentMenu(){
    menuTopLevel1MouseEnter($(".act1").parent());
}

// hide any visible submenus
function hideVisibleSubmenus(currentlyHoveringOver) {

    // find visible, animate height
    $(".menu-top li:not(.not-menu) ul:visible").not(currentlyHoveringOver).stop().animate({ height: 0 }, 400, "easeOutQuad");

}

function memoListRemove(t) {

    // List mode
    var $t = $(t);

    // fade out parent li
    var $c = $("#memo-item-" + $t.attr("data-doc-id"));

    $c.find(".memo-list-image").fadeTo(200, 0);
    $c.find(".memo-list-item-inner").delay(100).fadeTo(200, 0);
    $c.delay(400).animate({ height: 0, paddingTop: 0, paddingBottom: 0 }, 400, "easeOutExpo", function () { $(this).remove(); });

    memo_remove($t.attr("data-doc-id"), t);

    return false;
}

function memoThumbRemove(t){

    // thumb mode
    var $t = $(t);

    // fade out parent li
    var $c = $("#memo-item-" + $t.attr("data-doc-id"));
    var $p = $("#popup-box");

    // hide image behind at the same time as sliding up popup-box
    $c.animate({ opacity: 0 }, 1, "linear");
    $p.animate({ height: 0 }, 300, "easeOutExpo", function () { $(this).css({ display: "none", height: "auto" }) });
    $c.animate({ opacity: 0 }, 300, "easeOutExpo", function () { $(this).remove() });

    memo_remove($t.attr("data-doc-id"), t);

    return false;

}

// switch to differnet mode in memo
function memoMode(mode) {
    document.memo.cmd.value = mode;
    document.memo.submit();
}

function ieFix() {
    // header bg too big
    $(".doc-list-header").each(function () {
        var $t = $(this);
        var $txt = $t.find(".header-text");
        var $bg = $t.find(".header-bg");
        $bg.height($txt.outerHeight(true));
    });
}

function bindKeys() {
    $(document).keydown(function (e) {

        // left
        if (e.keyCode == 37) {
            if (gallery_active) galleryArrowLeft();
            return false;
        }

        // right
        if (e.keyCode == 39) {
            if (gallery_active) galleryArrowRight();
            return false;
        }

        // escape = close gallery
        if (e.keyCode == 27) {
            if (gallery_active) closeGallery();
            return false;
        }

    });
}

function configureProduct() {

    // configure add remove to from memo

    var $p = $(".product");
    if ($p.length == 0) return;

    // links to related elements - some point to PDF-files or similar, while others link to documents we want to load via ajax. Prepare the latter links:
    var $c = $(".subload");

    // if not exists, create container 
    if ($c.length == 0) {
        $p.parent().append("<div class=\"subload\"></div>");
        $c = $(".subload");
    }

    // each of the product-subload links opens document with ajax if js present.
    $(".product-subload").each(function () {
        var $t = $(this);

        // Click on link loads content with ajax
        $t.click(function () {

            // scroll to subload
            scrollTo(".subload");

            // slide down box first? 
            var $c = $(".subload");
            if ($c.height() == 0) {
                // animate before show
                /*
                $c.animate({height:}, 500, "easeOutExpo", function ($t) {
                    return function () {
                        productSubload($t);
                    }
                });
                */
                productSubload($t);

            }
            else {
                // no animation
                productSubload($t);
            }


            return false;
        });
    });

    // subload also download link - which just shows contents that are inside hidden div
    $(".product-download-link").click(function () {

        // scroll to subload
        scrollTo(".subload");

        var $c = $(".subload");
        var $exists = $c.find("div:first-child");

        if ($exists.length > 0) {
            $exists.animate({ opacity: 0 }, 250, "easeOutSine", function () {
                var $c = $(".subload");
                $c.addClass("subload-white");
                $c.html($(".product-download").html());
                $c.find("div:first-child").fadeTo(500, 1);
            });
        }
        else {
            var $c = $(".subload");
            $c.addClass("subload-white");
            $c.html($(".product-download").html());
        }

        return false;
    });

    // Gallery hoverbutton
    /*
    $b = $(".gallery-button");
    $b.fadeTo(0, 0); // initial
    $b.hover(
        function () {
            $(this).stop().fadeTo(150, 1);
        },
        function () {
            $(this).stop().fadeTo(400, 0);
        }
    );

    $b.click(function () { showGallery() });
    */

    $b = $(".gallery-button-zoom");

    // store orig height and width in attributes when image has loaded
    $(".gallery-teaser-zoom").load(function () {
        SetGallerySize();
    });

    // hover = zoom teaser a little.
    $b.hover(
        function () {
            var $t = $(".gallery-teaser-zoom");

            // only run logic if data-width has been set. 
            if ($t.attr("data-width") != undefined) {

                // chrome bugs and returns 0 on some images if this function is only run on image load.
                if ($t.attr("data-width") == 0) SetGallerySize();

                // change class of product zoom icon
                $(".product-zoom-icon").addClass("product-zoom-icon-over");

                // if not orig height stored, store now
                if (!$t.attr("data-width")) {
                    $t.attr("data-width", $t.width());
                    $t.attr("data-height", $t.height());
                }

                // zoom in a bit
                $t.stop().animate({
                    left: "-10px",
                    top: "-10px",
                    width: Number($t.attr("data-width")) + 20 + "px",
                    height: Number($t.attr("data-height")) + 20 + "px"
                }, 300, "easeOutExpo");
            }
        },
        function () {

            var $t = $(".gallery-teaser-zoom");

            // only run logic if data-width has been set. 
            if ($t.attr("data-width") != undefined) {
                // zoom back to original
                $t.stop().animate({
                    left: 0,
                    top: 0,
                    width: Number($t.attr("data-width")) + "px",
                    height: Number($t.attr("data-height")) + "px"
                }, 300, "easeOutExpo");

                // change class of product zoom icon
                $(".product-zoom-icon").removeClass("product-zoom-icon-over");
            }
        }
    );

    $b.click(function () { showGallery(); return false; });
}

// Store size of gallery teaser image as data-attributes inside image
function SetGallerySize() {
    var $t = $(".gallery-teaser-zoom");

    /*
    // if returns 0, run it again
    if ($t.width() == 0) {
        galleryTeaserTimeout = setTimeout(SetGallerySize(), 100);
    }
    else {
        clearTimeout(galleryTeaserTimeout);
        */
        $t.attr("data-width", $t.width());
        $t.attr("data-height", $t.height());
    //}
}

// loads a document underneath product info using ajax
function productSubload($t) {

    // Fade out container
    var $c = $(".subload");
    $c.removeClass("subload-white");
    $c.find("div:first-child").fadeTo(250, 0);

	var loadurl = "";
		if($t.hasClass("measurements")){
			loadurl = $t.attr("href");
		}
		else
		{
			loadurl = $t.attr("href") + "?ajax=1";
		}

    $.ajax({
		
        url: loadurl,
        success: function (data) {
            $c.html(data);

            // get first element
            var $doc = $c.find("div:first-child");
            $doc.fadeTo(0, 0);

            // fade in container
            $doc.fadeTo(500, 1, function () {
                try {
                    $(".subload div").each(function () {
                        this.style.removeAttribute("filter");
                    });
                } catch (e) { }
            });

            // trigger repos
            repos();
        }
    });
}

function closeGallery() {
    gallery_active = false;

    // slide up gallery
    $(".gallery-box").animate({
        height:0
    }, 700, "easeOutExpo");

    // show scrollbar in body
    $("body").css("overflow", "auto");
}

// shows product image gallery
function showGallery() {

    // active
    gallery_active = true;

    // get gallery box 
    var $g = $(".gallery-box");

    // disable selection
    $g.disableSelection();

    // populate if not already populated
    var $li = $g.find("li");
    if ($li.length == 0) {
        
        // add ul
        $ul = $g.find("ul");

        // add li and img for each image in gallery
        for (var i = 0; i < gallery.length; i++) {
            $ul.append("<li><img class='gallery-image' src='" + gallery[i].url + "'" +
                        " data-orig-width='" + gallery[i].width + "'" +
						" data-memo='" + gallery[i].inMemo + "'" +
						" data-attparamid='" + gallery[i].attParamID + "'" +
                        " data-orig-height='" + gallery[i].height + "' />"+
						"</li>");

        }

    }

	

    // assign left, right and close button
    $(".gallery-arrow-left").click(function () { galleryArrowLeft() });
    $(".gallery-arrow-right").click(function () { galleryArrowRight() });
    $(".gallery-show-menu").click(function () { closeGallery() });

    // initially, hide left arrow
    $(".gallery-arrow-left").css("display", "none");

    // also hide right arrow if just one image
    if (gallery.length == 1) $(".gallery-arrow-right").css("display", "none");

    // hide scrollbar from body
    $("body").css("overflow", "hidden");

    // resize all li boxes inside gallery-box so they fill entire browser window
    resizeGallery();
	toggleMemoGallery();
    $(".gallery-box").height(0); // initial

    // animate - show
    $g.height(0);
    $g.animate({
        height: $(window).height()
    }, 700, "easeOutExpo");

}

function toggleMemoGallery()
{
	 // get current image
    var $img = $(".gallery-box ul img:eq(" + gallery_current + ")");

	if ($img.attr("data-memo") == "1") 
	{
		$(".gallery-memo-remove").removeClass("gallery-memo-action-disabled");
		$(".gallery-memo-add").addClass("gallery-memo-action-disabled");
	}
	else
	{
		$(".gallery-memo-add").removeClass("gallery-memo-action-disabled");
		$(".gallery-memo-remove").addClass("gallery-memo-action-disabled");
	}

}


// add to memo
function gallery_memo_add(doc_id, obj) {

	var $img = $(".gallery-box ul img:eq(" + gallery_current + ")");
	var att_param_id  = $img.attr("data-attparamid");

    // hide add-button
    $(obj).addClass("gallery-memo-action-disabled");
    $(obj).parent().find(".gallery-memo-remove").removeClass("gallery-memo-action-disabled");

    // hide add-button in popup source too
    //$("#popup" + doc_id).find(".memo-remove").removeClass("memo-action-disabled");
    //$("#popup" + doc_id).find(".memo-add").addClass("memo-action-disabled");

    // ajax call to add.
    $.ajax({
        type: "POST",
        url: '/h_memo_post.aspx',
        data: 'CMD=ADD&DOC_ID=' + doc_id + "&ATT_PARAM_ID=" + att_param_id,
        success: function (data) {
			var $img = $(".gallery-box ul img:eq(" + gallery_current + ")");
			$img.attr("data-memo", 1);
            memo_update(data);
        }
    });
}

// remove from memo
function gallery_memo_remove(doc_id, obj) {

	var $img = $(".gallery-box ul img:eq(" + gallery_current + ")");
	var att_param_id  = $img.attr("data-attparamid");

    // hide remove-button
    $(obj).addClass("gallery-memo-action-disabled");
    $(obj).parent().find(".gallery-memo-add").removeClass("gallery-memo-action-disabled");

    // hide add-button in popup source too
    //$("#popup" + doc_id).find(".memo-remove").addClass("memo-action-disabled");
    //$("#popup" + doc_id).find(".memo-add").removeClass("memo-action-disabled");

    // ajax call to remove. 
    $.ajax({
        type: "POST",
        url: '/h_memo_post.aspx',
        data: 'CMD=REMOVE&DOC_ID=' + doc_id + "&ATT_PARAM_ID=" + att_param_id,
        success: function (data) {
			var $img = $(".gallery-box ul img:eq(" + gallery_current + ")");
			$img.attr("data-memo", 0);
            memo_update(data);
        }
    });
}

// click on image in gallery zooms in and out
function galleryToggleZoom(e) {

    // get current image
    var $img = $(".gallery-box ul img:eq(" + gallery_current + ")");

    // zoomed?
    if ($img.attr("data-zoom") == "active") {

        // set inactive
        $img.attr("data-zoom", "");

        // remove mouse event from gallery-box
        $(".gallery-box").unbind("mousemove");

        // calculate zoomed out size
        var w, h;
        var ww = $(window).width();
        var wh = $(window).height();

        // find out which size we should make the image
        var aspect = $img.attr("data-orig-width") / $img.attr("data-orig-height");
        w = ww;
        h = w / aspect;
        if (h > wh) {
            h = wh;
            w = h * aspect;
        }

        // zoom out
        $img.animate({
            width: w + "px",
            height: h + "px",
            paddingTop: 0,
            paddingBottom: 0,
            marginLeft: ((ww / 2) - (w / 2)) + "px",
            marginTop: ((wh / 2) - (h / 2)) + "px"
        }, 500, "easeOutExpo", function () { galleryZoomOutComplete($(this)) });

    }
    else {

        // set active
        $img.attr("data-zoom", "active");

        // calculate which size to present the image in (full width, scroll height)
        var w = $(window).width();

        //if (w > $img.attr("data-orig-width")) w = $img.attr("data-orig-width");
        var ratio = $img.attr("data-orig-width") / $img.attr("data-orig-height");
        var h = w / ratio;

        // find marginTop
        var move = galleryZoomInMove(e, $(".gallery-box"), $img);
        var pc = move.percent;
        var maxMove = h - $(".gallery-box").height();
        move.marginTop = Math.ceil(-(maxMove) * pc) + "px";

        // animate zoom in
        $img.animate({
            width: w + "px",
            height: h + "px",
            paddingTop: "100px",
            paddingBottom: "100px",
            marginLeft:0,
            marginTop:move.marginTop
        }, 500, "easeOutExpo", function () { galleryZoomInComplete($(this)) });
                  
    }
   
}

function galleryZoomOutComplete($img) {
}

function galleryZoomInComplete($img)
{
    // when zoom complete, attach move event to gallery-box. causes image to pan
    var $g = $(".gallery-box");
    $g.mousemove(function (e) {

        // get coordinates within box
        var move = galleryZoomInMove(e, $g, $img);

        //$img.stop().animate({ marginTop: move }, 500, "easeOutExpo");
        $img.css("margin-top", move.marginTop)
    });
}

// calculate how much to move zoomed in image
function galleryZoomInMove(e, $g, $img) {

    var x = e.clientX;
    var y = e.clientY;

    // calculate percentage within y
    var pc = (y / ($g.outerHeight() / 100)) / 100;

    // how much is the maximum we move the picture up? It's the image height minus box viewport
    var maxMove = $img.outerHeight() - ($g.height());
    var move = Math.ceil(-(maxMove) * pc);

    return { marginTop: move + "px", percent: pc }
}

// what happens when you click right arrow in gallery?
function galleryArrowRight() {

    // got here by mistake? good bye
    if (gallery_current >= gallery.length - 1) return;

    // get current image
    var $img = $(".gallery-box ul img:eq(" + gallery_current + ")");
    
    // zoomed in? zoom out
    //if ($img.attr("data-zoom") == "active") galleryToggleZoom();

    var w = $(".gallery-box ul li:first").width();

    // increase current by one
    gallery_current += 1;

    // slide .gallery-box ul 1 screen to the left
    $(".gallery-box ul").animate({ left: -gallery_current * w }, 700, "easeOutExpo", function(){toggleMemoGallery();});

    // hide arrow right?
    galleryUpdateArrows();
}

// what happens when you click left arrow in gallery?
function galleryArrowLeft() {

    // got here by mistake? good bye
    if (gallery_current <= 0) return;

    var w = $(".gallery-box ul li:first").width();

    // decrease current by one
    gallery_current -= 1;

    // slide .gallery-box ul 1 screen to the right
    $(".gallery-box ul").animate({ left: -gallery_current * w }, 700, "easeOutExpo", function(){toggleMemoGallery();});

    // hide arrow right?
    galleryUpdateArrows();
	
}

// show or hide arrows
function galleryUpdateArrows() {
    
    // last? hide right button
    if (gallery_current >= gallery.length - 1) {
        $(".gallery-arrow-right").fadeOut(400);
    }
    else {
        $(".gallery-arrow-right").fadeIn(200);
    }

    // first? hide left button
    if (gallery_current <= 0) {
        $(".gallery-arrow-left").fadeOut(400);
    }
    else {
        $(".gallery-arrow-left").fadeIn(200);
    }

	
}

// resize each li box inside gallery-box.ul so it fits entire screen. 
// resize images inside li, and center them acorrdingly.
function resizeGallery() {
    var $w = $(window);
    var ww = $w.width();
    var wh = $w.height();
    var $li = $(".gallery-box ul li");

    // resize gallery box
    var $g = $(".gallery-box");
    $g.width(ww);
    $g.height(wh);

    // loop li
    $li.each(function (i) {
        $t = $(this);
        $t.css({
            width: ww,
            height: wh,
            left: ww * i,
            top: 0
        });

        // get image
        var $img = $t.find(".gallery-image");
        var w, h;

        // find out which size we should make the image
        var aspect = $img.attr("data-orig-width") / $img.attr("data-orig-height");
        w = ww;
        h = w / aspect;

        // now, if not zoomed in, we want to fit entire product. Therefore check height also
        if ((h > wh) && $img.attr("data-zoom") != "active") {
            h = wh;
            w = h * aspect;
        }

        // resize and position image within available area
        $img.width(w).height(h);
        $img.css({
            marginLeft: ((ww / 2) - (w / 2)) + "px",
            marginTop: ((wh / 2) - (h / 2)) + "px"
        });

		$(".gallery-memo-add, .gallery-memo-remove").css({left: ((ww / 2)) + "px"});

    });

    // resize and position credit-box
    var $credit = $(".credit-box");
    $credit.width(ww).height(wh - 6);
    $credit.css({
        width:ww-70,
        height:wh-6
    });

    // resize and position click through
    $click = $(".gallery-zoom-clickthrough");
    $click.css({
        left:"147px",
        top:"3px",
        width: ww - 247 + "px",
        height:wh - 6
    });

    // assign click
    $click.unbind("click").click(function (e) {
        galleryToggleZoom(e);
        return false;
    });

}

// resize on window resize
function repos() {

    var windowHeight = $(window).height();
    var windowWidth = $(window).width();

    // resize bg image container
    $("#bg").width(windowWidth + sbwidth + "px");
    $("#bg").height(windowHeight + "px");

    // resize dots over image if exists
    if (dots) {
        $(".bg-dots").width($("#bg").width());
        $(".bg-dots").height($("#bg").height());
    }

    // resize bg
    var bg = $(".bg-image");
    var w = $(bg).attr("width");
    var h = $(bg).attr("height");
    var ww = windowWidth + sbwidth;
    var aspect = w / h;
    w = ww
    h = w / aspect;
    if (h < windowHeight) {
        h = windowHeight;
        w = h * aspect;
    }

    $(bg).width(w);
    $(bg).height(h);
    $(bg).css("left", ((ww - w) / 2));
    $(bg).css("top", ((windowHeight - h) / 2));

    // repos quote if exists
    var $q = $(".bg-quote");
    if ($q.length > 0) {
        $q.css("left", 190);
        $q.css("top", ((windowHeight + $(".menu-top-container").height() + $(".menu-top-level2:visible").height()) / 2) - ($q.height() / 2));
    }

    // resize menu-top-level2 items
    resizeMenu();

    // resize gallery?
    if (gallery_active) {
        resizeGallery();
    }

}

function resizeMenu() {
    $(".menu-top-level2").each(function () {
        var windowWidth = $(window).width();
        var $ul = $(this);
        var mW = windowWidth - $ul.offset().left;
        if (mW < 757) mW = 757;
        $ul.width(mW);
    });
}


function configurePopup() {

    // mouse over a product/collection displays popup-box
    $(".popup-parent").mouseover(
        function () {
            var $a = $(this);
            var $p = $("#popup-box");
            //$p.stop(); // stop any previous ongoing fadeout

            // stop any intervals waiting to time out 
            clearTimeout(closeTimeout);

            // set contents from hidden div 
            $p.html($a.parent().find(".popup").html());

            // mouse leaving
            $p.find("a").mouseleave(
                function () {
                    closeTimeout = setTimeout(fnClosePopup, 100);
                }
            );

            // when hover on add/remove, don't "leave"
            $p.find(".memo-add, .memo-remove, .memo-remove-thumb").mouseenter(
                function () {
                    clearTimeout(closeTimeout);
                }
            );

            // fade in overlay on all items
            if (lteie8) {
                $(".popup-overlay").css({ display: "block" });
            }
            else {
                $(".popup-overlay").fadeIn(350);
            }

            // position and fade in
            //console.log("really here?");
            $p.css("left", $a.position().left - 24);
            $p.css("top", $a.position().top - 24);

            if (lteie8)
                $p.css("display", "block");
            else
                $p.fadeIn(200);

            // zoom image
            var $i = $p.find("img");

            // zoom image
            $i.animate(
                {
                    left: "-18px",
                    top: "-26px",
                    width: "230px",
                    height: "260px"
                },
                250,
                "easeOutQuad"
            );

            // pan up product name
            $p.find("a").css({
                "opacity": 0,
                "paddingTop": "170px"
            }).animate({
                "opacity": 1,
                "paddingTop": "160px"
            }, 250, "easeOutQuad",
                function () {
                    try {
                        this.style.removeAttribute("filter");
                    } catch (e) { }
                }
            );

        }
    );

}

// add to memo
function memo_add(doc_id, obj) {

    // hide add-button
    $(obj).addClass("memo-action-disabled");
    $(obj).parent().find(".memo-remove").removeClass("memo-action-disabled");

    // hide add-button in popup source too
    $("#popup" + doc_id).find(".memo-remove").removeClass("memo-action-disabled");
    $("#popup" + doc_id).find(".memo-add").addClass("memo-action-disabled");

    // ajax call to add.
    $.ajax({
        type: "POST",
        url: '/h_memo_post.aspx',
        data: 'CMD=ADD&DOC_ID=' + doc_id,
        success: function (data) {
            memo_update(data);
        }
    });
}

// remove from memo
function memo_remove(doc_id, obj) {

    // hide remove-button
    $(obj).addClass("memo-action-disabled");
    $(obj).parent().find(".memo-add").removeClass("memo-action-disabled");

    // hide add-button in popup source too
    $("#popup" + doc_id).find(".memo-remove").addClass("memo-action-disabled");
    $("#popup" + doc_id).find(".memo-add").removeClass("memo-action-disabled");

    // ajax call to remove. 
    $.ajax({
        type: "POST",
        url: '/h_memo_post.aspx',
        data: 'CMD=REMOVE&DOC_ID=' + doc_id,
        success: function (data) {
            memo_update(data);
        }
    });
}

// updates footer when ajax call is completed
function memo_update(data) {
    
    // get number-container
    var $m = $(".memo-right");
    var $mbox = $(".memo");

    // change value of counter
    $m.html(data);

    // fade in from a certain opacity to inform user what action he just performed
    $mbox.fadeTo(0, 0.5);
    $mbox.fadeTo(500, 1);
}

function fnClosePopup() {
    if ($("#popup-box").length > 0) {
        
        //if (lteie8)
            $("#popup-box").css("display", "none");
        //else
        //    $("#popup-box").fadeOut(400);
        

        // fade out all overlays
        if (lteie8) {
            $(".popup-overlay").css({ display: "none" });
        }
        else {
            $(".popup-overlay").fadeOut(400);
        }
        
    }
}




// disable selecting
// $.disableSelection(selector)
jQuery.fn.extend({
	disableSelection: function() {
		this.each(function() {
			this.onselectstart = function() { return false; };
			this.unselectable = "on";
			jQuery(this).css('-moz-user-select', 'none');
		});
	}
});

// check if page has visible scrollbar
// $.hasScrollbar()
jQuery.fn.hasScrollbar = function() {
	var scrollHeight = this.get(0).scrollHeight;

	//safari's scrollHeight includes padding
	if ($.browser.safari)
		scrollHeight -= parseInt(this.css('padding-top')) + parseInt(this.css('padding-bottom'));

	if (this.height() < scrollHeight)
		return true;
	else
		return false;
}

// get width of scrollbar (varies between browsers)
function scrollbarWidth() {
	var div = $('<div style="width:50px;height:50px;overflow:hidden;position:absolute;top:-200px;left:-200px;"><div style="height:100px;"></div>');
	// Append our div, do our calculation and then remove it 
	$('body').append(div);
	var w1 = $('div', div).innerWidth();
	div.css('overflow-y', 'scroll');
	var w2 = $('div', div).innerWidth();
	$(div).remove();
	return (w1 - w2);
}

// selects one of the available layouts in the PDF Generator
function selectLayout(obj, val) {
    document.memo.PROJECT_LAYOUT.value = val;
    $(".layout a").removeClass("active");
    $(obj).addClass("active");
}

function configureGenerator() {

    // click on PDF-generator reveals configuration for PDF download.
    $(".bt-pdf-generator").click(function () {
        $(".generator").css({ height: 0, display: "block" }).animate({ height: "533px" }, 800, "easeOutExpo");
        $("div.header-bottom").addClass("header-bottom-generator");
        return false;
    });

    // click on "download pdf"
    $(".bt-download-pdf").click(function () {
        document.memo.action = "h_request_pdf.aspx";
        document.memo.submit();
        return false;
    });

    // click on "send to e-mail"
    $(".bt-send-email").click(function () {
        var $t = $(this);
        document.memo.action = "h_request_pdf.aspx";
        document.memo.cmd.value = "EMAIL";
        document.memo.submit();
        return false;
    });
}

function scrollTo(selector) {
    $('html,body').animate({ scrollTop: $(selector).offset().top }, 'slow', "easeOutQuad");
}
