﻿var version = deconcept.SWFObjectUtil.getPlayerVersion();

function flashIsEnabled() {
    var flash = my_getCookie("KF_FlashEnabled");
    if (flash != null) {
        if (flash == "False") {
            return false;
        }
    }
    return true;
}

function fixFlashPosition(containerid) {
    if (document.getElementById && (version['major'] > 7) && flashIsEnabled()) {
        var flashdiv = document.getElementById(containerid);
        flashdiv.style.marginTop = "-40px";
        flashdiv.style.marginRight = "-35px";
        flashdiv.style.marginBottom = "-25px";
        flashdiv.style.marginLeft = "-35px";
    }
}
function fixFlashPositionByCoordinates(containerid, marginstyle) {
    if (document.getElementById && (version['major'] > 7) && flashIsEnabled()) {
        var flashdiv = document.getElementById(containerid);
        flashdiv.style.margin = marginstyle;
    }
}
function resetPagetypeContainer(containerid) {
    if (document.getElementById && (version['major'] > 7) && flashIsEnabled()) {
        var masterpage_type = document.getElementById(containerid);

        masterpage_type.style.paddingLeft = "0";
        masterpage_type.style.paddingRight = "0";
        masterpage_type.style.paddingBottom = "0";
        masterpage_type.style.paddingTop = "0";
    }
}
function resetMainMenuContainer() {
    if (document.getElementById && (version['major'] > 7) && flashIsEnabled()) {
        var menu = document.getElementById("menu");

        menu.style.top = "34px";
        menu.style.left = "120px";
        menu.style.bottom = "0";
    }
}
function resetProdSpecs(elemid) {
    if (document.getElementById && (version['major'] > 7) && flashIsEnabled()) {
        var prodspecs = document.getElementById(elemid);
        prodspecs.style.width = "890px";
        prodspecs.style.paddingLeft = "20px";
    }
}

/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/

if (document.addEventListener) { // DOM
    window.addEventListener("load", init_k, false);
} else if (window.attachEvent) { // ie specific
    window.attachEvent("onload", init_k);
}
if (navigator.userAgent.indexOf("MSIE") != -1) { // sifr replacement hack
    jQuery(document).ready(function() {
        jQuery("#specialtop h1").each(function() {
            jQuery(this).css("width", this.offsetWidth + "px");
        });
        startSifr(); // config and start sifr - IE makes it after load
    });
} else {
    startSifr(); // config and start sifr -other browsers loads directly 
}
function init_k() {
    jQuery.noConflict();
    startJQueryFunctions();
    // start page "ticker"/scrolling text
    startTickerStartPage(true);

    // Linux hack for logo above the flash 
    if (navigator.userAgent.indexOf("X11") != -1 || navigator.userAgent.toLowerCase().indexOf("linux") != -1) {
        var crestimage = document.getElementById("crest"); //.getElementsByTagName("img")[0];
        crestimage.style.zIndex = "60";
        var hack = document.createElement('iframe');
        hack.style.zIndex = "50";
        hack.style.position = "absolute";
        hack.style.height = "80px";
        hack.style.width = "83px";
        hack.style.top = "0";
        hack.style.left = "0px";
        hack.style.display = "none";
        hack.id = "xlinux"
        document.getElementById("top").appendChild(hack);
        document.getElementById("xlinux").style.display = "block";
    }
}

function startJQueryFunctions() {

    // css enhancement
    jQuery("h1.sIFR-replaced + h2.sIFR-replaced").css({ margin: "-22px 0 16px" }); // sifr fix

    jQuery(".compare tbody.js_shownexttbody td:first-child").addClass("first"); // cpm
    jQuery(".compare tbody.js_shownexttbody td:last-child").addClass("last");
    jQuery(".compare tbody:not(.js_shownexttbody) tr:last-child").addClass("last");

    // js classes with different functions
    jQuery(".js_vanish").css({ "display": "none" });

    var btGo = document.getElementById('ctl00_top1_Select_region___dropdown1_btGo');
    btGo.style.display = 'none';

    // form functions
    //jQuery("select.js_autosubmit").bind("change",function(){ this.form.submit(); }); // see also next ones, better to use on form tag

    /************************** Comment by Sogeti 0804011
    jQuery("form.js_autosubmit input[type=submit]").hide(); 

	jQuery("form.js_autosubmit select:not(.js_locations)").bind("change",function(){
    var regex=/^[_\- ]*$/; 
    if (!this.options[this.selectedIndex].value.match(regex))
    this.form.submit(); 
    });
    jQuery("form.js_autosubmit select.js_locations").bind("change",function(){ 
    var regex=/^[_\- ]*$/; 
    if (!this.options[this.selectedIndex].value.match(regex))
    window.location=this.options[this.selectedIndex].value; 
    });
    ***************************/

    window.countpopups = 0;
    jQuery(".js_popupwin").click(function() {
        var url = this.href;
        var winname = '';
        window.countpopups++;
        var winname = "win" + window.countpopups;
        var w = url.replace(/.*w=(\d+).*?$/, "$1") * 1;
        var h = url.replace(/.*h=(\d+).*?$/, "$1") * 1;
        w = (typeof w == "number" && !isNaN(w)) ? w : 500;
        h = (typeof h == "number" && !isNaN(h)) ? h : 500;
        var popupWin = window.open(url, winname, 'menubar=no,toolbar=no,location=no,directories=no,status=no,scrollbars=yes,resizable=no,dependent=no,width=' + w + ',height=' + h + '');
        return false;
    });
    jQuery(".js_winx").click(function() {
        self.close();
    });
    jQuery(".js_selectbox").selectbox();
    //jQuery(".js_selectbox").addClass("selectbox").css("opacity","0");

    // plugins and functions for effects/animations enhancement	

    // plugin: show/hide , note: method findobj overrides property area
    /* html example: 
    <div class="js_shownext"><a href="#"></a></div>
    <div class="js_showhidearea"></div>
    (  class="open" is added to "a" tag if not overridden )
    js:
    jQuery(".js_shownext").showHide(); 
    */
    jQuery.fn.showHide = function(opt) {
        opt = jQuery.extend({
            area: ".js_showhidearea",
            openselector: "a",
            openclass: "open",
            eventtype: "click",
            effect: "slide",
            defaultstate: { "display": "none" }, // css values
            findobj: function(obj) {
                return jQuery(obj).next(opt.area);
            }
        }, opt);
        opt.findobj(this).css(opt.defaultstate);
        return this.bind(opt.eventtype, function(e) {
            if (opt.effect == "slide") opt.findobj(this).slideToggle(300);
            else if (opt.effect == "none") opt.findobj(this).toggle();
            jQuery(this).children(opt.openselector).toggleClass(opt.openclass);
            jQuery(this).children("tr").children("td.first").children(opt.openselector).toggleClass(opt.openclass);
            // komatsu special:
            if ((jQuery(".js_showhideall").hasClass("buttoncollapsed") && jQuery(opt.area + ":hidden").size() == 0) ||
				(jQuery(".js_showhideall").hasClass("buttonopened") && jQuery(opt.area + ":visible").size() == 0))
                switchStateCollapse();
            return false;
        });
    };

    jQuery(".js_shownext").showHide();
    jQuery(".js_shownexttbody").showHide({
        "effect": "none",
        "findobj": function(obj) {
            return jQuery(obj).next("tbody.js_showhidearea");
        }
    });
    jQuery(".js_showhideall").click(function() {
        switchStateCollapse();
        return false;
    });
    var switchStateCollapse = function() {
        if (jQuery(".js_showhideall").hasClass("buttonopened")) {
            jQuery(".js_showhideall").removeClass("buttonopened").addClass("buttoncollapsed");
            jQuery(".js_showhidearea").hide();
            jQuery(".js_shownext a").removeClass("open");
            jQuery(".js_shownexttbody td.first a").removeClass("open");
        } else {
            jQuery(".js_showhideall").removeClass("buttoncollapsed").addClass("buttonopened");
            jQuery(".js_showhidearea").show();
            jQuery(".js_shownext a").addClass("open");
            jQuery(".js_shownexttbody td.first a").addClass("open");
        }
    }

    jQuery.fn.plugin = function(opt) {
        opt = jQuery.extend({
            forcealert: false,
            checknode: false
        }, opt);
        return this.each(function() {
            var info = jQuery.log.tagInfo(this, opt);
            if (opt.forcealert) {
                alert(info);
            } else {
                jQuery.echo(info);
            }
            if (opt.checknode) {
                jQuery(this).children("*").debug(opt); // jQuery.extend(opt,{ pad : " - "})
            }
        });
    };
    /* Comment 080903 - Inaktiverade animeringar Product Overview		
    // animation for product Selector - enlarge/shrink thumbnails in overview			
    var toggleEnlarge=function(obj) {
    jQuery(obj).each(function() {
    var jQ_ul=jQuery(this),
    jQ_li=jQ_ul.children("li"),
    jQ_img=jQ_li.children("a").children("img"),
    jQ_text=jQ_li.children("p"),
    jQ_trigger=jQ_ul.prev(".js_selectortrigger").children("h3");

			
    jQ_text.dequeue();
    jQ_li.dequeue();
    jQ_img.dequeue();
				
    if (jQ_li.css("width")!="172px") {
    jQ_img.animate({ height: "110px",width: "110px" }, 600, "easeOutCirc");
    jQ_li.animate({ height: "120px", width: "172px" }, 300, "easeOutCirc", function() {
    jQ_text.fadeIn(500);
    jQ_trigger.removeClass("closed").addClass("opened");
    });
    jQ_ul.unbind("click");
    } else {
    jQ_img.animate({ height: "55px",width: "55px" },600, "easeOutCirc",function () { 					jQ_trigger.removeClass("opened").addClass("closed");
    });
    jQ_li.animate({ height: "55px", width: "86px" },500);
    jQ_text.fadeOut(300);
    jQ_ul.bind("click",function(){toggla( jQuery(this) ); return false; });
    }
		
		});
    }
    jQuery("ul.js_productselector li:nth-child(5),ul.js_productselector li:nth-child(10)").after('<br class="clr" />');
    jQuery("ul.js_productselector").css({ width: '100%' });
    jQuery(".js_selectortrigger h3").bind("click",function(){ toggleEnlarge( jQuery(this).parent(".js_selectortrigger").next("ul.js_productselector") ); return false; });
    jQuery("ul.js_productselector").bind("click",function(){ toggleEnlarge( jQuery(this) ); return false; });
    */
    jQuery("#js_growingpict .ill img").each(function() {
        var w = this.offsetWidth;
        var h = this.offsetHeight;
        var t = Math.round(h / 2);
        var l = Math.round(w / 2);
        jQuery(this).css({ "position": "relative", "width": "10px", "height": "10px", "top": t + "px", "left": l + "px" }).animate({ "left": "0px", "top": "0px", "height": h + "px", "width": w + "px" }, 800, "easeOutCirc");
    });

    jQuery("#main").each(function() {
        if (jQuery(this).children(".landingpage")[0]) {
            jQuery(this).next("#subnav").addClass("landing");
        }
    });
}

function startTickerStartPage(init) {
    if (jQuery("#question")[0]) {
        if (init) {
            jQuery("#question a").css({ "display": "block", "position": "absolute", "white-space": "nowrap" });
            var w = jQuery("#question a")[0].offsetWidth + 30;
            jQuery("#question a").css({ "left": "-" + w + "px" });
            jQuery("#question").css({ "position": "relative", "overflow": "hidden" });
            setTimeout("startTickerStartPage(false)", 2000);
        } else {
            jQuery("#question a").animate({ "left": "0px" }, 1000, "easeOutCirc");
        }
    }
}

// sIFR 3

function my_getCookie(name) {
    var arg = name + "=";
    var alen = arg.length;
    var clen = document.cookie.length;
    var i = 0;
    while (i < clen) {
        var j = i + alen;
        if (document.cookie.substring(i, j) == arg)
            return my_getCookieVal(j);
        i = document.cookie.indexOf(" ", i) + 1;
        if (i == 0) break;
    }

    return null;
}

function my_getCookieVal(offset) {
    var str = document.cookie.indexOf(";", offset);
    if (str == -1) str = document.cookie.length;
    return unescape(document.cookie.substring(offset, str));
}

function startSifr() {

    var lang = my_getCookie("CS_Language");

    if (!flashIsEnabled()) {
        return;
    }

    var univers45 = {
        src: 'Flash/Font/univers45.swf'
    };


    if (lang != null) {
        if (lang == "ru") {	// Temporary fix for russia
            univers45 = {
                src: 'Flash/Font/helveticacyr.swf'
            };
        }
    }

    sIFR.activate(univers45);

    sIFR.replace(univers45, {
        selector: '.landing_red h1'
	, wmode: 'transparent'
	, css: {
	    '.sIFR-root': { 'color': '#ffffff', 'letter-spacing': -0.7 }
	}
    });

    sIFR.replace(univers45, {
        selector: '.landing_black h1'
	, wmode: 'transparent'
	, css: {
	    '.sIFR-root': { 'color': '#d8d8d8', 'letter-spacing': -0.7 }
	}
    });

    sIFR.replace(univers45, {
        selector: 'h1'
	, wmode: 'transparent'
	, css: {
	    '.sIFR-root': { 'color': '#454545', 'letter-spacing': -0.7 }
	}
    });

    sIFR.replace(univers45, {
        selector: '.landing_black h2'
	, wmode: 'transparent'
	, css: {
	    '.sIFR-root': { 'color': '#a0a0a0', 'letter-spacing': -0.5 }
	}
    });

    sIFR.replace(univers45, {
        selector: 'h2'
	, wmode: 'transparent'
	, css: [
		'.sIFR-root { color: #454545, letter-spacing: -0.5 }'
		, 'a { text-decoration: none; }'
		, 'a:link { color: #454545; }'
		, 'a:hover { color: #333333; }'
		]
    });
}

/*
*
* 			jQuery Plugins
*
*/


/*
* edited version of ... (komatsu has only the easing functions it needs)
* jQuery EasIng v1.1.2 - http://gsgd.co.uk/sandbox/jquery.easIng.php
*
* Copyright (c) 2007 George Smith
* Licensed under the MIT License:
*   http://www.opensource.org/licenses/mit-license.php
*/

// t: current time, b: begInnIng value, c: change In value, d: duration

jQuery.extend(jQuery.easing,
{
    easeInCirc: function(x, t, b, c, d) {
        return -c * (Math.sqrt(1 - (t /= d) * t) - 1) + b;
    },
    easeOutCirc: function(x, t, b, c, d) {
        return c * Math.sqrt(1 - (t = t / d - 1) * t) + b;
    }
});

/*
* jQuery selectbox plugin
*
* (c) 2008 Elin Tjerngren, artopod.se 
* Licensed under the GPL license and MIT:
*   http://www.opensource.org/licenses/GPL-license.php
*   http://www.opensource.org/licenses/mit-license.php
*
* The code is inspired from Selectbox plugin by Sadri Sahraoui (http://brainfault.com)
*
*/
jQuery.fn.extend({
    selectbox: function(options) {
        if (!(
			(jQuery.browser.opera && jQuery.browser.version < 9.25) ||
			(jQuery.browser.msie && jQuery.browser.version < 7)
			)) { // edit by elin: filter out old operas
            return this.each(function() {
                new jQuery.SelectBox(this, options);
            });
        }
    }
});

jQuery.SelectBox = function(selectobj, options) {
    var $ = jQuery;  // local fix by elin

    var opt = options || {};
    opt.selClass = opt.selClass || "selectbox";
    opt.selStartClass = opt.selStartClass || "selectbox-start";
    opt.containerClass = opt.containerClass || "selectbox-wrapper";

    var elm_id = selectobj.id;
    var active = -1;
    var inFocus = false;
    var hasfocus = 0;
    //jquery object for select element
    var $select = $(selectobj);
    var $styledSelect = setupStyledSelect();
    updateSelectValue();
    $select.change(updateSelectValue);

    function setupContainer(options) {
        var container = document.createElement("div");
        $container = $(container);
        //$container.attr('id', elm_id+'_container');
        $container.addClass(options.containerClass);

        return $container;
    }

    function setupStyledSelect() {
        var el = document.createElement("div");
        var $styledSelect = $(el);
        $styledSelect.addClass(opt.selClass);
        $styledSelect.width(selectobj.offsetWidth); // width of the actual selectbox 
        $select.wrap('<div class="' + opt.containerClass + '"></div>').before($styledSelect);
        $styledSelect.wrap('<div class="' + opt.selStartClass + '"></div>');
        return $styledSelect;
    }

    function updateSelectValue() {
        $styledSelect.html($select.children("option:selected").html());
    }
};

/*
* Thickbox 3 - One Box To Rule Them All.
* By Cody Lindley (http://www.codylindley.com)
* Copyright (c) 2007 cody lindley
* Licensed under the MIT License: http://www.opensource.org/licenses/mit-license.php
*/

var tb_pathToImage = "Administration/WebsiteImages/loadingAnimation.gif";

//on page load call tb_init
$(document).ready(function() {
    tb_init('a[@rel*=lightbox], a.thickbox, area.thickbox, input.thickbox'); //pass where to apply thickbox
    imgLoader = new Image(); // preload image
    imgLoader.src = tb_pathToImage;
});

//add thickbox to href & area elements that have a class of .thickbox
function tb_init(domChunk) {
    jQuery(domChunk).click(function() {
        var t = this.title || this.name || this.imageid || null;
        var a = this.href || this.alt;
        var g = this.rel || false;
        tb_show(t, a, g);
        this.blur();
        return false;
    });
}

function tb_show(caption, url, imageGroup) {//function called when the user clicks on a thickbox link
    var $ = jQuery;
    try {
        if (typeof document.body.style.maxHeight === "undefined") {//if IE 6
            disableSelects(false);

            $("body", "html").css({ height: "100%", width: "100%" });
            $("html").css("overflow", "hidden");
            if (document.getElementById("TB_HideSelect") === null && url.indexOf("kfsurvey") == -1) {//iframe to hide select elements in ie6
                //$("body").append("<iframe id='TB_HideSelect'></iframe><div id='TB_overlay'></div><div id='TB_window'></div>");
                $("body").append("<div id='TB_overlay'></div><div id='TB_window'></div>");
                $("#TB_overlay").click(tb_remove);
            }
            else if (document.getElementById("TB_HideSelect") === null && url.indexOf("kfsurvey") != -1) {
                $("body").append("<div id='TB_overlay'></div><div id='TB_survey'></div>");
                $("#TB_overlay").click(tb_remove);

            }

            /*else
            {
            //$("body").append("<iframe id='TB_HideSelect'></iframe><div id='TB_overlay'></div><div id='TB_survey'></div>");
            $("body").append("<div id='TB_overlay'></div><div id='TB_survey'></div>");
            //$("body").append("<div id='TB_overlay'></div><div id='TB_survey'></div>");			    
            }*/

        }
        else {//all others

            if (document.getElementById("TB_overlay") === null && url.indexOf("kfsurvey") == -1) {
                $("body").append("<div id='TB_overlay'></div><div id='TB_window'></div>");
                $("#TB_overlay").click(tb_remove);
            }
            else if (document.getElementById("TB_overlay") === null && url.indexOf("kfsurvey") != -1) {
                $("body").append("<div id='TB_overlay'></div><div id='TB_survey'></div>");
                $("#TB_overlay").click(tb_remove);

            }
        }

        if (tb_detectMacXFF()) {
            $("#TB_overlay").addClass("TB_overlayMacFFBGHack"); //use png overlay so hide flash
        } else {
            $("#TB_overlay").addClass("TB_overlayBG"); //use background and opacity
        }

        if (caption === null) { caption = ""; }
        $("body").append("<div id='TB_load'><img src='" + imgLoader.src + "' /></div>"); //add loader to the page
        $('#TB_load').show(); //show loader

        var baseURL;
        if (url.indexOf("?") !== -1) { //ff there is a query string involved
            baseURL = url.substr(0, url.indexOf("?"));
        } else {
            baseURL = url;
        }

        var urlString = /\.jpg$|\.jpeg$|\.png$|\.gif$|\.bmp$/;
        var urlType = baseURL.toLowerCase().match(urlString);

        if (urlType == '.jpg' || urlType == '.jpeg' || urlType == '.png' || urlType == '.gif' || urlType == '.bmp') {//code to show images

            TB_PrevCaption = "";
            TB_PrevURL = "";
            TB_PrevHTML = "";
            TB_NextCaption = "";
            TB_NextURL = "";
            TB_NextHTML = "";
            TB_imageCount = "";
            TB_FoundURL = false;
            if (imageGroup) 
            {
                TB_TempArray = $("a[@rel=" + imageGroup + "]").get();
                TB_TempArray2 = $("a[@imageid]").get();

                for (TB_Counter = 0; ((TB_Counter < TB_TempArray.length) && (TB_NextHTML === "")); TB_Counter++) {
                    
                    var urlTypeTemp = TB_TempArray[TB_Counter].href.toLowerCase().match(urlString); //Giltig bildurl?

                    if (TB_TempArray2[TB_Counter].imageid != caption) 
                    { 
                        // Nej
                        if (TB_FoundURL) { //Är url:en hittad?
                            // Ja
                            TB_NextCaption = TB_TempArray2[TB_Counter].imageid;
                            TB_NextURL = TB_TempArray[TB_Counter].href;
                            TB_NextHTML = "<span id='TB_next'>&nbsp;&nbsp;<a href='#'>Next &gt;</a></span>";
                        }
                        else {
                            //Nej
                            TB_PrevCaption = TB_TempArray2[TB_Counter].imageid;
                            TB_PrevURL = TB_TempArray[TB_Counter].href;
                            TB_PrevHTML = "<span id='TB_prev'>&nbsp;&nbsp;<a href='#'>&lt; Prev</a></span>";
                        }
                    }
                    else {
                        TB_FoundURL = true;
                        TB_imageCount = "Image " + (TB_Counter + 1) + " of " + (TB_TempArray.length);
                    }
                }
            }

            //Reset caption!
            caption = '';    

            imgPreloader = new Image();
            imgPreloader.onload = function() {
                imgPreloader.onload = null;

                // Resizing large images - orginal by Christian Montoya edited by me.
                var pagesize = tb_getPageSize();
                var x = pagesize[0] - 150;
                var y = pagesize[1] - 150;
                var imageWidth = imgPreloader.width;
                var imageHeight = imgPreloader.height;
                if (imageWidth > x) {
                    imageHeight = imageHeight * (x / imageWidth);
                    imageWidth = x;
                    if (imageHeight > y) {
                        imageWidth = imageWidth * (y / imageHeight);
                        imageHeight = y;
                    }
                } else if (imageHeight > y) {
                    imageWidth = imageWidth * (y / imageHeight);
                    imageHeight = y;
                    if (imageWidth > x) {
                        imageHeight = imageHeight * (x / imageWidth);
                        imageWidth = x;
                    }
                }
                // End Resizing

                TB_WIDTH = imageWidth + 30;
                TB_HEIGHT = imageHeight + 60;
                $("#TB_window").append("<a href='' id='TB_ImageOff' title='Close'><img id='TB_Image' src='" + url + "' width='" + imageWidth + "' height='" + imageHeight + "' alt='" + caption + "'/></a>" + "<div id='TB_caption'>" + caption + "<div id='TB_secondLine'>" + TB_imageCount + TB_PrevHTML + TB_NextHTML + "</div></div><div id='TB_closeWindow'><a href='#' id='TB_closeWindowButton' title='Close'>close</a> or Esc Key</div>");

                $("#TB_closeWindowButton").click(tb_remove);

                if (!(TB_PrevHTML === "")) {
                    function goPrev() {
                        if ($(document).unbind("click", goPrev)) { $(document).unbind("click", goPrev); }
                        $("#TB_window").remove();
                        $("body").append("<div id='TB_window'></div>");
                        tb_show(TB_PrevCaption, TB_PrevURL, imageGroup);
                        return false;
                    }
                    $("#TB_prev").click(goPrev);
                }

                if (!(TB_NextHTML === "")) {
                    function goNext() {
                        $("#TB_window").remove();
                        $("body").append("<div id='TB_window'></div>");
                        tb_show(TB_NextCaption, TB_NextURL, imageGroup);
                        return false;
                    }
                    $("#TB_next").click(goNext);

                }

                document.onkeydown = function(e) {
                    if (e == null) { // ie
                        keycode = event.keyCode;
                    } else { // mozilla
                        keycode = e.which;
                    }
                    if (keycode == 27) { // close
                        tb_remove();
                    } else if (keycode == 190) { // display previous image
                        if (!(TB_NextHTML == "")) {
                            document.onkeydown = "";
                            goNext();
                        }
                    } else if (keycode == 188) { // display next image
                        if (!(TB_PrevHTML == "")) {
                            document.onkeydown = "";
                            goPrev();
                        }
                    }
                };

                tb_position();
                $("#TB_load").remove();
                $("#TB_ImageOff").click(tb_remove);
                $("#TB_window").css({ display: "block" }); //for safari using css instead of show
            };

            imgPreloader.src = url;
        } else {//code to show html

            var queryString = url.replace(/^[^\?]+\??/, '');
            var params = tb_parseQuery(queryString);

            TB_WIDTH = (params['width'] * 1) + 30 || 630; //defaults to 630 if no paramaters were added to URL
            TB_HEIGHT = (params['height'] * 1) + 40 || 440; //defaults to 440 if no paramaters were added to URL
            ajaxContentW = TB_WIDTH - 30;
            ajaxContentH = TB_HEIGHT - 45;

            if (url.indexOf('TB_iframe') != -1) {// either iframe or ajax window		
                urlNoQuery = url.split('TB_');
                $("#TB_iframeContent").remove();
                if (params['modal'] != "true") {//iframe no modal
                    $("#TB_window").append("<div id='TB_title'><div id='TB_ajaxWindowTitle'>" + caption + "</div><div id='TB_closeAjaxWindow'><a href='#' id='TB_closeWindowButton' title='Close'>close</a> or Esc Key</div></div><iframe frameborder='0' hspace='0' src='" + urlNoQuery[0] + "' id='TB_iframeContent' name='TB_iframeContent" + Math.round(Math.random() * 1000) + "' onload='tb_showIframe()' style='width:" + (ajaxContentW + 29) + "px;height:" + (ajaxContentH + 17) + "px;' > </iframe>");
                } else {//iframe modal
                    $("#TB_overlay").unbind();
                    $("#TB_window").append("<iframe frameborder='0' hspace='0' src='" + urlNoQuery[0] + "' id='TB_iframeContent' name='TB_iframeContent" + Math.round(Math.random() * 1000) + "' onload='tb_showIframe()' style='width:" + (ajaxContentW + 29) + "px;height:" + (ajaxContentH + 17) + "px;'> </iframe>");
                }
            }
            else {// not an iframe, ajax
                if (url.indexOf("kfsurvey") == -1) {
                    if ($("#TB_window").css("display") != "block") {
                        if (params['modal'] != "true") {//ajax no modal
                            $("#TB_window").append("<div id='TB_title'><div id='TB_ajaxWindowTitle'>" + caption + "</div><div id='TB_closeAjaxWindow'><a href='#' id='TB_closeWindowButton'>close</a> or Esc Key</div></div><div id='TB_ajaxContent' style='width:" + ajaxContentW + "px;height:" + ajaxContentH + "px'></div>");
                        } else {//ajax modal
                            $("#TB_overlay").unbind();
                            $("#TB_window").append("<div id='TB_ajaxContent' class='TB_modal' style='width:" + ajaxContentW + "px;height:" + ajaxContentH + "px;'></div>");
                        }
                    } else {//this means the window is already up, we are just loading new content via ajax
                        $("#TB_ajaxContent")[0].style.width = ajaxContentW + "px";
                        $("#TB_ajaxContent")[0].style.height = ajaxContentH + "px";
                        $("#TB_ajaxContent")[0].scrollTop = 0;
                        $("#TB_ajaxWindowTitle").html(caption);
                    }
                }
                else {
                    if ($("#TB_survey").css("display") != "block") {
                        if (params['modal'] != "true") {//ajax no modal
                            $("#TB_survey").append("<div id='TB_title'><div id='TB_ajaxWindowTitle'>" + caption + "</div><div id='TB_closeAjaxWindow'><a href='#' id='TB_closeWindowButton'>close</a> or Esc Key</div></div><div id='TB_ajaxContent' style='width:" + ajaxContentW + "px;height:" + ajaxContentH + "px'></div>");
                        }
                        else {//ajax modal
                            $("#TB_overlay").unbind();
                            $("#TB_survey").append("<div id='TB_surveyContent' class='TB_modal' style='width:" + ajaxContentW + "px;height:" + ajaxContentH + "px;'></div>");
                        }
                    }
                    else {
                        //this means the window is already up, we are just loading new content via ajax
                        $("#TB_surveyContent")[0].style.width = ajaxContentW + "px";
                        $("#TB_surveyContent")[0].style.height = ajaxContentH + "px";
                        $("#TB_surveyContent")[0].scrollTop = 0;
                        $("#TB_ajaxWindowTitle").html(caption);
                    }
                }
            }

            $("#TB_closeWindowButton").click(tb_remove);

            if (url.indexOf('TB_inline') != -1) {
                if (url.indexOf("kfsurvey") == -1) {
                    $("#TB_ajaxContent").append($('#' + params['inlineId']).children());
                    $("#TB_window").unload(function() {
                        $('#' + params['inlineId']).append($("#TB_ajaxContent").children()); // move elements back when you're finished
                    });
                }
                else {
                    $("#TB_surveyContent").append($('#' + params['inlineId']).children());
                    $("#TB_survey").unload(function() {
                        $('#' + params['inlineId']).append($("#TB_surveyContent").children()); // move elements back when you're finished
                    });
                }

                tb_position();
                $("#TB_load").remove();
                // TODO: Copy
                if (url.indexOf("kfsurvey") == -1) {
                    $("#TB_window").css({ display: "block" });
                }
                else {
                    $("#TB_survey").css({ display: "block" });
                }
            } else if (url.indexOf('TB_iframe') != -1) {
                tb_position();
                if ($.browser.safari) {//safari needs help because it will not fire iframe onload
                    $("#TB_load").remove();
                    $("#TB_window").css({ display: "block" });
                }
            } else {
                $("#TB_ajaxContent").load(url += "&random=" + (new Date().getTime()), function() {//to do a post change this load method
                    tb_position();
                    $("#TB_load").remove();
                    tb_init("#TB_ajaxContent a.thickbox");

                    if (url.indexOf("kfsurvey") == -1) {
                        $("#TB_window").css({ display: "block" });
                    }
                    else {
                        $("#TB_survey").css({ display: "block" });
                    }
                });
            }

        }

        if (!params['modal']) {
            document.onkeyup = function(e) {
                if (e == null) { // ie
                    keycode = event.keyCode;
                } else { // mozilla
                    keycode = e.which;
                }
                if (keycode == 27) { // close
                    tb_remove();
                }
            };
        }

    } catch (e) {
        //nothing here
    }
}

//helper functions below
function tb_showIframe() {
    jQuery("#TB_load").remove();
    jQuery("#TB_window").css({ display: "block" });
}

function tb_remove() {
    jQuery("#TB_imageOff").unbind("click");
    jQuery("#TB_closeWindowButton").unbind("click");
    jQuery("#TB_window").fadeOut("fast", function() { jQuery('#TB_window,#TB_overlay,#TB_HideSelect').trigger("unload").unbind().remove(); });

    //TODO: Copy
    jQuery("#TB_survey").fadeOut("fast", function() { jQuery('#TB_survey,#TB_overlay,#TB_HideSelect').trigger("unload").unbind().remove(); });

    jQuery("#TB_load").remove();
    if (typeof document.body.style.maxHeight == "undefined") {//if IE 6
        jQuery("body", "html").css({ height: "auto", width: "auto" });
        jQuery("html").css("overflow", "");
    }
    document.onkeydown = "";
    document.onkeyup = "";

    if (typeof document.body.style.maxHeight === "undefined") {//if IE 6
        disableSelects(true);
    }

    return false;
}

function tb_position() {
    jQuery("#TB_window").css({ marginLeft: '-' + parseInt((TB_WIDTH / 2), 10) + 'px', width: TB_WIDTH + 'px' });
    if (!(jQuery.browser.msie && jQuery.browser.version < 7)) { // take away IE6
        jQuery("#TB_window").css({ marginTop: '-' + parseInt((TB_HEIGHT / 2), 10) + 'px' });
    }

    //TODO: Copy
    jQuery("#TB_survey").css({ marginLeft: '-' + parseInt((TB_WIDTH / 2), 10) + 'px', width: TB_WIDTH + 'px' });
    if (!(jQuery.browser.msie && jQuery.browser.version < 7)) { // take away IE6
        jQuery("#TB_survey").css({ marginTop: '-' + parseInt((TB_HEIGHT / 2), 10) + 'px' });
    }
}

function tb_parseQuery(query) {
    var Params = {};
    if (!query) { return Params; } // return empty object
    var Pairs = query.split(/[;&]/);
    for (var i = 0; i < Pairs.length; i++) {
        var KeyVal = Pairs[i].split('=');
        if (!KeyVal || KeyVal.length != 2) { continue; }
        var key = unescape(KeyVal[0]);
        var val = unescape(KeyVal[1]);
        val = val.replace(/\+/g, ' ');
        Params[key] = val;
    }
    return Params;
}

function tb_getPageSize() {
    var de = document.documentElement;
    var w = window.innerWidth || self.innerWidth || (de && de.clientWidth) || document.body.clientWidth;
    var h = window.innerHeight || self.innerHeight || (de && de.clientHeight) || document.body.clientHeight;
    arrayPageSize = [w, h];
    return arrayPageSize;
}

function tb_detectMacXFF() {
    var userAgent = navigator.userAgent.toLowerCase();
    if (userAgent.indexOf('mac') != -1 && userAgent.indexOf('firefox') != -1) {
        return true;
    }
}
function disableSelects(show) {
    var selects = document.getElementsByTagName("select");

    var value;
    if (show)
        value = "block";
    else
        value = "none";

    for (i = 0; i < selects.length; i++) {
        selects[i].style.display = value;
    }


}

/* ************************************************************ */
/* Insert av flash video into the page. 			*/
/* Parameters:							*/
/*	divId 	- Id (string) of the div to put the player in.	*/
/*	flvUrl 	- URL to the FLV to play.			*/
/* Requires: SWFObject 1.5 and jQuery 1.2.1			*/
/* Author: David Haglund, Sogeti.				*/
/* ************************************************************ */
function showVideo(divId, flvUrl) {
    var videoOriginalWidth = 4;
    var videoOriginalHeight = 3;
    var controlBarHeight = 24;
    var swfUrl = "http://www.komatsuforest.com/Flash/FlashMovies/KomatsuVideo.swf";
    var divWidth;
    if ($('#' + divId) != undefined) {
        divWidth = $('#' + divId).width();
    }
    else {
        //IE6 fix
        var flashDiv = document.getElementById(divId);
        divWidth = flashDiv.offsetWidth;
    }
    var percentage = divWidth / videoOriginalWidth;
    var divHeight = percentage * videoOriginalHeight + controlBarHeight;
    var swo = new SWFObject(swfUrl, "KomatsuVideoSWF", divWidth, divHeight, "8");
    swo.addParam("allowFullScreen", "true");
    swo.addVariable("flvUrl", flvUrl);
    swo.addVariable("swfWidth", divWidth);
    swo.write(divId);
}