﻿/**
 * Global JS 
 *
 */

window.navHeight = 400;    // This is with banana, also see line 921
window.theCampaignImage;
window.campaignLength;
window.campaignClickTime = new Date();
window.markerad;	
window.unikId = "";
window.languageBranch;
window.gvStoreID = 0;

/*window.onerror = function (msg, url, line) {
    var errorObj = {
        "message" : msg,
        "jsUrl" : url,
        "docUrl" : document.location.href,
        "line" : line,
        "clientTime" : new Date(),
        "userAgent" : navigator.userAgent
    }
    
    $.post("/JavaScriptErrorHandler.ashx", errorObj);
};*/

String.prototype.trim = function () {
    return this.replace(/(^\s+)|(\s+$)/g, "");
};

function splitThousands(nStr) {
    var nStr,
    x,
    x1,
    x2,
    rgx;
    
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ' ' + '$2');
	}
	return x1 + x2;
}

function getStyle(elem, style) {
    var result, replacer;
    if (elem.currentStyle) { //IE
        replacer = function (match) {
            return match.replace(/\-/, "").toUpperCase();
        };
        style = style.replace(/\-[a-z]/, replacer);
        result = elem.currentStyle[style];
    } else { // Standard
        result = document.defaultView.getComputedStyle(elem, null).getPropertyValue(style);
    }
    return result;
}

function styleIsSupported(style) {
    var mozWebkit, result = false, style2, replacer1, replacer2;
    
    replacer1 = function (match) {
        return match.toUpperCase();
    };
    style2 = style.replace(/^[a-z]/g, replacer1);
    
    replacer2 = function (match) {
        return match.replace(/\-/, "").toUpperCase();
    };
    style2 = style2.replace(/\-[a-z]/g, replacer2);
    
    if (typeof document.body.style[style] === "string") {
        // if the style/cssProperty exists return true
        result = true;
    } else if (typeof document.body.style[style.replace(/\-[a-z]/, replacer2)] === "string") {
        result = true;
    } else {
        // Check for Mozilla and Webkit specials
        // There should probably be som sort of '-ms-' ans -o- check too.
        
        mozWebkit = (/webkit/i).test(navigator.userAgent) ? "Webkit" : "Moz";
        
        if (document.body.style[mozWebkit + style2] || (!document.body.style[mozWebkit + style2] && typeof document.body.style[mozWebkit + style2] === "string")) {
            result = true;
        }
    }
    
    return result;
}

function addCorners (elem, shouldSupport) {
    var e = $(elem),
    css3 = function () {
        var dontAdd = true,
        i,
        format;
        
        if (shouldSupport) {
            for (i = 0; i < shouldSupport.length; i += 1) {
                format = shouldSupport[i].replace(/([A-Z])/, "-$1").toLowerCase().trim();
                if (!styleIsSupported(format)) {
                    dontAdd = false;
                    break;
                }
            }
        } else {
            dontAdd = false;
        }
        
        return dontAdd;
    },
    add = css3();
    
    if (elem.tagName && !add) {
    
        if (shouldSupport) {
            e.addClass("notCss3");
        }
                
        e.wrapInner("<div class=\"riBo\"><div class=\"leBo\"><div class=\"midWrap\"></div></div></div>");
        e.prepend("<div class=\"fcTop\"><div class=\"leCo\"></div><div class=\"riCo\"></div><div class=\"midFill\"></div></div>");
        e.append("<div class=\"fcBottom\"><div class=\"leCo\"></div><div class=\"riCo\"></div><div class=\"midFill\"></div></div>");
    
    }
            
}


function getAllStyles(elem) {
    var result = [], keys, cs = elem.currentStyle;
    
    for (keys in cs) {
        if (cs[keys] && (cs[keys] !== "auto")) {
            result.push([keys, cs[keys]]);
        }
    }
    
    return result;
}

function copyStyle(elem) {
    var cStyles = getAllStyles(elem), i;
    
    for (i = 0; i < cStyles.length; i += 1) {
        elem.style[cStyles[i][0]] = cStyles[i][1];
    }
}

function alertObjectKeys (obj, not) {
    var keys, 
    str = ""
    ar = arguments,
    add = true,
    i = 1;
    
    if (typeof obj === "object") {
        if (ar.length < 3) {
            for (keys in obj) {
                if (obj[keys] !== not) {
                    str += keys + " = " + obj[keys] + "\n";
                }
            }
        } else {
            for (keys in obj) {
                add = true;
                for (i = 1; i < ar.length; i += 1) {
                    if (typeof obj[keys] === ar[i] || obj[keys] === ar[i]) {
                        add = false;
                        break;
                    }
                }
                
                if (add) {
                    str += keys + " = " + obj[keys] + "\n";
                }
            }
        }
    }
    
    alert(str);
}

function getRegion(region) {
    var main = $("div.slideContainer div.allMovies")[0],
    regionCont = $("div.slideContainer div.regionMovies")[0],
    getLangAndMarket = function () {
        var result = {}, 
        bcn = document.body.className,
        mid = $("div.wide.flashList").length ? $("div.wide.flashList")[0].className : "";
        
        result.lang = bcn.match(/language\-[a-z]{2}/ig).toString().trim().replace(/language\-/, "");
        result.market = bcn.match(/market\-[a-z]+(\s|$)/ig).toString().trim().replace(/market\-/, "");
        result.movieId = mid ? mid.match(/(^|\s)mid[\w]+/g).toString().replace(/(^|\s)mid/, "") : "";
        
        return result;
    },
    lm = getLangAndMarket(),
    lang = lm.lang,
    market = lm.market,
    movieId = lm.movieId,
    newTr,
    getReg = function () {
        $.getJSON("/Ajax/UpdateConstructionProjectList.ashx", {
            "region" : region, 
            "market" : market, 
            "lang" : lang, 
            "movieid" : movieId
        }, function (json) {
            var newTrs = json.items, 
            i,
            tb = $("div.slideContainer div.regionMovies tbody")[0];
            $("h2.regionContainer")[0].innerHTML = json.region;
            
            $(tb).find("tr").each(function () {
                $(this).remove();
            });
            
            for (i = 0; i < newTrs.length; i += 1) {
                addTr(tb, newTrs[i]);
            }
            
            slide("ltr");
            
            $("div.slideContainer a").each(function () {
                var loc = this.href;
                $(this).parents("td:not(.hasClick), tr:not(.hasClick)").css({
                    cursor : "pointer"
                }).addClass("hasClick").click(function (e) {
                    document.location = loc;
                });
            });
        });
    },
    addTr = function (tb, item) {
        newTr = "";
        newTr += "<tr class=\"" + item.oddEven + "\">";
        newTr += "<td  class=\"first-child\"><a href=\"" + item.td1.href + "\"><img src=\"" + item.td1.src + "\" alt=\"\" /></a></td>";
        newTr += "<td class=\"movieDescription\"><h2><a href=\"" + item.td2.href + "\">" + item.td2.h2 + "</a></h2>";
        newTr += "<p>" + item.td2.text + "</p>";
        newTr += "</td>"
        newTr += "</tr>";
        
        $(tb).append(newTr);
    },
    slide = function (dir) {
        var amw,
        time = 500;
        if (dir === "ltr") {
            $("div.slideContainer > div.allMovies").each(function () {
                var toLeft = "-" + this.offsetWidth + "px";
                
                amw = this.offsetWidth;
                
                $(this).animate({
                    left : toLeft
                }, time);
            });
            $("div.slideContainer > div.regionMovies").each(function () {
                var toLeft = "-" + parseInt(this.offsetWidth - amw, 10) + "px";
                $(this).animate({
                    left : toLeft
                }, time);
            });
        } else {
            $("div.slideContainer > div.allMovies").each(function () {
                amw = this.offsetWidth;
                $(this).animate({
                    left : 0
                }, time);
            });
            $("div.slideContainer > div.regionMovies").each(function () {
                var toLeft = parseInt(amw, 10) + "px";
                $(this).animate({
                    left : toLeft
                }, time);
            });
        }
    };
    
    if (!region) {
        region = 0;
    }
    
    
    if (region === 0) {
        slide("rtl");
    } else { 
        regionCont.style.left = main.offsetWidth + "px";
        regionCont.style.top = parseInt(main.offsetTop - main.offsetHeight, 10) + "px";
        getReg();
    }
}

function display360Product(productId) {
    var flashvars = {
        xmlData : "/xml/View360XmlFeed.ashx?productID=" + productId
    },
    params = { wmode: "transparent", allowScriptAccess: "always" },
    attributes = {};
    
    swfobject.embedSWF("/Flash/view360/view360.swf", "view360Flash", "534", "534", "9.0.0", "expressInstall.swf", flashvars, params, attributes);
    
    //productImage
    $(".productImage img").addClass("hideImp")
    $(".productImageThumbs img").removeClass("selected");
}

jQuery.fn.extend({
    "replaceClass" : function (oldClassName, newClassName) {
        var t = $(this);
        t.removeClass(oldClassName);
        t.addClass(newClassName);
    },
    "bindMulti" : function () {
        var that = this, evts = [], i, func, t;
        
        for (i = 0; i < arguments.length; i += 1) {
            if (typeof arguments[i] === "function") {
                // It is possible to define more than one function/method but it is the last one that will be used.
                func = arguments[i];
            } else {
                // The arguments should be strings separated by commas. ("click", "focus", "keyup")
                // But the "jQuery style" (meaning a comma separated string: "click, focus, keyup") will also work.
                evts = evts.concat(arguments[i].toString().replace(/(\s?,\s?)/g, ",").split(","));
            }
        }
        
        t = $(that);
        that.each(function () {
            for (i = 0; i < evts.length; i += 1) {
                // Do the binding.
                t.bind(evts[i].trim(), func);
            }
        });

        return that;
    },
    "removeText" : function () {
        var that = this;
        that.each(function () {
            var that2 = this, i, cn = that2.childNodes;
            for (i = cn.length - 1; i > -1; i -= 1) {
                if (!cn[i].tagName) {
                    that2.removeChild(cn[i]);
                }
            }
        });
        return that;
    },
    "toArray" : function () {
        var result = [], i;
        
        if (this.length) {
            for (i = 0; i < this.length; i+= 1) {
                result.push(this[i]);
            }
        }
        
        return result;
    },
    getOPM : function () { // get Object Properties and Methods
        var that = this, 
        str = "", 
        keys,
        type = arguments.length ? arguments[0] : false;
        
        for (keys in that) {
            if (!type) {
                str += keys + " = " + that[keys] + "\n";
            } else if (type && typeof that[keys] === type) {
                str += keys + " = " + that[keys] + "\n";
            }
        }
        
        return str;
    },
    toggleFade : function (that) {
        var that2 = this,
        stoShow,
        stoHide,
        elem,
        ua = navigator.userAgent,
        mc,
        pcc,
        getMouseCoords = function (e) {
            var evt = e ? e : window.event;
            mc = {
                x : evt.pageX,
                y : evt.pageY
            };
        },
        getPrevCoords = function (previewContainer) {
            var pc = previewContainer,
            ofs = $(pc).offset();
            
            return {
                top : ofs.top,
                left : ofs.left,
                right : parseInt(ofs.left + pc[0].offsetWidth, 10),
                bottom : parseInt(ofs.top + pc[0].offsetHeight, 10)
            };
        },
        showPrev = function () {
            clearTimeout(stoHide);
            var all = $(that2).find("*"),
            stoOut;
            
            if (elem) {
                if (that2.css("display") === "none") {
                    if ((/MSIE\s[78]/).test(ua)) {
                        that2.css({
                            background : "#fff"
                        });
                    }
                    that2.css({
                        opacity : "0",
                        display : "block"
                    }).animate({
                        opacity : "1"
                    }, "slow", function () {
                        pcc = getPrevCoords(that2);
                        
                        if ((mc.y < pcc.top) || (mc.y > pcc.bottom) || 
                        (mc.x < pcc.left) || (mc.x > pcc.right)) {
                            stoHide = setTimeout(hidePrev, 1000);
                        }
                        
                        that2.mouseover(function (e) {
                            e.preventDefault();
                            clearTimeout(stoHide);
                        });
                        
                        all.mouseover(function () {
                            clearTimeout(stoOut);
                            clearTimeout(stoHide);
                        });
                        
                        that2.bind("mouseout", function (e) {
                            stoOut = setTimeout(hidePrev, 10);
                        });
                        
                        if ((/MSIE\s[78]/).test(ua)) {
                            that2.css({
                                opacity : "",
                                background : "Transparent"
                            });
                        }
                    });
                }
            }
        },
        hidePrev = function (e) {
            clearTimeout(stoShow);
            if (elem) {
                if (that2.css("display") === "block") {
                    
                    if ((/MSIE\s[78]/).test(ua)) {
                        that2.css({
                            background : "#fff"
                        });
                    }
                    
                    that2.animate({
                        opacity : "0"
                    }, "slow", function () {
                        that2.css({
                            display : "none"
                        });
                    });
                }
            }
        },
        omOver = function (e) {
            e.preventDefault();
            
            elem = that2.length ? that2[0] : null;
            stoShow = setTimeout(showPrev, 500);
            
            $(that).mouseout(function (e) {
                e.preventDefault();
                clearTimeout(stoShow);
            });
        };
        
        $(that).bind("mouseover", omOver);
        
        
        $(document.body).bind("mousemove", getMouseCoords);
    }
});


/**
 * Pre loader 
 *
 * This loads as parsed that is prior to main loader.
 */
//byggmaxSearch();       // call external clickview js


/**
 * Main loader 
 *
 * This loads events after the DOM is loaded, but prior to images 
 * and objects.
 */
 
if (!window.globalVariables) {
    window.globalVariables = {};
}
 
$(document).ready(function () {
    var testTopZip,
        bmCookieZip,
        st,
        note,
        noteDiv;

    /*$("img[src$='sverige_bygger_flash.jpg']").click(function () {
        getRegion();
    });*/
    
    if ((/MSIE\s6/).test(navigator.userAgent)) {
        if (globalVariables && globalVariables.ie6 && globalVariables.ie6.notice) {
            st = $(".startTicker");
            note = globalVariables.ie6.notice;
            noteDiv = "<div class=\"ie6Notice\">" + note + "</div>";
            
            if (st.length) {
                st[0].style.height = "auto";
                st[0].innerHTML += noteDiv;
            } else {
                $(".outer > .left").before("<div class=\"startTicker\" style=\"height: auto;\">" + noteDiv + "</div>");
            }
        }
    
        
        $("span.flag").each(function () {
            var orgSrc = getStyle(this, "background-image").trim().replace(/(^url\("|"\)$)/g, "");
            if (orgSrc !== "none") {
                this.style.backgroundImage = "none";
                this.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + orgSrc.replace(/^(url\('|'\))/g, "") + "', sizingMethod='crop')";
            }
        });
    }
    
    function zipcodeSplash() {
        //.start .splash .center
        var startBody = $("body.start"), 
        sb = $(startBody), 
        dofsw = document.body.offsetWidth, 
        dofsh = document.body.offsetHeight, 
        sideFillerWidthOrg,
        sideFillerWidth, 
        textBlock,
        sCenter,
        capEnter,
        inputDigits,
        gs = globalVariables.splash,
        splashBG,
        loadSplash;
        
        capEnter = function (e) {
            var enter = (e.keyCode === 13) ? true : false;
            
            if (enter) {
                $(".splash .buyButton").trigger("click");
                $(document).unbind("keypress", capEnter);
            }
        };
        
        $("body").addClass("splash");
        
        startBody.append("<div class=\"splash\"><div class=\"filler top right\"></div><div class=\"filler top left\"></div><div class=\"sCenter\"></div><div class=\"filler bottom\"></div></div>");
        
        sCenter = $(".sCenter").length ? $(".sCenter")[0] : null;
        
        if (sCenter) {
            sideFillerWidthOrg = parseFloat(((dofsw - sCenter.offsetWidth) / 2), 10);
            //sideFillerWidth = parseInt(((dofsw - sCenter.offsetWidth) / 2), 10);
            sideFillerWidth = (/MSIE\s[567]/).test(navigator.userAgent) ? parseInt(((dofsw - 525) / 2), 10) : $("body > .splash .sCenter")[0].offsetLeft;

            
            /*if (!(/Opera|Chrome/).test(navigator.userAgent) && (sideFillerWidthOrg > sideFillerWidth)) {
                sideFillerWidth += 1;
            }*/
            
            sb.find(".filler.top").css({
                width : sideFillerWidth + "px"
            });
            
            sb.find(".filler.top.right").css({
                left : parseInt(sideFillerWidth + 525, 10) + "px"
            });
            
            sb.find(".filler.bottom").css({
                height : parseInt((dofsh - 565) + 220, 10) + "px"
            });
            
            textBlock = "<p class=\"splashHeader\">" + gs.header + "</p>";
            textBlock += "<p>" + gs.mainText.replace(/\s\[/, " <span class=\"zipHighlight\">").replace(/\]\s/, "</span> ") + "<label><input type=\"text\" /></label></p>";
            
            textBlock += "<p>";
            textBlock += "<a href=\"#\" class=\"bigButton buyButton\"><span class=\"begin\"><!-- v --></span><span class=\"text\"><span>" + gs.readyButton + "</span></span><span class=\"end\"><!-- v --></span></a>";
            
            textBlock += "<a href=\"#\" class=\"bigButton calcButton\"><span class=\"begin\"><!-- v --></span><span class=\"text\"><span>" + gs.cancelButton + "</span></span><span class=\"end\"><!-- v --></span></a>";
            textBlock += "</p>";
          
            sb.find(".sCenter").append("<div class=\"zipInfo\">" + textBlock + "</div>");
            
            setTimeout(function () {
                var dbc = $(document.body), zipLength = 5;
                if (dbc.hasClass("market-Norweigan")) {
                    zipLength = 4;
                }
                
                sb.find(".splash input").attr("maxlength", zipLength);
                sb.find(".splash input").focus();
                sb.find(".splash input").bind("keyup", "change", function () {
                    this.value = this.value.replace(/\D/g, "").substring(0, zipLength);
                });
            }, 100);
            
            // add triggers to the splash zipcode input and buttons
            sb.find(".splash input").keyup(function () {
                var that = this;
                $(".login .topzip").attr("value", that.value);
            });
            
            // The green button
            sb.find(".buyButton").click(function (e) {
                e.preventDefault();
                
                createCookie("askForZip", "false", 999);
                
                if (styleIsSupported("opacity")) {
                    $("body > .splash").animate({
                        opacity: 0
                    }, "fast", function () {
                        $(this).remove();
                        $("body").removeClass("splash");
                    });
                } else {
                    $("body > .splash").remove();
                    $("body").removeClass("splash");
                }
                
                $(".login .topzip").each(function () {
                    var t = $(this), selectStore;
                    
                    t.trigger("keyup");
                    
                    selectStore = function () {
                        var lts = $(".login .topstore");
                        
                        if (lts.find("optgroup").length) {
                            if (lts.find("option")[1]) {
                                lts.find("option")[1].selected = "selected";
                                lts.change();
                            }
                        } else {
                            setTimeout(selectStore, 100);
                        }
                    };
                    
                    setTimeout(selectStore, 100);
                });
                
                $(document).unbind("keypress", capEnter);
            });
            
            // The red button
            sb.find(".calcButton").click(function (e) {
                e.preventDefault();
                
                createCookie("askForZip", "false", 999);
                
                if (styleIsSupported("opacity")) {
                    $("body > .splash").animate({
                        opacity: 0
                    }, "fast", function () {
                        $(this).remove();
                        $("body").removeClass("splash");
                    });
                } else {
                    $("body > .splash").remove();
                    $("body").removeClass("splash");
                }
                
                $(document).unbind("keypress", capEnter);
            });
            
            $(".splash .zipInfo").each(function () {
                this.focus();
            });
            
            $(document).bind("keypress", capEnter);
            
            $(window).resize(function () {
                if ($("body > .splash .sCenter").length && $("body > .splash .sCenter")[0]) {
                    dofsw = document.body.offsetWidth;
                    dofsh = document.body.offsetHeight;
                    
                    sideFillerWidth = (/MSIE\s[567]/).test(navigator.userAgent) ? parseInt(((dofsw - 525) / 2), 10) : $("body > .splash .sCenter")[0].offsetLeft;
                
                    sb.find(".filler.top").css({
                        width : sideFillerWidth + "px"
                    });
                    
                    sb.find(".filler.top.right").css({
                        left : parseInt(sideFillerWidth + 525, 10) + "px"
                    });
                    
                    sb.find(".filler.bottom").css({
                        height : parseInt((dofsh - 565) + 220, 10) + "px"
                    });
                }
            });

            /** Attach click event to close splash when clicking on the faded area **/
            $('.filler').click(function (e) {
                if (styleIsSupported("opacity")) {
                    $("body > .splash").animate({
                        opacity: 0
                    }, "fast", function () {
                        $(this).remove();
                        $("body").removeClass("splash");
                    });
                } else {
                    $("body > .splash").remove();
                    $("body").removeClass("splash");
                }
                
                $(document).unbind("keypress", capEnter);
            });
        }
    }
    
    bmCookieZip = document.cookie ? document.cookie.toString().match(/zip[A-Z]{2}\=\d+/) : null;
    
    if (!bmCookieZip) {
        testTopZip = $(".login .topzip"); //.attr("value").trim();
        if (testTopZip.length) {
            testTopZip = testTopZip.attr("value").trim();
        } 
        bmCookieZip = (/\d+/).test(testTopZip) ? true : false;
    }
    
    if (!bmCookieZip && !(/MSIE\s[56]/).test(navigator.userAgent) && !document.cookie.match(/askForZip\=false/)) {
        
        splashBG = document.createElement("img");
        splashBG.src = "/image/startSplash/splashCenter.png";
        
        $(splashBG).css({
            position : "absolute",
            top : "-1000px"
        });
        
        document.body.appendChild(splashBG);
        
        loadSplash = function () {
            if (splashBG.offsetHeight && splashBG.offsetWidth) {
                zipcodeSplash();
                document.body.removeChild(splashBG);
            } else {
                setTimeout(loadSplash, 10);
            }
        };
        
        loadSplash();
    }
    
    /*$("table").each(function () {
        this.cellPadding = 0;
        this.cellSpacing = 0;
    });*/

    languageBranch = $("#ctl00_HFlanguage").val();
    gvStoreID = $("#ctl00_HFstoreId").val();


	/* =PRODUCTS
	 * -------------------------------------------------------------- */
 
	if ($("div.products").length > 0) {		// Page contains product list
//		productlistCheckInterval();		// functionality in .net instead = faster klient loads

		setTimeout(function () {
			productToCart(".products .product .add img", false);
			productAmountEvents();
			loadTooltips();
			//showEcommerceGuideOnce();
			askForZip();
			makeSeparatorBarFixed();
	        truncateTextBox();
		}, 1);

		if ($("div.productContainer").length > 0) {		// Page is product page
			productToCart("#addStuff", true);
			productpageStorePicker();
			productpageThumbs();
	        frameworkHover();					// Image hover function
		}

		if ($("div.shoppinglist").length > 0) {		// TODO: Cart page needs some more love
			commerceGeneral();
			commerceCheckConditions();			// Check if user agreed to terms & conditions
			cartStorePicker();					// commerce enabled stores only
		}

	}
	else {
		startpageCampaignMonitor();
		modalCustom();
		commerceGeneral();
		aboutFaq();
		aboutGeneral();
		commerceCheckConditions();			// Check if user agreed to terms & conditions
	}

	/* =FRAMEWORK
	 * -------------------------------------------------------------- */
    if (window.Qww !== null) {
        qvLiveSearch();
    }

	setTimeout(function () {
		productBlockNonDigits();
		frameworkStorePicker();
		navigationProducts();
		navigationProjects();
		frameworkLanguage();
		modalCustom();
//		askForSurvey();
	}, 1);
	
	if ($("ul.aboutNav").length) {
	    
	    var t = $("ul.aboutNav"), 
	    ofs = t.offset(), 
	    fromTop = ofs.top;
	    
	    $(window).scroll(function (e) {
	       
	        var sy = this.scrollY;
	        
	        if (!sy && sy !== 0) {
	            sy = document.documentElement.scrollTop;
	        }
	        
	        if (sy > (120 - 33)) {
	            t.css({
                    position: 'fixed',
	                top : 0
	            });
	        } else {
	            t.css({
                    position: 'absolute',
	                top : "120px"
	            });
	        }
	        
	    });
	}
	
	//alert("Mossning");
	//table.productList tr.product
	
});


/**
 * This loads events after the document has been fully loaded, 
 * with images and objects.
 */
 
$(window).load(function () {
	productlistHover();						// Adds yellow hover over effect on table rows
});


function rotateCampaign() {
	theCampaignCurrentTime = new Date();
	if (theCampaignCurrentTime - campaignClickTime >= 7990) {
		if (theCampaignImage >= (campaignLength - 1)) {
			theCampaignImage = 0;
		} else {
			theCampaignImage += 1;
		}
		if (!theCampaignImage) {
			$("div.campaignMonitor ul li:first").css({
				left : ((169 * campaignLength)) + "px"
			});
			$("div.campaignMonitor ul").animate({
				left : -(169 * campaignLength) + "px"
			}, "slow", function () {
				$("div.campaignMonitor ul li:first").css({
					left : "0px"
				});
				$("div.campaignMonitor ul").css({
					left : "0px"
				});
			});
		} else {
			$("div.campaignMonitor ul").animate({
				left : -(169 * theCampaignImage) + "px"
			}, "slow");
		}
		$("div.campaignMonitor .bullet").attr("src", "/image/bullet.slides.passive.gif");
		$("div.campaignMonitor .bullet:eq(" + theCampaignImage + ")").attr("src", "/image/bullet.slides.active.gif");
		setTimeout(rotateCampaign, 8000);
	}
}
function sumThisUp(productId) {
	window.theOrigSum = 0; // Don't know if this variabel needs to be global.
	
	//alert("productId = " + productId + "\n---\nfunc = " + arguments.callee);
	
	$("#" + productId).parents(".orderSub").find(".productid").filter(function (i) {
		return $(this).attr("id");
	}).siblings(".total").each(function () {
		window.theOrigSum += parseFloat($(this).text().replace(/\,/, ".").replace(/\ /, ""));
	});

	window.theSum = window.theOrigSum.toFixed(2);
	window.theSum = splitThousands(window.theSum).replace(/\./,",");
	$("#" + productId).parents(".orderSub").find("tr.sum .total").text(window.theSum);
}


function feedToSmallCart() {
    var addToCartCue,
    i,
    t;
    
    $.ajax({
        url: "/Ajax/UpdateSmallCart.ashx",
        cache: false,
        dataType: "json",
        success: function(data) {
		    $(".cart .TotalItems").text(data.TotalItems);

		    var theSubTotal = splitThousands(data.SubTotal).replace(/\./,","),
                SubTotalExVat = data.SubTotalExVat,
                SubTotalVat = data.SubTotalVat,
                n,
                /**
                  * Parsing n to contain correct number of 0
                  * If n is 13, return is 13.00
                  * If n is 13.1, return is 13.10
                  * if n is 13.10, return is n
                  * @param {Integer/String} n   number to parse
                  * @return {String}    Correct parsed number
                */
                parseSubTotalString = function (n) {
                    n = typeof n === 'string' ? n : n.toString();    
                    if (n.indexOf('.') !== -1) {
                        if (n.split('.')[1].length === 1) {
                           return n + '0'; 
                        } else {
                            return n;
                        }
                    } else {
                        return n + '.00';
                    }
                }

		    $(".cart .SubTotal").text(theSubTotal);

		    if (data.TotalItems == 0) {
			    $(".cart").removeClass("notEmpty");
			    //$(".cart .cartContent a").attr("disabled","disabled");
			    $(".cart .cartContent a").removeAttr("href");
		    } 
		    else {
			    $(".cart").addClass("notEmpty");
			    //$(".cart .cartContent a").removeAttr("disabled");
			    
			    $(".cart .cartContent a").attr("href", $("#ctl00_HFcartUrl").val());
		    }

            if ($(".orderTotal").length > 0) {    // If total numbers are shown, also update them
				$(".orderTotal .totalsum").text(parseSubTotalString(SubTotalVat)); // Uses parseSubTotalString to display correct price with 2 hundredth-digits
				$(".orderTotal .totalsumVat").text(parseSubTotalString(SubTotalExVat));// Uses parseSubTotalString to display correct price with 2 hundredth-digits
				$(".orderTotal .totalweight span").text(Math.round(data.TotalWeight));
			}

			// update crane or pallet for entire cart
			showDeliveryType($(".checkout .head img.truck"),data.DeliveryTypeCssClass);
        }
    });
    
    addToCartCue = $("tr:visible input[type=text].amount");
    
    for (i = 0; i < addToCartCue.length; i += 1) {
        t = $(addToCartCue[i]);
        
        // checks if an "amount" input has a yellow background.
        // If it does trigger the keyup event to update the cart.
        
        // This check should probably be done in another (better) way.
        if(t.css("background-color").trim().match(/(rgb\(255\,\s?255\,\s?0\)|\#f(f)?f(f)?0(0)?)/ig)) {
            t.trigger("keyup.wtf");
        }
    }
    
}


function waitAndSend(element, blockedAjaj){
	setTimeout((element+'.siblings("input[name=\'amount\']").css({backgroundColor: "#fff"})'),2000)
}


function makeReturningImage(currentColumn,currentOpen,columnWidth,navOriginHeight) {
	$("div.prodnav div.mid ul.main").append('<img src="/image/prodnavvtab.back.png" class="returningImage" alt="" style="display:none" />')
	$(".returningImage").css({
		position:"absolute",
		top:"30px",
		right: "-17px",
		cursor:"pointer",
		display:"block"
	});

	$(".returningImage").click(function(){
		var prodnavTop = getPixelsFromTop($("div.prodnav .top").get(0));
		var prodnavBottom = getPixelsFromTop($("div.prodnav .bottom").get(0));
		var prodnavHeight = prodnavBottom - prodnavTop;

		$("div.prodnav div.mid ul.main").animate({
			height:(prodnavHeight-7) +"px",
			width:"180px"
		},function(){
			$("li", this).not(".open").children("ul").hide();
			
			if($(".prodnav").hasClass("contractedNav")){	
				$(".slideProdnavDown").show();
			}
			
			$(".center select").show()
			$("div.prodnav div.mid").css({
				height:"auto",
				width:"auto",
				position:"static"
			})
			$("div.prodnav div.mid ul.main").css({
				height:"auto",
				width:"auto",
				position:"static",
				border:0,
				border:"2px solid #FFFFFF",
				borderTop: "0"
			});
			$("div.prodnav div.mid ul.main").children("li").css({
				width:"auto",
				position:"",
				top:0,
				left:0,
				zIndex:"1"
			});
//			$("ul.main li").not(".open").find("img").removeClass("showIcon");
			$("ul.main li").not(".open").find("img.icon").hide();
			$("ul.main").children("li").removeClass("mapAll")
			$("ul.main").children("li:eq("+currentOpen+")").addClass("open")
			$(".returningImage").remove()
			//$("div.prodnav div.mid ul.main").append('<img src="../image/prodnavvtab.png" class="returningImage" alt="" />')
		});
		
		return false;
	});
}


function getPixelsFromTop(obj){
	objFromTop = obj.offsetTop;
	while(obj.offsetParent!=null) {
		objParent = obj.offsetParent;
		objFromTop += objParent.offsetTop;
		obj = objParent;
	}
	return objFromTop;
}


function numbersonly(e) {
	var unicode = e.charCode ? e.charCode : e.keyCode;

	if (unicode == 8 || unicode == 9 || unicode == 13 || unicode == 37 || unicode == 39 ) {
		return true;
	} 
	else {
		if ((unicode >= 48 && unicode <= 57) ||
			(unicode >= 96 && unicode <= 105)) {
			return true;
		}
		else {
			return false;
		}
	}
}

//  Functions for external links and popups
addEvent(document, 'click', function(e) {
	theObject = (window.event) ? window.event.srcElement : e.target;
	if(theObject.tagName.toLowerCase() == "a") {
        var relIndex = theObject.rel;
		if (relIndex){
			if(relIndex.indexOf("external") != -1) {
				theObject.target = "_blank";
			}
			if(relIndex.indexOf("popup")!=-1) {
				theHref = theObject.href;
				theObject.href = "javascript:void(0)";
				var popupWidth, popupHeight
				var relSplit = relIndex.split("|");
				if(relSplit[1]){
					popupWidth = relSplit[1];
					popupHeight = relSplit[2];
		        } else {
					popupWidth = 435;
					popupHeight = 350;
	        	}
	        	popMeUp(theHref,popupWidth,popupHeight);
	        }
		}
	}
})
//  adding titles to popup- and external links
addEvent(document, 'mouseover', function(e) {
	theObject = (window.event) ? window.event.srcElement : e.target;
	if(theObject.tagName.toLowerCase() == "a") {
        var relIndex = theObject.rel;
		if (relIndex){
			if(relIndex.indexOf("external") != -1) {
				theObject.title = "Öppnas i nytt fönster";
			}
			if(relIndex.indexOf("popup")!=-1) {
				theObject.title = "Öppnas i popupfönster";
	        }
		}
	}
})


function popMeUp(strURL,strWidth,strHeight) {
	theWin = window.open(strURL, 'popupWin', "scrollbars,resizable,height=" + strHeight + ",width=" + strWidth);
	theWin.focus()
}


addEvent(window, 'load', function(){
	if (!window.print) return;
	if(document.getElementById("printBox")) {
		thePrintBox = document.getElementById("printBox");
		thePrintButton = createElement("p");
		thePrintButton.className = "link floatRight"
		thePrint = createElement("a");
		thePrint.classname="printBut"
		thePrint.href="javascript:window.print()"
		thePrintText = document.createTextNode("Skriv ut");

		theArrow = createElement("em");
		theArrowText = document.createTextNode("> "); //createTextNode(entity("&raquo;") + " ")
		theArrow.appendChild(theArrowText);
		thePrint.appendChild(theArrow);
		thePrint.appendChild(thePrintText);
		
		thePrintButton.appendChild(thePrint);
		thePrintBox.insertBefore(thePrintButton, thePrintBox.firstChild);
	}
})


function createElement(element) {
	if (typeof document.createElementNS != 'undefined') {
		return document.createElementNS('http://www.w3.org/1999/xhtml', element);
	}
	if (typeof document.createElement != 'undefined') {
		return document.createElement(element);
	}
	return false;
}

function addEvent( obj, type, fn ) {
	if (obj.addEventListener)
		obj.addEventListener( type, fn, false );
	else if (obj.attachEvent) {
		obj["e"+type+fn] = fn;
		obj[type+fn] = function() { obj["e"+type+fn]( window.event ); }
		obj.attachEvent( "on"+type, obj[type+fn] );
	}
}


function removeEvent( obj, type, fn ) {
	if (obj.removeEventListener)
		obj.removeEventListener( type, fn, false );
	else if (obj.detachEvent) {
		obj.detachEvent( "on"+type, obj[type+fn] );
		obj[type+fn] = null;
		obj["e"+type+fn] = null;
	}
}




/* =ORGANIZED FUNCTIONS
 * ------------------------------------------------------------------ */


/**
 * Adds or removes product from shopping cart. Handles both the small
 * (+) button on product list and the big (+) button on product pages.
 *
 * @param	pElements	DOM Element(s) to bind events to
 * @param	pBigButton	True if pElements is a big (+) button 
 */
 
 function pNode (that, tag) {
    var pn = that.parentNode, 
    re = new RegExp("^" + tag + "$", "i");
    
    while (!(re).test(pn.tagName)) {
        pn = pn.parentNode;
    }
    if (!pn) {
        pn = document;
    }
    return pn;
}

function addFeedback (elementId) {
    var store = elementId.find("td.triggerShowEGuide"), 
    ctd = store.length ? store[0] : null, 
    parentTable, 
    parentTBody,
    top,
    ofs,
    left,
    pos,
    text,
    finalLeft,
    ah,
    ah2 = document.getElementById("addHint2"),
    lang = document.location.toString().match(/\/[a-zA-Z]{2}\-[a-zA-Z]{2}\//).toString(),
    isProduct = ctd ? ($(ctd.parentNode).hasClass("hide") ? true : false) : false,
    ua = navigator.userAgent,
    isCart = $(".fastCheckout").length ? true : false,
    borderRadiusSupport,
    test;
    
    $("#addHint, #addHint2").remove();
    
    $(".inlinePopup").hide();
    
    $("div.right div.handyMan").css({
        "z-index" : 10
    });
    
    //alert("store.length = " + store.length);
    //alertObjectKeys(elementId);

    if (ctd) {
        $(ctd).parents("table").removeText();
    }
    
    if (ctd && !isProduct && !isCart) {
        
        parentTBody = pNode(ctd, "tbody");
        parentTable = pNode(ctd, "table");
        
        top = parseInt(parentTable.offsetTop + parentTBody.offsetTop, 10);
        
        left = parseInt(parentTable.offsetWidth + parentTable.offsetLeft, 10);
        pos = "top: " + top + "px; left: " + left + "px;";
        text = globalVariables.product.addedToCart;
        
        $(parentTable).parent().prepend("<div id=\"addHint\" style=\"" + pos + "; visibility: hidden;\"><a href=\"" + lang + "Cart.aspx\">" + text + "</a></div>");
        
        ah = document.getElementById("addHint");
        ah.currentTBody = parentTBody;
        parentTBody.flarp = ah;
        
        if (parentTBody.addEventListener) {// Standard (sort of)
            // DOMAttrModified is not supported by webkit at the time of writing (2009-05-07)
            parentTBody.addEventListener("DOMAttrModified", function (e) {
                if (parentTBody.flarp.offsetTop !== parseInt(parentTable.offsetTop + this.offsetTop, 10)) {
                    parentTBody.flarp.style.top = parseInt(parentTable.offsetTop + this.offsetTop, 10) + "px";
                }
            }, false);
        } else if (parentTBody.attachEvent) { //IE
            parentTBody.attachEvent("onpropertychange", function () {
                var that = window.event.srcElement;
                if (parentTBody.flarp.offsetTop !== parseInt(parentTable.offsetTop + that.offsetTop, 10)) {
                    parentTBody.flarp.style.top = parseInt(parentTable.offsetTop + that.offsetTop, 10) + "px";
                }
            });
        }
        
        
        borderRadiusSupport = styleIsSupported("border-radius");
        //if ((/(Opera\/[89]|MSIE\s[678])/).test(ua)) {
        if (!borderRadiusSupport) {
            $("#addHint").addClass("noCSS3");
            $("#addHint").wrapInner("<div class=\"ahInner\"></div>");
            $("#addHint").prepend("<div class=\"ahTop\"><div class=\"filler\"><!-- ie6 fix --></div><div class=\"right\"><!-- ie6 fix --></div></div>");
            $("#addHint").append("<div class=\"ahBottom\"><div class=\"filler\"><!-- ie6 fix --></div><div class=\"right\"><!-- ie6 fix --></div></div>");
        }
        
        finalLeft = ah.offsetLeft;
        $(ah).css({
            left : parseInt(ah.offsetLeft - ah.offsetWidth, 10),
            visibility : "visible"
        });
        
        $(ah).animate({
            left : finalLeft + "px"
        });
        
        var ahAnime = function () {
            $(ah).animate({
                left : parseInt(ah.offsetLeft - ah.offsetWidth, 10) + "px"
            }, function () {
                $("#addHint").remove();
            });
        }
        
        clearTimeout(window.addFeedbackDelay);
        window.addFeedbackDelay = setTimeout(function () {
            ahAnime();
        }, 3000);
        
        $("#addHint").mouseover(function () {
            clearTimeout(window.addFeedbackDelay);
            setTimeout(function () {
                $("#addHint").mouseout(function () {
                    window.addFeedbackDelay = setTimeout(function () {
                        ahAnime();
                    }, 500);
                });
            },1000)
        });
        
    } else if (ctd && isProduct && !isCart) {
        text = globalVariables.product.addedToCart;
        $(".productContainer").find(".products").prepend("<div id=\"addHint2\" style=\"\"><a href=\"" + lang + "Cart.aspx\">" + text + "</a></div>");
        
        ah2 = document.getElementById("addHint2");
        borderRadiusSupport = styleIsSupported("border-radius");        
        //if ((/(Opera\/[89]|MSIE\s[678])/).test(ua)) {
        if (!borderRadiusSupport) {
            var flarpWidth = document.getElementById("addHint2").offsetWidth;
            $("#addHint2").addClass("noCSS3");
            $("#addHint2").wrapInner("<div class=\"ah2Inner\"></div>");
            $("#addHint2").prepend("<div class=\"ah2Top\"><div class=\"right\"></div><div class=\"left\"></div><div class=\"filler\"></div></div>");
            
            $("#addHint2").css({
                width : flarpWidth + "px"
            });
        }
       
        top = ah2.parentNode.offsetHeight;
        
        $(ah2).animate({
            bottom : top + "px"
        });
        
        var ahAnime2 = function () {
            $(ah2).animate({
                bottom : 0
            }, function () {
                $(ah2).remove();
            });
        }
        
        clearTimeout(window.addFeedbackDelay);
        window.addFeedbackDelay = setTimeout(function () {
            ahAnime2();    
        }, 3000);
        
        $("#addHint2").mouseover(function () {
            clearTimeout(window.addFeedbackDelay);
            
            setTimeout(function () {
                $("#addHint2").mouseout(function () {
                    window.addFeedbackDelay = setTimeout(function () {
                      ahAnime2();
                    }, 500);
                });
            },1000)
        });
    }
}

function productToCart(pElements, pBigButton) {
    
	$(pElements).click(function() {
	    var productRow,
	    productId,
	    isPlank,
	    ah,
	    elementId,
	    qProductsId,
	    t = $(this);
	    
		if (pBigButton) {
			productRow = $(".productContainer .product tbody:first, table.productListproductList tbody:nth-child(2)");
			productId = t.parents(".productContainer").find(".ProductId").text();
			isPlank = $(".productContainer tbody").find(">tr").hasClass("orderSub");
		    
	        //alert(pElements + "\n" + pBigButton + "\n" + isPlank);
		}
		else {
			productRow = t.parents("tbody");
			productId = t.parents("tbody").find(".ProductId").text();
			t.parents(".orderOn").find(".orderSub").find("input[name='amount']").val("0");
		    isPlank = t.parents("tbody").find(">tr").hasClass("orderSub");
		}
		
		//alert("pElements = " + pElements + "\npBigButton = " + pBigButton + "\nproductRow.attr(\"id\") = " + productRow.attr("id"));
		
		elementId = $("#" + productRow.attr("id"));    // Save found element
		
		
		if (!elementId.length) {
		    elementId = $(productRow);
		}
		
		ah = document.getElementById("addHint");
		if (ah) {
		    $(ah).animate({
                left : parseInt(ah.offsetLeft - ah.offsetWidth, 10) + "px"
            });
        }
		
		// REMOVE FROM CART
		if ((typeof($(this).attr("src")) != "undefined" && $(this).attr("src").match("unchoose")) ||      // Product list
			($("img.choose", this).hasClass("hide"))) {     // Big button on product page
			
			qProductsId = isPlank	? 
											"&isPlank=true&productidList=" +productRow.find(".orderSub .productid").filter(function (i) {
																				return $(this).attr("id");
																			}).map(function(){
																				return $(this).attr("id");
																			}).get().join(',') + "," + productId.replace(/^p/, "")
										:
											"&productId=" + productId.replace(/^p/, "");
            
			$.ajax({
				url: "/Ajax/AddToCart.ashx?quantity=0" +"&languageBranch=" + languageBranch + "&storeid=" + gvStoreID + qProductsId,
				cache: false,
				dataType: "json",
				success: function(data) {
					if (data.Quantity != -1) {
						if (isPlank) {
							elementId.find("input[name='amount']").val(0);
							elementId.find(".corQuant").text("0");
							elementId.find("tr.sum>td.amount span.totQuant").text("0");
							elementId.find("tr.sum>td.amount span.totCorQuant").text("0");
							elementId.find("td.total").text("0");
						}
						else {
							elementId.find(".Quantity").text(data.Quantity);
							elementId.find(".corrquantity").text(data.CorDispUnitQuant);
						}

						hideCart(elementId, pBigButton);
						feedToSmallCart();    // Send changes to top bar cart
						
						$("#addHint2").css({display : "none"}).remove();
					}
					else {
						alert("No data from server!");
					}
				}
			});
		} //remove from cart end

		// ADD TO CART
		else {
			if (pBigButton) {
				// TODO: Make something shiny here too!
			} 
			else {
				elementId.find(".add img").attr("src", elementId.find(".add img").attr("src").replace(/choose/,"loader"));
			}
			    
			if (isPlank) {
				showCart(elementId, pBigButton, isPlank);
			}
			else {
			    
			    productId = productId.replace(/^p/, "");
			    
				$.ajax({
					url: "/Ajax/AddToCart.ashx?quantity=1&languageBranch=" + languageBranch + "&storeid=" + gvStoreID + "&productId=" + productId,
					cache: false,
					dataType: "json",
					success: function(data) {
						if (data.Quantity != -1) {
						    
							elementId.find(".Quantity").text(data.Quantity);
							elementId.find(".corrquantity").text(data.CorDispUnitQuant);
							elementId.find(".order").find("input[name='amount']").val(data.Quantity);
	
							// Calculate and format Prize * Amount
							thePrice = parseFloat(elementId.find(".costPrice:first").text().replace(/\,/,".").replace(/\ /,""));
							tempVal = thePrice != 0 ? thePrice * data.Quantity : 0;
							tempVal = tempVal.toFixed(2);
							elementId.find(".total").text(splitThousands(tempVal).replace(/\./,","));

							// show crane or pallet
							showDeliveryType(elementId.find("img.deliveryType"), data.DeliveryTypeCssClass);

							showCart(elementId, pBigButton, isPlank);
							feedToSmallCart();
							//updateCartTotal(data.SubTotalVat, data.SubTotalExVat, data.TotalWeight);
							
						    clearTimeout(window.addFeedbackDelay);
						    $("#addHint").remove();
						    
						    //alert("elementId = " + elementId);
						    addFeedback(elementId);
						}
						else {
							alert("No data from server!");
						}
					}
				});
			}
		} //add to cart end
	});
	
	function showCart(pElementId, pBigButton, pIsPlank) {
	
		// Show mini cart
		pElementId.addClass("orderOn");
		if (pIsPlank) { // deal with correct tr depending on isPlank or not
			pElementId.find(">tr.orderSub").show();
		} else {
			pElementId.find(">tr.order").show();
		}

		if (pBigButton) {    // Hide big Add to cart button
			$(".unchoose").removeClass("hide");
			$(".choose").addClass("hide");
		} else {
			// Show Remove from cart buttons
			pElementId.find(".add img").attr("src", pElementId.find(".add img").attr("src").replace(/loader/, "unchoose"));
			pElementId.find(".add img").attr("alt", PRODUCT_REMOVE_FROM_CART);
			pElementId.find(".add img").attr("title", PRODUCT_REMOVE_FROM_CART);
		}

		productAmountEvents();   // Bind events to amount input field
	}
	
	function hideCart(pElementId, pBigButton) {
		// Hide and reset mini cart
		pElementId.removeClass("orderOn");
		pElementId.find(">tr.order").hide();
		pElementId.find(">tr.orderSub").hide();

		if (pBigButton) {                        // Show big Add to cart button
			$(".unchoose").addClass("hide");     // Hide Remove from cart button
			$(".choose").removeClass("hide");    // Show Add to cart button
		}
		else {
			// Show small add to cart buttons
			pElementId.find(".add img").attr("src", pElementId.find(".add img").attr("src").replace(/unchoose/, "choose"));
			pElementId.find(".add img").attr("alt", PRODUCT_ADD_TO_CART);
			pElementId.find(".add img").attr("title", PRODUCT_ADD_TO_CART);
		}
	}
}



/**
 * Shows correct delivery type icon and text
 */
function showDeliveryType(imgObj, type) {
	var fileName = imgObj.parent().parent().hasClass("checkout") ? "checkout" : "cart" ;
	imgObj.attr("src", "/image/fastCheckout/" + type + "_mini.png");

	// Large checkout image has other text
	if (imgObj.parent().parent().hasClass("checkout")) {
		var palletText = ECOMMERCE_DELIVERY_TYPE_PALLET_TITLE;
		var craneText  = ECOMMERCE_DELIVERY_TYPE_CRANE_TITLE;
	}
	else {
		var palletText = PRODUCT_DELIVERY_TYPE_PALLET_TITLE;
		var craneText  = PRODUCT_DELIVERY_TYPE_CRANE_TITLE;
	}
	
/*
	var palletText = imgObj.parent().parent().hasClass("checkout") ? ECOMMERCE_DELIVERY_TYPE_PALLET_TITLE : PRODUCT_DELIVERY_TYPE_CRANE_TITLE;
	var craneText  = imgObj.parent().parent().hasClass("checkout") ? ECOMMERCE_DELIVERY_TYPE_CRANE_TITLE : PRODUCT_DELIVERY_TYPE_PALLET_TITLE;
*/

	switch(type) {
		case "pallet":
			imgObj.attr("alt", palletText);
			imgObj.attr("title", palletText);
			break;    
		case "crane":
			imgObj.attr("alt", craneText);
			imgObj.attr("title", craneText);
			break;
		default:
			imgObj.attr("alt", "delivery type missing");
			imgObj.attr("title", "delivery type missing");
	}
}


/**
 * Binds events to the product amount box, making it possible 
 * to add or remove more of the same product to the cart. 
 */
var timer = null;
 	
function productAmountEvents() {
	// (Re)Bind events to namespace "wtf", in order to be able to unbind them safely
	// Must be done to prevent multiple events on same targets.
	$("#addHint").remove();
	
	$(".orderOn .amount img").unbind("click.wtf").bind("click.wtf", function() {
		productAmountChanger($(this), true);     // Bind to mouse click on arrows
	});
	
	$(".products .orderOn input[name='amount']").unbind("keyup.wtf").bind("keyup.wtf", function(e) {
		productAmountChanger($(this), false);    // Bind to keyboard input on product list
	});
	
	$(".productContainer input[name='amount']").unbind("keyup.wtf").bind("keyup.wtf", function(e) {
		productAmountChanger($(this), false);    // Bind to keyboard input on product page
	});
}


/**
 * Main amount box event binder function
 *
 * @attr	pMouseClick		True for mouse click triggers, false for keyboard
 */
 
function productAmountChanger(pTrigger, pMouseClick) {
    
    var tot = $(pTrigger).parents("tbody").find(".sum .total"), 
    orgAmount = tot.length ? parseInt(tot[0].innerHTML.replace(/\s/g, ""), 10) : null, 
    newAmount,
    productId;
    
    //alert("pTrigger = " + pTrigger + "\npMouseClick = " + pMouseClick);
    
    if (!orgAmount) {
        tot = $(pTrigger).parents("tbody").find(".total");
        orgAmount = tot.length ? parseInt(tot[0].innerHTML.replace(/\s/g, ""), 10) : null;
    }
    
	if (pMouseClick) {
		var myField = new AmountField(pTrigger.siblings("input[name='amount']"));

		if (pTrigger.attr("src").match("more")) {    // More arrow button
			myField.changeAmount(1);                 // Increase by 1 item
		} 
		else {                                       // Less arrow button
			myField.changeAmount(-1);                // Decrease by 1 item
		}
	}
	else {
		var myField = new AmountField(pTrigger);
		myField.changeAmount(0);
	}
	
	if (!myField.isMarked) {
		myField.mark();
	}

	myField.isPlank = pTrigger.parents("tbody").find(">tr").hasClass("orderSub");

	if(myField.isPlank) {
	    productId = pTrigger.parents("tr").find(">td.productid").attr("id");
	}
	else {
		productId = pTrigger.parents(".orderOn").find(".ProductId").text();
	}

	var productElement = pTrigger.parents(".orderOn");
	var qIsPlank = myField.isPlank ? "&isPlank=true" : "";
	var getString = "/Ajax/AddToCart.ashx?productId=" + productId.replace(/^p/, "") + "&quantity=" + myField.amount + "&languageBranch=" + languageBranch + "&storeid=" + gvStoreID +qIsPlank;

	if (timer != null) {
		clearTimeout(timer);
	}

	timer = setTimeout(function() {
	    
		$.ajax({
			url: getString,
			cache: false,
			dataType: "json",
            success: function(data) {

				 /*alert("ProductId: " +data.ProductId +"\n"
						+"Quantity: " +data.Quantity +"\n"
						+"CorDispUnitQuant: " +data.CorDispUnitQuant +"\n"
						+"TotPlankLength: " +data.TotPlankLength +"\n"
						);*/
				

				if (myField.isPlank) {
					// update corresponding quantity: (xxx m)
					myField.changeCorrAmount(data.TotPlankLength);
					productElement.find("#p" + data.ProductId).siblings(".amount").find(".corQuant").text(splitThousands(myField.corrAmount).replace(/\./,","));

					// We need to add all items before updating
					var totalQuantity = 0;
					var totalCorrQuantity = 0;
										
					// count and add all quantities
					productElement.find(".orderSub input[name='amount']").each(function() {
						totalQuantity = totalQuantity + parseInt($(this).val());
						totalCorrQuantity = totalCorrQuantity + parseFloat($(this).siblings(".corQuant").text().replace(/\,/,".").replace(/\ /,""));
					});
					
					// update total quantity and total corresponding quantity
					productElement.find("tr.sum>td.amount span.totQuant").text(totalQuantity);
					productElement.find("tr.sum>td.amount span.totCorQuant").text(splitThousands(totalCorrQuantity.toFixed(1)).replace(/\./,","));

					// calculate subtotal and total
					myField.calculateTotalPrice(productElement.find("#p" + data.ProductId).siblings(".amount").find("input.itemPrice:first").val());
					
					productElement.find("#p" + data.ProductId).siblings(".total").text(myField.totalprice);
					
					sumThisUp(productId);
					
				}
				else {
					// update quantity and corresponding quantity
					productElement.find(".Quantity").text(data.Quantity);
					productElement.find(".corrquantity").text(data.CorDispUnitQuant);
					
					// calculate total
					myField.calculateTotalPrice(productElement.find(".costPrice:first").text());
					productElement.find(".total").text(myField.totalprice);
				}

				// show crane or pallet
				showDeliveryType(productElement.find("img.deliveryType"), data.DeliveryTypeCssClass);
				
				myField.unmark();
				feedToSmallCart();
			    
			    newAmount = tot.length ? parseInt(tot[0].innerHTML.replace(/\s/g, ""), 10) : null;
			    
			    if (!orgAmount || ((orgAmount && newAmount) && (newAmount > orgAmount))) {
				    addFeedback($(pTrigger).parents("tbody"));
				}
            }
		});
		
		if ($(".checkout").length > 0) {    // If on cart checkout page
			$(".checkout .body").slideUp("slow");
		}

	}, 900);
	
	function AmountField(pElements) {
		this.elements = pElements;
		this.isMarked = false;
//		this.isSpecified = false;
		this.isPlank = false;
		this.amount = 0;
		this.corrAmount = 0;
		this.price = 0;
		this.totalprice = 0;
		
		this.changeAmount = function(pValue) {
			if (pValue != 0) {
				newValue = parseInt(this.elements.val()) + pValue;
				
				if (newValue < 0)
					newValue = 0;
		
				this.amount = newValue;
				this.elements.val(this.amount);
			}
			else {
				this.amount = parseInt(this.elements.val());

				if (isNaN(this.amount)) {
					this.amount = 0;
				}
			}
		};

		this.changeCorrAmount = function(pValue) {
			myValue = parseFloat(pValue.replace(/\,/,".").replace(/\ /,""));
			if (myValue < 0)
				myValue = 0;
	
			this.corrAmount = myValue;
		};
		
		this.mark = function() {
			this.elements.css({ backgroundColor: "#FF0" });
			this.isMarked = true;
		};
		
		this.unmark = function() {
//			this.elements.animate({ backgroundColor: "#FFF" }, 500);
			this.elements.css({ backgroundColor: "#FFF" });
			this.isMarked = false;
		};
		
		this.calculateTotalPrice = function(pItemPrice) {
			this.price = parseFloat(pItemPrice.replace(/\,/,".").replace(/\ /,""));

			tempVal = this.amount != 0 ? this.price * this.amount : 0;			
			tempVal = tempVal.toFixed(2);
			this.totalprice = splitThousands(tempVal).replace(/\./,",");
		};
	}
}


function productBlockNonDigits() {
	$("input[name='amount']").keypress(function(e){
		return numbersonly(e);
	});
}


function productlistHover() {
	// Color hovered rows yellow

	$(".products > table > tbody").mouseover(function(){
		$(this).children("tr.product").addClass("hover");
	}).mouseout(function(){
		$(this).children("tr.product").removeClass("hover");
	});
}


function navigationProducts() {
	$("ul.main").children("li").mouseover(function(){
		if(!$(this).hasClass("mapAll")){
			$(this).children("a").addClass("mjHover");
//			$("li.open img.icon").hide();
			$(this).find(".icon").show();
			
			// force qv live search to be on top
			if($(this).find("input").length < 1) {
				$(this).css("zIndex", "2");
			} else {
				$(this).css("zIndex", "3");
			}
		}		
	});

	$("ul.main").children("li").mouseout(function(){
		if(!$(this).hasClass("mapAll")){
			$(this).children("a").removeClass("mjHover");
//			$("li.open img.icon").show();
			$(this).not(".open").find(".icon").hide();

			// force qv live search to be on top
			if($(this).find("input").length < 1) {
				$(this).css("zIndex", "1");
			}
		}
	});

	$("div.prodnav div.mid ul.main").children("li").children("a").click(function(){
		var thisIsOpen = $(this).parent("li").hasClass("open");
		if(!$(this).hasClass("showall") && !$(this).parent().hasClass("mapAll")){
			if(thisIsOpen) {
				$(this).parent("li").children("ul").slideUp("normal", function(){
					$(this).slideDown("fast");
				});
			} else {
				$("div.prodnav div.mid ul.main").children("li").children("ul").slideUp("normal", function(){
					$(this).parent("li").removeClass("open");
					$(this).parent("li").find("img.icon").hide();
				});
				$(this).parent("li").addClass("open").children("ul").hide().slideDown("fast");
				$(this).parent("li").find(".icon").show();
			}
			return false;
		}
	});

	var currentOpen;
	var columnWidth = 189;
	
	if ($(".prodnav").hasClass("expandedNav")) {
		var currentHeight = 0;
		var currentColumn = 0;
		var topHeight = 0;

		$(".center select").hide();
		navOriginHeight = $("div.prodnav div.mid ul.main").height;

		$("div.prodnav div.mid ul.main").css({
			position : "absolute",
			top : "-5px",
			left : "-7px",
			height : $("div.prodnav div.mid").height() + "px",
			width : "172px",
			border : "6px solid #cb0e0e",
			background : "#f3f3f3 url(/image/bg.sitemap.gif)"
		});
		
		$("div.prodnav div.mid ul.main").children("li").css({
			width : (columnWidth - 2) + "px",
			position : "absolute"
		});
		
		$("div.prodnav div.mid ul.main").children("li").not(".liveSearch").css({
			zIndex:"10"
		});
		
		$("div.prodnav div.mid ul.main").children("li").each(function(i){
			if ($(this).hasClass("open")){
				currentOpen = i
			}
			$(this).addClass("mapAll");
			tempCurrentHeight = currentHeight + $(this).height();
			if(tempCurrentHeight > navHeight) {
				currentHeight = 0;
				currentColumn ++;
			}
			$(this).css({
				top: currentHeight + "px",
				left:((currentColumn * columnWidth)+2) + "px"
			});
			if( !$(this).hasClass("liveSearch") ) {
				$(this).css({zIndex:"20"});
			}
			if(tempCurrentHeight > navHeight) {
				currentHeight = $(this).height();
			} else {
				currentHeight = currentHeight + $(this).height();
			}
			if(topHeight < currentHeight) topHeight = currentHeight;	
		});
		setTimeout(function () {
		    $("div.expandedNav").css({
		        visibility : "visible"
		    });
		}, 0);
		
/* old style non-animation */
		$("div.prodnav div.mid ul.main").css({
			height:(topHeight + 4) + "px",
			width:((currentColumn * columnWidth) + columnWidth + 2) + "px"
		});
		$("div.prodnav div.mid").css({
			height:(topHeight + 4) + "px",
			position:"relative"
		});

		// If customer interview foldout banan is visisble, push down content 140 pixels
		if ($(".foldout").length > 0) {
			var INSTRUCTIONS_FOLDOUT_HEIGHT = 140;
		}
		else {
			var INSTRUCTIONS_FOLDOUT_HEIGHT = 0;
		}

		$(".center").css({
			marginTop:(topHeight + 23 + INSTRUCTIONS_FOLDOUT_HEIGHT) + "px",
			visibility : "visible"
		});
	}
/* end old style */


/* new style with animation 
		$("div.prodnav div.mid").animate({
			height:(topHeight + 4) + "px"
		},1200);
		$("div.prodnav div.mid ul.main").animate({
			height:(topHeight + 4) + "px",
			width:((currentColumn * columnWidth) + columnWidth + 2) + "px"
		},1200);
	}

	$(".center .startTeasers").animate({
		marginTop:(topHeight + 33) + "px"
	},400);
 end new style */

	$(".center .startTeasers .head").each(function(){
		headHTML = $(this).html();
		$(this).parent().append('<div class="headShadow">'+ headHTML + '</div>');
	});
	$(".center .startTeasers .price").each(function(){
		headHTML = $(this).html();
		$(this).parent().append('<p class="priceShadow">'+ headHTML + '</p>');
	});
	$(".center .startTeasers .bigTeaser,.center .startTeasers .teaser").each(function(){
		var teaserHref = $("a:first",this).attr("href");
		$("*",this).css({
			cursor:"pointer"
		});
		$("*",this).click(function(){
			window.location.href = teaserHref;
		});
	});
	
	/*$(".handyMan .relatedtHandymanBoxHeader").each(function(){
		var text = this.innerHTML.trim();
		
		this.innerHTML = "<span class=\"handyManHeader shadow\">" + text + "</span>";
		this.innerHTML += "<span class=\"handyManHeader\">" + text + "</span>";
	});*/
	//}

	$("div.prodnav img.vtab").click(function(){	
		var currentHeight = 0
		var currentColumn = 0
		var topHeight = 0

		$(".center select").hide()

		$("ul.main img.icon").show();

		navOriginHeight = $("div.prodnav div.mid ul.main").height;
		$(".slideProdnavDown").hide()
		$("div.prodnav div.mid").css({
			height:$("div.prodnav div.mid").height() + "px",
			position:"relative"
		})
		$("div.prodnav div.mid ul.main").css({
			position:"absolute",
			top:"-3px",
			left:"-7px",
			height:($("div.prodnav div.mid").height()-4) + "px",
			width:"172px",
			border:"7px solid #cb0e0e",
			borderLeft:"7px solid #cb0e0e",				
			background:"#f3f3f3 url(/image/bg.sitemap.gif)"
		})
		$("div.prodnav div.mid ul.main").children("li").css({
			width:(columnWidth - 2) + "px",
			position:"absolute"
		});
		$("div.prodnav div.mid ul.main").children("li").not(".liveSearch").css({
			zIndex:"10"
		});
		$("div.prodnav div.mid ul.main").children("li").each(function(i){
			$(this).children("ul").show();
			
			if ($(this).hasClass("open")){
				currentOpen = i
			}
			$(this).addClass("mapAll");
			tempCurrentHeight = currentHeight + $(this).height();
			if(tempCurrentHeight > navHeight) {
				currentHeight = 0;
				currentColumn ++;
			}
			$(this).css({
				top:currentHeight + "px",
				left:((currentColumn * columnWidth)+2) + "px"
			});
			if( !$(this).hasClass("liveSearch") ) {
				$(this).css({zIndex:"20"});
			}
//			$("img",this).addClass("showIcon")
			if(tempCurrentHeight > navHeight) {
				currentHeight = $(this).height();
			} else {
				currentHeight = currentHeight + $(this).height();
			}
			if(topHeight < currentHeight) topHeight = currentHeight;	
		})

		$("div.prodnav div.mid ul.main").animate({
			height:(topHeight + 4) + "px",
			width:((currentColumn * columnWidth) + columnWidth + 2) + "px"
		},function(){
			makeReturningImage(currentColumn,currentOpen,columnWidth,navOriginHeight);
		})			
		return false;
	})
	
	if($(".prodnav").hasClass("contractedNav")){	
		//$(".contractedNav img.slider").attr("src",$(".contractedNav img.slider").attr("src").replace(/up/,"down"))
		$(".contractedNav .showProdnavDown").filter(".slider").click(function(){
			if ($(".contractedNav img.slider").attr("src").match("down")){
				
				$("ul.main li").not(".open").find("img.icon").hide();
				
				$(".contractedNav .main").slideDown(300,function(){
					$(".prodnav .vtab").css("display","inline");
				});
				$(".contractedNav img.slider").attr("src",$(".contractedNav img.slider").attr("src").replace(/down/,"up"));
				return
			} else {
				$(".contractedNav .main").slideUp(300,function(){
					$(".prodnav .vtab").css("display","none");
				});
				$(".contractedNav img.slider").attr("src",$(".contractedNav img.slider").attr("src").replace(/up/,"down"));
			}
		});
	}
} /*** end document.ready ***/


function frameworkStorePicker() {
	storePicker("top");
}


function productpageStorePicker() {
    new storePicker("stock");
}

function cartStorePicker() {
	var csp = new storePicker("commerce");

	// load dropdown with commerce stores if zip exists
	if($(".commercezip").val() != "" && $(".commercestore").children("option:first").is(":selected")) {
//		csp.loadCityList();
	}
}


function storePicker(storePickerID) {
	var myZipStorePicker = $("." +storePickerID +"zip");
	var myCityStorePicker = $("." +storePickerID +"store");
	var myStorePickerName = myCityStorePicker.attr("name");
	var isCommerce = storePickerID == "commerce";
	var thisStorePicker = this;
	var isLocked = false;

	// zip input filter
	myZipStorePicker.keydown(function(e) {
		theForm = "disabled"
		if(e.which == 13) {
			if($(this).val() == "") {
 				setTimeout(function() {
					__doPostBack(myStorePickerName + "","");
				}, 100);
			}
			else {
				return false
			}
		} else {
			return numbersonly(e)
		}
	});

	// zip interaction
	var zipValue = myZipStorePicker.val()
	myZipStorePicker.focus(function(e) {
		if($(this).val() == zipValue) {
			$(this).select();
		}
	});
	myZipStorePicker.blur(function(e) {
		if($(this).val() == "") {
//			$(this).val(zipValue);
			theForm = "enabled";
		}
	});


	var theForm = "enabled";
	$("form").submit(function() {
		if(theForm == "disabled") return false;
	});
	var theStoreId = "zoot";


	myZipStorePicker.keyup(function(e){
		//$(".storeListing").html("");

		if( storePickerID == "commerce" && $(".checkout .body").is(":visible") ) {    // If on cart checkout page
			$(".checkout .body").slideUp("slow");
		}
		
		// mark yellow while input (and reset select if re-entering new zip)
		$(this).css({ backgroundColor:"#ff0"} );
		myCityStorePicker.css({ backgroundColor:"#fff"} );
		myCityStorePicker.children("option").css( {backgroundColor:"#fff"} );
	
		// variable zip lenghts in different countries
		if($("#ctl00_HFmarket").val() == "Norweigan") {
			theLength = 4
		}
		else {
			theLength = 5
		}
		
		if($(this).val().length == theLength || ($(this).val().length == 0 && parseInt(e.which) == 13) ) {
			if (parseInt(e.which) == 13) {
				e.preventDefault();
				if(theStoreId == "zoot") return false;
				myCityStorePicker.val(theStoreId)
				setTimeout(function() {
					__doPostBack(myStorePickerName + "","");
				}, 100);
				return false;
			}
			else {
				thisStorePicker.loadCityList();
			}
		} // end if not correct length
		else if($(this).val().length > theLength) {
			return false;
		}
	});


	// allows cart to autoload commerce stores in list if zip exists
	this.loadCityList = function(){
		if(myCityStorePicker.children("optgroup").length > 0) {
			myCityStorePicker.children("option:first").remove();
			myCityStorePicker.children("optgroup").remove();
		}

		var qCommerce = isCommerce ? "&commerce=1" : "";

		if(!isLocked) { // prevents dubble input for fast typers
			isLocked = true;
			$.ajax({
				url: "/Ajax/FindNearestStores.ashx?zip=" +myZipStorePicker.val() +"&market=" +$("#ctl00_HFmarket").val() +"&language=" +$("#ctl00_HFlanguage").val() +qCommerce,
				cache: false,
				dataType: "json",
				success: function(data) {
	
					if(data.stores.length > 0){
					
						// hide error and reset colors
						myCityStorePicker.children("option.error").remove();
						myCityStorePicker.css({ color:"",backgroundColor:"" });
						
						// show original list
						myCityStorePicker.children("option").show();
						myCityStorePicker.children("optgroup").show();

						var htmlString = '<option class="storeNearHead" value="">' + STOREPICKER_LOCALE_PICKSTORE + '</option><optgroup>';
						
						var opgheader = htmlString.replace(/<optgroup>$/, "");
						$.each(data.stores, function(i,store){
							if(i==0) theStoreId = store.storeId;
							htmlString += '<option class="storeNear" value="' + store.storeId + '">' + store.storeName + '</option>';
						});
						htmlString += '</optgroup>';
						
						if(isCommerce) {
						    myCityStorePicker.empty();
						} else {
						    $(".commercezip").each(function () {
						        if (this.value.length === theLength) {
						            $(this).trigger("keyup");
						        }
						    });
						}
						
						$(".fastCheckout .tooltip").remove();
						
						myCityStorePicker.prepend(htmlString);
						myCityStorePicker.children("option:first").attr("selected", "selected");
						myCityStorePicker.css( {backgroundColor:"#ff0"} );
						myCityStorePicker.children("option").css( {backgroundColor:"#fff"} );
						myCityStorePicker.children("option.storeNear").css({ backgroundColor:"#ff0"} );
						myCityStorePicker.children("option.storeNearHead").css({ backgroundColor:"#ff0"} );
						myZipStorePicker.css({ backgroundColor:"#fff"} );
						
						if (myCityStorePicker && $(myCityStorePicker).parent().hasClass("noStore")) {
						    $(myCityStorePicker).parent().removeClass("noStore");
						    $(".bigButton.buyButton.noStore").removeClass("noStore").click(function (e) {
						        var that = this;
						        if (!myCityStorePicker[0].value) {
						            var i, cn = myCityStorePicker[0].getElementsByTagName("option");
						            e.preventDefault();
						            for (i = 0; i < cn.length; i += 1) {
						                if (cn[i].value) {
						                    cn[i].selected = "selected";
						                    $(myCityStorePicker[0]).trigger("change");
						                    break;
						                }
						            }
						        }
						    });
						}
						
						/*var opg = $(".topstore").find("optgroup");
						if (opg.length) {
						    $("select.commercestore").each(function () {
						        this.innerHTML = opgheader + opg[0].innerHTML;
						    });
						    $(myCityStorePicker).change(function () {
						        var that = this;
						        $("select.commercestore option[value=" + that.value + "]").attr("selected", "selected");
						    });
						}*/
					}
					else {
						theStoreId = "zoot";
						
						// hide current list
						myCityStorePicker.empty();
						
						// enter new list and change colors
						var htmlString = '<option selected class="error">' + globalVariables.cart.error.zip +'</option>';
						myCityStorePicker.prepend(htmlString);
						myCityStorePicker.css({ color:"#ffffff",backgroundColor:"#EE1111" });
						myCityStorePicker.children("option.error").css({ color:"#ffffff",backgroundColor:"#EE1111" });

					}
					theForm = "enabled"
					isLocked = false;
				}
				
			});
		}
		return false;
	}
}


function navigationProjects() {
	//constructionnav - måste vara global

	$("li.project h4").not(".active").mouseover(function(){
		$(this).addClass("active");
	}).mouseout(function(){
		$(this).removeClass("active");
	});


/*
	$(".constructionnav li").mouseover(function() {
		var aName = $(this).attr("class").split(" ")[1];
		aBackground = "url(/image/constructionnav." + aName + "-on.jpg)";
		$(this).css("background", aBackground);
	}).mouseout(function() {
		var aName = $(this).attr("class").split(" ")[1];
		aBackground = "url(/image/constructionnav." + aName + ".jpg)";
		$(this).css("background", aBackground);
	});;
*/
}


function startpageCampaignMonitor() {
	if ($("div.campaignMonitor")){
		var theCampaign = $("div.campaignMonitor");
		campaignLength = $("div.campaignMonitor li").length;
		$("div.campaignMonitor ul").css({
			width:((169 * campaignLength)+10)+"px",
			position:"absolute",
			left:0,
			top:0
		});
		$("div.campaignMonitor li").each(function(index){
			$(this).css({
				position:"absolute",
				left:(169*index) + "px"
			})
			$("div.campaignMonitor").append('<img class="bullet" src="/image/bullet.slides.passive.gif" alt="">');
		});
		$("div.campaignMonitor .bullet:first").attr("src","/image/bullet.slides.active.gif");
		$("div.campaignMonitor .bullet").each(function(i){
			$(this).click(function(){
				campaignClickTime = new Date() 
				$("div.campaignMonitor ul").animate({
					left:-(169 * i)+"px"
				},"slow");
				$("div.campaignMonitor .bullet").attr("src","/image/bullet.slides.passive.gif");
				$(this).attr("src","/image/bullet.slides.active.gif");
				theCampaignImage = i
				setTimeout("rotateCampaign()",8000)
			})
		});
		theCampaignImage = 0
		setTimeout("rotateCampaign()",8000)	
	}
}


function modalCustom() {
    var ua = navigator.userAgent;
	// inlinePopup
	$(".ipEntry").click(function() {
	    var that = this;
		
		if ($.browser.msie && (/^[67]/).test($.browser.version) && $(that).parent().hasClass("calc")) {
		    $(that.parentNode.popUp).show("fast");
		} else {
		    $(that.parentNode).find(".inlinePopup").show("fast");
		}
	});	
	$(".ipClose").click(function() {
		$(this).parent().parent().hide("fast");
		$("div.right div.handyMan").css({
	        "z-index" : 10
	    })
	});
	
	// toolTip
	$(".ttEntry").mouseover(function(){
		$(this).siblings(".toolTip").show();
	});
	$(".ttEntry").parent().parent().mouseout(function(){
		$(this).find(".toolTip").hide();
	});
	
	$(".relatedtHandymanBoxHeader .quest").click(function () {
	    $("div.right div.handyMan").css({
	        "z-index" : 50
	    })
	    //clearTimeout(window.addFeedbackDelay);
	    $("#addHint, #addHint2").remove();
	    $(this).parent().siblings(".inlinePopup").show();
	});
}


function commerceGeneral() {
	// caclulate freight and show calendar
	$(".calculateButton").click(function() {
		$(this).parent().siblings(".body").slideDown("fast");
	});
	
	
	//toggle create account conditions
	//toggle e-commerce conditions
	$("span.agree").click(function(){
		$(".conditions").slideToggle("fast");
	});
	
	//add recievers
	$("span.addReciever").click(function(){
		$(this).parent().siblings(".hide:first").slideDown("fast", function() {
			$(this).removeClass("hide");
			if( !$(this).siblings(".extraReciever:last").is(".hide") ) {
				$(this).parent().find("span.addReciever").fadeOut("fast");
			}
		});
	});
	
	//toggle change password
	$(".changePasswordEntry").click(function(){
		$(this).siblings(".saveButton").toggle();
		$(this).siblings(".changePassword").slideToggle("fast");
		$(this).siblings(".changePassword").find("input").attr("value","");
		$(this).children("span").toggle();
	});

	//shoppinglist print
	$("span.printShoppinglist").click(function(){
		window.print();
	});

	//shoppinglist remove
	$(".shoppinglist a.ttEntry").mouseover(function(){
		$(this).parent().siblings().children("img.remove").show();
	}).mouseout(function(){
		$(this).parent().siblings().children("img.remove").mouseover(function(){
			$(this).stop();
		});
		$(this).parent().siblings().children("img.remove").mouseout(function(){
			$(this).hide();
		});
		$(this).parent().siblings().children("img.remove").slideUp(1);
	});
	
	//shoppinglist general functions
	$(".shoppinglistBoxContainer .generalFunctions .functionEntry").click(function(){
		if (!$(this).parent().siblings("li").hasClass("open")){
			$(this).not(".noaction").parent().toggleClass("open");
			$(this).siblings(".action").slideToggle(200);
			if( $(this).parent().is(".open")) {
				$(this).children("img").attr("src",$(this).children("img").attr("src").replace(/norm/,"inv"));
			} else {
				$(this).children("img").attr("src",$(this).children("img").attr("src").replace(/inv/,"norm"));
			} 
		} else {
			if (!$(this).parent().hasClass("open")){
				$(this).not(".noaction").parent().addClass("open");
				var current = $(this);
				$(this).parent().siblings("li").filter(".open").children(".action").slideUp(250,function(){
					$(this).siblings().children("img").attr("src",$(this).siblings().children("img").attr("src").replace(/inv/,"norm"));
					$(this).parent().removeClass("open");
					current.not(".noaction").children("img").attr("src",current.children("img").attr("src").replace(/norm/,"inv"));
					current.not(".noaction").siblings(".action").slideDown(200);
				});
			}else{
				$(this).parent().removeClass("open");
				$(this).siblings(".functionEntry").children("img").attr("src",$(this).siblings(".functionEntry").children("img").attr("src").replace(/inv/,"norm"));
				$(this).siblings(".action").slideUp(200);
			}
		}
	});
}

function loadTooltips() {
	// stocklist hover
	$(".isPlankStockListTooltipEntry").mouseover(function(){
		$(this).parents().siblings(".tooltipHelper").children(".isPlankStockListTooltip").show();
	}).mouseout(function(){
		$(this).parents().siblings(".tooltipHelper").children(".isPlankStockListTooltip").hide();
	});
}


function frameworkLanguage() {
	//language select
	$(".divider .lang .select").mouseover(function(){
		$(this).addClass("hover");
	}).mouseout(function(){
		$(this).removeClass("hover");
	}).click(function(){
		$(this).toggleClass("open");
		$(this).children("ul.options").children("li").filter(".hide").toggle();
	});
	$(".divider .lang .select ul.options li").mouseover(function(){
		$(this).addClass("hover");
	}).mouseout(function(){
		$(this).removeClass("hover");
	});
}


function aboutGeneral() {
	// highlight aboutme target
	$(".aboutSection").each(function(){
		if( "#"+$(this).attr("id") == location.hash ) {
			$(this).addClass("highlightAboutTarget");
		}
	});
	$("ul.aboutNav li").click(function(){
		$(".aboutSection").nextAll().removeClass("highlightAboutTarget");
		$(location.hash).addClass("highlightAboutTarget");
	});
}


function aboutFaq() {
	//faq
	$("div.aboutSection div.aboutContainer dl.faq dt").click(function(){
		$(this).next().slideToggle(250);
		$(this).toggleClass("open");
	});
	$("div.aboutSection div.aboutContainer span.showall").click(function(){
		$(this).siblings(".body").find("dt").addClass("open");
		$(this).siblings(".body").find("dd").slideDown(250);
	});
	$("div.aboutSection div.aboutContainer span.hideall").click(function(){
		$(this).siblings(".body").find("dd").slideUp(250, function(){
			$(this).prev().removeClass("open");
		});
	});
}


function productpageThumbs() {
	//product presentation thumbnails
	$("div.productImageThumbs img").click(function() {
	    var t = $(this),
	    pn = $("#view360Flash").parent(),
	    nd;
	    
	    $("#view360Flash").remove();
	    
	    pn.prepend("<div id=\"view360Flash\"></div>");
	    
	    if (!t.hasClass("selected")) {
		    t.siblings().removeClass("selected");
		    $(".productImage").children("img").addClass("hideImp");
		    $(".productImage").children("img." + t.attr("class")).removeClass("hideImp");
		    t.addClass("selected");
		}
	});
}

function checkPickUp(that, hasValue) {
    if (that.checked || hasValue) {
        $(".leftFormEl .error").css({
            display : "none"
        });
        return true;
    } else {
         $(".leftFormEl .error").css({
            display : "inline"
        });
        return false;
    }
};

function commerceCheckConditions() {
	// create account checkbox check

	$(".agreeInput input").click(function(){
		/*if( $(this).is(":checked") ) {
			$("span.agreeError").addClass("hide");
		}*/
		if (this.checked) {
		    $(this).parent().siblings(".error").hide();
		} else {
		    $(this).parent().siblings(".error").show();
		}
	});
	
	$("input.agreeButton").click(function () {
	    
	    var result = true, gotNothing = [];
	    
	    $(".homedelivery .error").parent().each(function () {
	        
	        var delAddr = $(this).find(".deliveryAddress2"), err = $(this).find(".error"), inputs = $(this).find("input"), allFalse = [], bl;
	        if (delAddr.length) {
	            $(delAddr).parent().parent().find("input").each(function () {
	                if ((this.type === "text" && this.value) || (this.type === "checkbox" && this.checked)) {
	                    allFalse.push(this);
	                }
	                
	                bl = function () {
                        var tErr = $(this).parent().find(".error");
                        if (!this.value) {
                            tErr.show();
                        } else {
                            tErr.hide();
                        }
                    };
	                
	                if (this.type === "checkbox") {
	                    $(this).click(function () {
	                        var tErr = $(this).parent().find(".error");
	                        if (!this.checked) {
	                            $(delAddr[0]).bind("blur", bl);
	                            tErr.show();
	                        } else {
	                            $(delAddr[0]).unbind("blur", bl);
	                            tErr.hide();
	                        }
	                    });
	                }
	            });
	            
	            if (!allFalse.length) {
	                $(delAddr[0]).bind("blur", bl);
	                gotNothing.push(delAddr[0]);
	                result = false;
	                err.show();
	            } else {
	                $(delAddr[0]).unbind("blur", bl);
	                err.hide();
	            }
	            
	        } else {
	            if ((inputs[0].type === "text" && !inputs[0].value) || (inputs[0].type === "checkbox" && !inputs[0].checked)) {
	                gotNothing.push(inputs[0]);
	                result = false;
	                err.show();
	            } else {
	                err.hide();
	            }
	        }
	    });
	    
	    if (gotNothing.length) {
	        gotNothing[0].focus();
	    }
	    
	    return result;
	    
	});
}


function frameworkHover() {
	$("img.hover").hover(function () {
	    var t = $(this);
		t.attr("src", t.attr("src").replace(/hout/,"hover"));
	}, function () {
	     var t = $(this)
		t.attr("src", t.attr("src").replace(/hover/,"hout"));
	});
}



function setTransid(id) {
	$('#ctl00_WideContentPH_HFTransactionID').attr('value', id);
}


function triggerConfirm() {
	$('div.paybybmcard input.pin2').attr('value', '2468');
	$('div.paybybmcard input.pin').attr('value', '2468');
	$('#ctl00_WideContentPH_BtnConfirm').trigger('click');
}


function triggerBackBtn() {
	$('#ctl00_WideContentPH_BtnBack').trigger('click');
}


/* returns value of variable in querystring (?variable=value) */
function getQueryVariable(querystring, variable) {
	var query = querystring.substring(1);
	var vars = query.split("&");
	for (var i=0;i<vars.length;i++) {
		var pair = vars[i].split("=");
		if (pair[0] == variable) {
			return pair[1];
		}
	}
}


function askForZip() {
	/*if (readCookie('askForZip') == 'false') {
		// do nothing
	}
	else if (readCookie('askForZip') == null) {
		// first time()
		createCookie('askForZip','false',999);
		
		// fix for ppl with cookies disabled
		if( readCookie('askForZip') == 'false' ) {
			$(".divider").append( $(".askForZip") );
			$(".askForZip").show();
		}
	}*/
	var c = document.cookie, 
	askForZip = c.match(/askForZip\=fals[e]/) ? false : true, 
	tz = $(".login .topzip")[0];
	
	//tz.value = tz.value.replace(/\D/g, "");
	
	if (askForZip && !tz.value) {
	    createCookie("askForZip", "false", 999);
	    $(".divider").append($(".askForZip"));
	    $(".askForZip").show();
	    tz.focus();
	    
	    setTimeout(function () {
	        $(".askForZip").hide("slow");
	    }, 10000);
	}
}


function askForSurvey() {
	if (readCookie('askForSurvey') == 'false') {
		// do nothing
	}
	else {
		// show surveylink
		$(".askForSurvey").removeClass("hide");
	}
	
	$(".closeAskForSurvey").click(function () {
		createCookie('askForSurvey','false',999);
		$(".askForSurvey").addClass("hide");
	});
}


function showEcommerceGuideOnce() {
    
	if (readCookie('showEcommerceGuide') == 'false') {
		// do nothing
	}
	else {
		$(".triggerShowEGuide").click(function () {
			if (readCookie('showEcommerceGuide') == 'false') {
				// do nothing
			}
			else {
				createCookie('showEcommerceGuide','false',999);
				$(".showEcommerceGuide").show();
				$(".triggerShowEGuide").unbind();
			}
		});
	}
}


/*** cookie handling ***/
/*** http://www.quirksmode.org/js/cookies.html ***/
function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}
/*** end cookie handling ***/



/*** make separator bar fixed ***/
function makeSeparatorBarFixed() {
	var isFixed = false;

	$(window).scroll(function() {
		if($(window).scrollTop() > 97) {
			if(!isFixed) {
				$('.divider').css({
					position: "fixed",
					left: "50%",			// only needed for ie
					marginLeft: "-495px"	// only needed for ie
				});

				isFixed = true;
			}
		}
		else {
			if(isFixed) {
				$('.divider').css({
					position: "relative",
					left: "0",				// only needed for ie
					marginLeft: "0"			// only needed for ie
				});

				isFixed = false;
			}
		}
	});
}



/*** truncate textBox text ***/
function truncateTextBox() {
	/* set truncate height */
	var newHeight =	176;

	$(".textBoxContainer").each(function() {

		if( $(".textBox",this).height() > newHeight ) {
			/* remember original height before setting new height */
			var origHeight = $(".textBox",this).height();
			$(".textBox",this).height(newHeight);

			/* set height and display "show more" */
			$(this).addClass("isTruncated showmore");


			/* attach "show more" and "show less" event */
			$(".bottom", this).toggle(function() {

				/* animate more text */
				$(this).siblings(".textBox").animate({
					height: origHeight +"px"
				},function() {

					/* remove "show more" */
					$(this).parent().removeClass("showmore");
				});
			},function() {

				/* animate less text */
				$(this).siblings(".textBox").animate({
					height: newHeight +"px"
				},function() {

					/* display "show more" */
					$(this).parent().addClass("showmore");
				});
			});
		}
	});
}

/*** 
 *
 * qlickview live search engine, prepares for ByggmaxSearch.js to do magic
 *
 ***/ 
function qvLiveSearch() {

	/***
	  * mark search key word in result
	  * @param key - search key
	  * @param str - the string to be marked
	  */
	
	if (window.Qww) {
	  
	    markSearchWord = function(key, str) {
    	    var r = new RegExp('('+key+')', 'gi');
    	    var h = "<span class='QwwJs_GlobalSearch-Searchword'>$1</span>";    	
		    return str.replace(r, h);
	    }


	    // hide / unhide live search container
	    $(".qsearch").keyup(function(e) {

		    // hide live search container
		    if( $(".qsearch").val() == "" ) {
			    $(".liveSearchPopin").hide();
		    }

		    // unhide live search container
		    else {
			    $(".liveSearchPopin").show();
		    }
	    });


	    // show / hide live search ajax loader
	    var lsObj = $("#liveSearchLoader");
	    function showSpinner(show) {
		    lsObj.css("display", (show ? "block" : "none"));
	    }


	    // bind qv live search CloseSearch to outer close
	    $(".liveSearchPopin .ipClose").unbind();
	    $(".liveSearchPopin .ipClose").bind("click", function() {
    	
		    // trigger qv live search close event
		    $(".QwwJs_GlobalSearch-CloseSearchIcon").trigger("click");
    		
		    // hide popin
		    $(this).parent().parent().hide();
	    });


	    // define qv-specific stuff
	    var objQvExSearchCtl1 = new Qww.Ctls.GlobalSearch.Mgr(
	    {
		    "Fields": [
			    new Qww.Ctls.GlobalSearch.Field({
				    ObjectID: "QV_SEARCH_"+CURRENT_STORE_ID +"_" +CURRENT_MARKET_AND_LANGUAGE,
				    MaxNumberOfResultsToShow: 70
			    })
		    ],
		    "ResultsElementId": "QvExSearchCtl1_results",
		    "SearchTextBoxId": "ctl00_LeftMenuContentPH_LeftProductMenu_TBSearchTextBox", //"QvExSearchCtl1_txtSearch",
		    "AutomaticallyClearSearchString": true,
		    SearchInterval:200,
		    OnGetSearchString: function(str) { return "*" + str + "*||*"; },
		    OnRenderResultsSection: renderByggmaxResults,
		    OnBeforeCloseSearch: function(searchCtl, isFromCloseButton) { 
			    //alert("before  close " + isFromCloseButton);
		    },
		    OnSearchClosed: function(searchCtl, isFromCloseButton) {
			    //alert("search closed " + isFromCloseButton);
		    },
		    OnSearchInitiated: function() {
			    showSpinner(true);
		    },
		    OnSearchCompleted: function() {
			    showSpinner(false);
		    }
	    });
	    //var dataPumpDomain = /www.byggmax.com/gi.test(location.href) ? "www.byggmax.com" : "localhost";
	    var dataPumpDomain = document.location.toString().match(/^(http[s]?:\/{2})(cn(\-)?note(\d+)|(www\.)?byggmax\.com|localhost|byggmax|cloudnine\.se)/ig).toString().trim();
    	
	    //var dataPumpDomain = document.location.toString().match(/(cn(\-)?note(\d+)|www\.byggmax\.com|localhost|byggmax\.cloudnine\.se)/ig).toString().trim().replace(/\,(cn(\-)?note(\d+)|www\.byggmax\.com|localhost|byggmax\.cloudnine\.se)/, "");
    	
	    //var https = (/^https/).test(document.location) ? "s" : "";
	    //var dump = "http" + https + "://" + dataPumpDomain + "/qvsdatapump/QvsViewClientEx.ashx"
	    //alert("https = " + https + "\n" + dump);
	    //qwwHub.RegisterWorkBenchOnlyDocument({ Application: "QV_SEARCH", DataPump: "http" + https + "://" + dataPumpDomain + "/qvsdatapump/QvsViewClientEx.ashx" });
        qwwHub.RegisterWorkBenchOnlyDocument({ Application: "QV_SEARCH", DataPump: dataPumpDomain + "/qvsdatapump/QvsViewClientEx.ashx" });
    }
}




/*** 
 *
 * qlickview live search render, needed for qv engine
 *
 ***/
function renderByggmaxResults(results, lbId, lbTitle, lbMatchString, lbNoMatchString, maxLengthOfMatchStringToShow, maxNumberOfResultsToShow, lbSelectAllText, lbReduceResultstext) {

	var html = "";

	if(results == null) {
		html = LIVESEARCH_NORESULTS;
	}
	else {
	    var marketAndLanguageBranch = CURRENT_MARKET_AND_LANGUAGE;
	    var categories = {};
		var searchKey = $(".qsearch").val();

	    for (var i = 0; i < results.length; i++) {
	
	        var mainParts = results[i].Text.split("||");
	
	        var parts = mainParts[0].split('#');
	
	        var productID = parts[0];
	        var catNameDisplay = parts[1];
	        var subCatNameDisplay = parts[2];
	        var name = parts[3];
	        var description = parts[4];
	        
	        var purchasePrice = parts[6];
	        var displayPrice = parts[7];
	
	        var privateParts = mainParts[1].split('#');
	
	        var catPrivateName = privateParts[0];
	        var subCatPrivateName = privateParts[1];
	
	        var categoryHeading = catNameDisplay + " / " + subCatNameDisplay;
	
	        if (categories[categoryHeading] == null) {
	
	            var Results = {};
	            Results.Items = [];
	            Results.LinkTextCat = catNameDisplay;
	            Results.LinkTextSubCat = subCatNameDisplay;
	            Results.LinkUrlCat = marketAndLanguageBranch + "/Prod/" + catPrivateName + "/Default.aspx"
	            Results.LinkUrlSubCat = marketAndLanguageBranch + "/Prod/" + catPrivateName + "/" + subCatPrivateName + "/Default.aspx"
	            categories[categoryHeading] = Results;
	        }
	
	        if (categories[categoryHeading].Items.length < 50) {
	
	            var obj = {};
	            obj.productID = productID;
	            obj.Name = name;
	            obj.Description = description;
	            obj.LinkUrl = marketAndLanguageBranch + "/Prod/PID-" + productID + ".aspx";
	            obj.purchasePrice = purchasePrice;
	            obj.displayPrice = displayPrice;
	            
	            categories[categoryHeading].Items.push(obj);
	        }
	    }
	
		for (c in categories) {
	
			var cat = categories[c];
	
			html += "<div class='Byggmax-SearchResult-Category'>";
			html += "  <a href='http://www.byggmax.com/" + cat.LinkUrlCat + "'>";
			html +=      markSearchWord(searchKey, cat.LinkTextCat);
			html += "  </a> /"
			html += "  <a href='http://www.byggmax.com/" + cat.LinkUrlSubCat + "'>";
			html +=      markSearchWord(searchKey, cat.LinkTextSubCat);
			html += "  </a>";
			html += "</div>";
	
			html += "<div class='Byggmax-SearchResult-DetailSection'>";
	
			var arr = cat.Items;
	
			for (var i = 0; i < arr.length; i++) {
	
				var prod = arr[i];
			
			    /*if (!window.firstRun) {
			        
			        var p = prod, k, str = "";
			        for (k in p) {
			            str += k + " = " + p[k] + "\n";
			        }
			        
			        alert(str);
			        
    			    window.firstRun = true;
			    }*/
	
				html += "<div class='Byggmax-SearchResult-ProductRow" + (i%2==0 ? " even" : "") + "'>";
				html += "  <a href='http://www.byggmax.com/" + prod.LinkUrl + "'>";
				html += "    <span class='Byggmax-SearchResult-Name'>"
				html +=        markSearchWord(searchKey, prod.Name);
				html += "    </span>";
				html += "    <span class='Byggmax-SearchResult-Description'>";
				html +=        markSearchWord(searchKey, prod.productID) + " - " + markSearchWord(searchKey, prod.Description);
				html += "    </span>";
				
				html += " : <span class=\"purchasePrice\">" + markSearchWord(searchKey, prod.purchasePrice) + " </span>";
				
				if (markSearchWord(searchKey, prod.purchasePrice) !== markSearchWord(searchKey, prod.displayPrice)) {
				    html += "<span> " + markSearchWord(searchKey, prod.displayPrice) + " </span>";
				}
				
				html += "  </a>";
				html += "</div>";
			}
	
			html += "</div>";
		} // end for
		html += "<a class='poweredbyQVLink' href='http://www.qlikview.com'>";
		html += "  <img class='poweredbyQV' src='/image/powered.by.qlikview.png' alt='powered by QlikView' />";
		html += "</a>"
	} // end if


	return html;
}

$(document).ready(function () {
    var showHideButtons;
    
    $(".addCorners").each(function () {
        var supClass = this.className.match(/(^|\s)css3Support(\-[a-zA-Z]+)+(\s|$)/g),
        shouldSupport = supClass ? supClass.toString().replace(/css3Support\-/, "").split("-") : null;
        
        if (shouldSupport) {
            addCorners(this, shouldSupport);
        } else {
            addCorners(this);
        }
    });
    
    $("div.handyMan h3").click(function () {
         var pn = $(this.parentNode);
         
         if (pn.hasClass("notVisib")) {
            pn.removeClass("notVisib");
         } else {
            pn.addClass("notVisib");
         }
    });
    
    $("div.slideContainer a").each(function () {
        var loc = this.href;
        $(this).parents("td, tr").css({
            cursor : "pointer"
        }).addClass("hasClick").click(function (e) {
            document.location = loc;
        });
    });
    
    // If the user have more merchandise than the current shop has in store, tell the user about that fact.
    $(".shoppinglist .products > table > tbody").each(function () {
        var that = this, t = $(this), aa, sa, availAmount, setAmount, errorMsg;
        
        aa = t.find("td.status strong");
        sa = t.find("tr.order td.amount input[name=amount]");
        
        availAmount = aa.length ? parseInt(aa[0].innerHTML.toString().replace(/\D/g, ""), 10) : "";
        // setAmount = the amount of merchandise selected by the user
        setAmount = sa.length ? parseInt(sa[0].value.toString().replace(/\D/g, ""), 10) : "";
        
        errorMsg = function () {
            that.style.backgroundColor = "#ef5959";
                
            sa.css({
                backgroundColor : "#ef5959"
            });
        };
        
        if (availAmount && setAmount) {
            if (setAmount > availAmount) {
                errorMsg();
            }
        } else if (!availAmount && setAmount) {
            // if availAmount is NaN (ex: 'Okänt')
            aa.find(".error").css({
                backgroundColor : "#fff"
            });
            errorMsg();
        }
    });
    
    // Adds a click event to the countryflag on the startpage
    $(".start .CustomerInterview .foldout").each(function () {
        var t = $(this), href;
        
        // The <div> to be clicked
        t.prepend("<div class=\"startFlagOvly\"></div>");
        
        t.find(".startFlagOvly").css({
            opacity : 0
        });
        
        // The (hidden) link
        href = t.parent().find(".mid h3.with_interview a").length ? t.parent().find(".mid h3.with_interview a")[0] : null;
        
        if (href && t[0] && t[0].firstChild) {
            t[0].firstChild.style.cursor = "pointer";
            // Add the click event to the transparent div
            $(t[0].firstChild).click(function () {
                document.location = href;
            });
        }
    });
    
    // Init the popup calendarpicker (cart)
    $("div.right .freightDate").each(function () {
        var that = this, 
        sd = $("a.selDate"), 
        dynPos,
        closeCalendar;
        
        if (sd.length) {
            // Move the calendar to the end of the <body>
            document.body.appendChild(that);
            that.style.visibility = "hidden";
            that.id = "ddCalendar";
            
            $(that).prepend("<img src=\"/image/fastCheckout/icon.close.calendar.png\" alt=\"\" class=\"closeCalendar\" />");
            
            // Add a click event to the "change day" button
            $("a.selDate:first").each(function () {
                var that2 = $(this), 
                that3, 
                cs, 
                changeDeliveryDate, 
                ua = navigator.userAgent;
                
                closeCalendar = function () {
                    $(that).hide();
                    $(document).unbind("click", closeCalendar);
                    $(that).unbind("click", closeCalendar);
                    
                    
                    if ((/MSIE\s[6]/).test(ua)) {
                        $(document.body).removeClass("noSelect");
                    }
                };
                
                $(".freightDate .closeCalendar").click(closeCalendar);
                
                that2.click(function (e) {
                    e.preventDefault();
                    that3 = document.getElementById("ddCalendar");
                    cs = getStyle(that3, "display");
                    if (cs === "none") {
                        $(that).show();
                        setTimeout(function () {
                            $(document).bind("click", closeCalendar);
                        }, 10);
                        
                        if ((/MSIE\s[6]/).test(ua)) {
                            $(document.body).addClass("noSelect");
                        }
                        dynPos();
                    } else {
                        closeCalendar();
                    };
                });
            });
            
            // gets the position of the "change day" button and positions the calendar beneath it.
            dynPos = function (init) {
                var asd = $("a.selDate:first"), ot, ol, ow, h, w;
                ot = parseInt(asd.offset().top, 10);
                ol = parseInt(asd.offset().left, 10);
                
                ow = that.offsetWidth;
                
                h = asd[0].offsetHeight;
                w = asd[0].offsetWidth;
                
                that.style.top = parseInt(ot + h, 10) + "px";
                that.style.left = parseInt(ol - ((ow / 2) - (w / 2)), 10) + "px";
                
                if (init && typeof init === "boolean") {
                    // Change the way the calendar is displayed (from visibility to display)
                    // This is done because width "visibility" the calendar has a height and a width, with "display:none" it has not.
                    that.style.visibility = "";
                    $(".freightDate .calendarText, .freightDate .continueButton").hide();
                    $(".freightDate").hide();   
                }
            };
            dynPos(true);
            
            // Check the position of the calendar if the window is resized.
            $(window).resize(dynPos);
            
            
            // Adds a "col-n" class to the weekday <td>s, ex: <td class="col-2">
            $(".freightDate table table table table tr").each(function () {
                var i = 1; // Start width Monday (1)
                $(this).find("td").each(function () {
                    $(this).addClass("col-" + i);
                    if (i === 6) {
                        i = 0; // End with Sunday (0)
                    } else {
                        i += 1;
                    }
                });
                i = 1;
            })
            
            // Change the delivery date (only done so the user can see the date beeing changed, no back-end dependencies)
            
            changeDeliveryDate = function () {
                var month, date = this.innerHTML.trim(), orgMonth;
                
                // get year and the name of the month
                orgMonth = $(".eo_Cal_Arrows:first + td")[0].innerHTML;
                // Replace all digits and white-space and get the month name
                month = orgMonth.replace(/\d/g, "").trim().toLowerCase();
                
                document.getElementById("delDate").innerHTML = date;
                document.getElementById("delMonth").innerHTML = month;
                
                closeCalendar();
            };
            
            $(".freightDate td div.eo_Cal_Day, .freightDate td div.eo_Cal_Day_Selected").click(changeDeliveryDate);
            
            $(".eo_Cal_Arrows").click(function () {
                $(".freightDate td div.eo_Cal_Day, .freightDate td div.eo_Cal_Day_Selected").click(changeDeliveryDate);
            });
        }
    });
    
    
    
    if ($(".fastCheckout").length) {
        var changeButton, checkCrane;
        
        changeButton = function () {
            $(".fastCheckout .inner a[id$=Buy]").each(function () {
                var t = $(this);
                t.addClass("notVisible");
            });
            
            $(".fastCheckout .inner a[id$=CalculateFreight]").each(function () {
                var t = $(this);
                t.removeClass("notVisible");
                t.replaceClass("buyButton", "calcButton");
            });
            
            setTimeout(checkCrane, 500);
        };
        
        // Check if the delivery will be done by cranetruck or pallet.
        checkCrane = function () {
            var imgs = document.images, i, cranes = 0, cbgi, quantity, lang = document.body.className.match(/language\-\w{2}/g).toString().replace(/language\-/, "");
            
             if ((/MSIE\s6/).test(navigator.userAgent)) {
                // Theres some funky PNG-fixes in here so we have to do a special thingy for IE 6
                for (i = 0; i < imgs.length; i += 1) {
                    cbgi = getStyle(imgs[i], "filter");
                    
                    // If the src OR the background-image is "crane_mini.png" 
                    if ((imgs[i].className && imgs[i].className === "deliveryType" && (/crane_mini\.png/i).test(cbgi)) ||  (/crane_mini\.png/i).test(imgs[i].src)) {
                        // Get the current quantity of merchandise
                        quantity = parseInt($(imgs[i]).parent().siblings(".Quantity")[0].innerHTML.trim(), 10);
                        if (quantity > 0) {
                            cranes += 1;
                        }
                    }
                }
             } else {
                // Same thing as the IE thing, but with less fuss.
                $("img[src$='crane_mini.png']").each(function () {
                    var t = $(this);
                    
                    quantity = parseInt(t.parent().siblings(".Quantity")[0].innerHTML.trim(), 10);
                    
                    if (quantity > 0) {
                        cranes += 1;
                    }
                });
            }
            
            // If there is no cranetruck deliveries show the pallettruck
            // Else show the cranetruck
            if (!cranes) {
                $(".cartCar").each(function () {
                    this.src = "/image/fastCheckout/pallet_" + lang + ".png";
                });
            } else {
                $(".cartCar").each(function () {
                    this.src = "/image/fastCheckout/crane_" + lang + ".png";
                });
            }
        }
        
        $("tr.order .amount input[name=amount]").siblings("img").click(changeButton);
        
        $("tr.product td.triggerShowEGuide img").click(changeButton);
        
        $("tr.order .amount input[name=amount]").keydown(function () {
            this.downValue = this.value;
        });
        
        $("tr.order .amount input[name=amount]").keyup(function () {
            if (this.downValue !== this.value) {
                changeButton();
            }
        });
        
        $(".fastCheckout a.noStore").click(function (e) {
            var cz = $(".commercezip")[0];
            
            cz.value = cz.value.replace(/\D/g, "");
            
            if (!$(this).hasClass("warned") && !cz.value) {
                e.preventDefault();
                $(this).addClass("warned");
                cz.focus();
                cz.style.backgroundColor = "#ff0";
                
                $(cz.parentNode).append("<span class=\"tooltip\">Fyll i ditt postnummer</span>");
                
                $(cz.parentNode).find(".tooltip").each(function () {
                    var that = this;
                    
                    that.style.top = parseInt( (cz.offsetHeight / 2) - (that.offsetHeight / 2), 5) + "px";
                    that.style.left = parseInt(cz.offsetLeft + cz.offsetWidth + 10, 10) + "px";
                });
            }
            
        });
    }
    
    $("input.amount, input.commercezip, input.topzip").keyup(function () {
        this.value = this.value.replace(/\D/g, "");
    });
    
    $("input.commercezip").each(function () {
        var tz = $("input.topzip"), val = tz.length ? tz[0].value : "";
        this.value = val;
    });
    
    function liveChangeZipStore (that, selector) {
        var val = that.value;
        $(selector).each(function () {
            this.value = val;
        });
    };
    
    $("input.topzip").bindMulti("blur", "focus", "keyup", function () {
         this.value = this.value.replace(/\D/g, "");
         liveChangeZipStore(this, "input.commercezip");
    });
    
    $("input.commercezip").bindMulti("blur", "focus", "keyup", function () {
         this.value = this.value.replace(/\D/g, "");
         liveChangeZipStore(this, "input.topzip");
    });
    
    $("input.commercezip").focus(function () {
        if(!this.store) {
            this.store = {};
        }
        this.store.value = this.value;
    });
    
    $("input.commercezip").bindMulti("keyup", "blur", function () {
        if (this.value !== this.store.value) {
            $(".bigButton.buyButton:not(.animButton)").removeClass("notVisible").addClass("calcButton");
            $(".bigButton.buyButton.animButton").addClass("notVisible");
        }
    });
    
    //if ($.browser.msie && (/^[67]/).test($.browser.version)) {
    if ((/MSIE\s[67]/).test(navigator.userAgent)) {
        /* This little fantastic "if(IE 6 or 7)" function does the following:
         * Loops all ".fastCheckout .inlinePopUp" and copys all applied styles to the style attribute.
         * Then the inlinePopUp is added to the bottom of the <body>
         * All this because a z-index problem in IE versions earlier then 8.
        */
        
        $(".fastCheckout .inlinePopup").each(function () {
            var that = this, ofs = $(that.parentNode).offset();
            copyStyle(that);
            $(that).find("*").each(function () {
                copyStyle(this);
            });
            
            that.parentNode.popUp = that;
            document.body.appendChild(that);
            
            that.style.top = ofs.top + "px";
            
            if (that.currentStyle.right && that.currentStyle.right !== "auto") {
            
                that.style.display = "block";
                that.style.visibility = "hidden";
                
                that.style.left = parseInt(parseInt(ofs.left - that.offsetWidth, 10), 10) + "px";
                
                that.style.display = "none";
                that.style.visibility = "visible";
                
            } else {
                that.style.left = ofs.left + "px";
            }
            
        });
    }
    
    $(".outer > div.right").click(function () {
        if(this.currentStyle && (parseInt(this.offsetWidth, 10) > 210)) {
            this.style.paddingRight = 0;
        }
    });
    
    $("iframe#visamcFrame").each(function () {
        var checkDelay, 
        count = 0, 
        docLoc = document.location.toString().match(/\/[a-z]{2}\-[a-z]{2}/), 
        fiveTimer, 
        min = 5, 
        sek = 0, 
        tow, 
        countZero = 0, 
        to,
        tenMin = ((1000 * 60) * 10);
        
        $(".paybyvisamc.payby").prepend("<div id=\"timeoutTimerWarning\"></div>");
        
        tow = document.getElementById("timeoutTimerWarning");
        
        fiveTimer = function () {
            
            if (sek < 10) {
                sek = "0" + parseInt(sek, 10);
            }
            
            if (min > -1) {
                tow.innerHTML = globalVariables.checkout.timeOutMessage + ": " + min + ":" + sek;
            } else {
                tow.innerHTML = "0:00";
            }
            sek = parseInt(sek, 10);
            
            if (!sek) {
                min -= 1;
                sek = 60;
            }
            sek -= 1;
            if (!countZero && (parseInt(min, 10) <= 0) && (parseInt(sek, 10) <= 0)) {
                to = setTimeout(arguments.callee, 1000);
                setTimeout(function () {
                    clearTimeout(to);
                    document.location = docLoc + "/Cart.aspx";
                }, 2000);
            } else {
                to = setTimeout(arguments.callee, 1000);
            }
        };
        
        checkDelay = setTimeout(function () {
            fiveTimer();
        }, tenMin);
        
    });
    
    $(".paybybmcard .bmCardNumber input").each(function () {
        var t = $(this);
        this.maxLength = 4;
        
        t.bindMulti("keypress", "keyup", function () {
            this.value = this.value.replace(/\D/g, "");
        });
        
        t.keyup(function () {
            var that = this;
            if (this.value.length === this.maxLength) {
                $(that).next("input").focus();
            }
        });
    });
    
    $(".products .status strong span.info, table.productData td.stock span.info").each(function () {
        var that = this,
        ua = navigator.userAgent,
        t = $(that),
        tp = t.parents("td"),
        closeAlt,
        pop = function () {
            var css3support = function () {
                if (!styleIsSupported("border-radius") || !styleIsSupported("box-shadow")) {
                    return false;
                }
                return true;
            },
            nc3 = tp.find(".inlinePopupDeluxe"),
            nc3ofsw,
            closeIE = function () {
                if((/MSIE\s[67]/).test(ua)) {
                    $("table.productList span.info, table.productData span.info").css({
                        display : "inline-block"
                    });
                }
            };
            //tp.append("<div class=\"ipWrapper\"><div class=\"inlinePopupDeluxe\"><p>" + globalVariables.emailWhenInStock.text + "</p><p><input type=\"text\" value=\"" + globalVariables.emailWhenInStock.input + "\" /></p></div></div>");
            //tp.find(".inlinePopupDeluxe").append("<div class=\"sendButton\"><div class=\"buttonStart\"><!-- ie6fix --></div><div class=\"buttonMid\"><input type=\"button\" value=\"" + globalVariables.emailWhenInStock.button + "\" /></div><div class=\"buttonEnd\"><!-- ie6fix --></div></div>");
        
            if(!css3support()) {
                //nc3 = tp.find(".inlinePopupDeluxe");
                nc3ofsw = nc3[0].offsetWidth;
                nc3.addClass("notCss3");
                
                nc3.wrapInner("<div class=\"riBo\"><div class=\"leBo\"><div class=\"midWrap\" style=\"width: " + nc3ofsw + "px\"></div></div></div>");
                nc3.prepend("<div class=\"popTop\"><div class=\"leCo\"><!-- ie --></div><div class=\"riCo\"><!-- ie --></div><div class=\"midFil\" style=\"width: " + nc3ofsw + "px\"><!-- ie --></div></div>");
                nc3.append("<div class=\"popBottom\"><div class=\"leCo\"><!-- ie --></div><div class=\"riCo\"><!-- ie --></div><div class=\"midFil\" style=\"width: " + nc3ofsw + "px\"><!-- ie --></div></div>");
                
                closeAlt = nc3.find(".midWrap img").attr("title");
                nc3.find(".midWrap img").remove();
                
                tp.find(".inlinePopupDeluxe").append("<img title=\"" + closeAlt + "\" class=\"ipClose\" alt=\"\" src=\"/image/icon.close.png\" />");
                
                $("img.ipClose").click(closeIE);
            }
            
            
            
            nc3.css({
                display : "none",
                visibility : "visible"
            });
            
        },
        infoSpan,
        infoSpan2;
        
        pop();
        
        // remove this
        //$(".previewContainer").remove();
        
        t.click(function () {
            var ipdlx = tp.find(".inlinePopupDeluxe"),
            ua = navigator.userAgent;
            
            $(".inlinePopupDeluxe").each(function () {
                if (this !== ipdlx[0]) {
                    $(this).hide();
                }
            });
            
            if(ipdlx.css("display") === "none" || ipdlx.parent().css("display") === "none") {
            
                tp.find(".inlinePopupDeluxe").parent().css({
                    display : "block"
                }).show();
                
                tp.find(".inlinePopupDeluxe").css({
                    display : "block"
                }).show();
                
                // This is for IE7
                if((/MSIE\s[67]/).test(ua)) {
                    $("table.productList span.info, table.productData span.info").each(function () {
                        var that2 = this,
                        t = $(this),
                        pn = pNode(that, "td"),
                        ofs = $(pn).offset(),
                        getDlxCoords = function () {
                            var dlx = null, 
                            result = null,
                            ofs = null;
                            
                            if (ipdlx.length) {
                                ofs = $(pNode(ipdlx[0], "td")).offset();
                                
                                result = {
                                    top : ofs.top,
                                    bottom : parseInt(ofs.top + ipdlx[0].offsetHeight, 10)
                                }
                            }
                            
                            return result;
                        },
                        dlxc = getDlxCoords(),
                        infoCoords = function () {
                            var result = null,
                            ofs = $(pNode(that2, "td")).offset();
                            
                            result = {
                                top : ofs.top,
                                bottom : parseInt(ofs.top + ipdlx[0].offsetHeight, 10)
                            }
                            
                            return result;
                        },
                        ic = infoCoords();
                        
                        if (ic && dlxc) {
                            if (ic.top > dlxc.top && ic.top < dlxc.bottom) {
                                t.css({
                                    display : "none"
                                });
                            }
                        }
                        
                    });
                }
                // end IE7 fix
            } else {
                
                tp.find(".inlinePopupDeluxe").css({
                    display : "none"
                });
                
                if((/MSIE\s[67]/).test(ua)) {
                    $("table.productList span.info, table.productData span.info").css({
                        display : "inline-block"
                    });
                }
            }
        });
        
        tp.find("input[type=button].notInStock").click(function () {
            var t = $(this), 
            pIdp = t.parents("tr.product").find(".ProductId"),
            pId = pIdp.length ? pIdp[0].innerHTML : "",
            sId = document.getElementById("ctl00_HFstoreId").value,
            emailInput = t.parents(".inlinePopupDeluxe").find("p input[type=text]"),
            email = emailInput.val(),
            lang = document.body.className.match(/language\-[a-z]{2}/g).toString().replace(/language\-/, ""),
            validEmail = /^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i ,
            checkEmail = function () {
                // validEmail regexp taken from:
                // http://xyfer.blogspot.com/2005/01/javascript-regexp-email-validator.html
                return (validEmail).test(email);
            },
            hasHiddenStore = t.parents("div.inlinePopupDeluxe").find("input[type=hidden]"),
            hiddenStoreId = hasHiddenStore.length ? hasHiddenStore[0].value : null;
            
            if (!pId) {
                pId = $("strong.productNumber").length ? $("strong.productNumber")[0].innerHTML :  "";
            }
            
            if (hiddenStoreId) {
                sId = hiddenStoreId;
            }
            
            t.parents("div.inlinePopupDeluxe").find("span.error").remove();
            
            if (checkEmail()) {
                $.getJSON("/Ajax/AddQuantityReminder.ashx", {
                    "partid" : pId,
                    "storeid" : sId,
                    "email" : email,
                    "lang" : lang
                }, function (json) {
                    if (json.Success === "True") {
                        var epip = emailInput.parents(".inlinePopupDeluxe");
                        epip.addClass("success");
                        
                        setTimeout(function () {
                            epip.css({
                                display : "none"
                            });
                            
                            if((/MSIE\s[67]/).test(ua)) {
                                $("table.productList span.info, table.productData span.info").css({
                                    display : "inline-block"
                                });
                            }
                            
                        }, 3000);
                    }
                });
            } else {
                emailInput.parent().prepend("<span class=\"error\">\"" + email + "\" " + globalVariables.error.notValidEmail + "</span>");
                emailInput.attr("value", "");
                emailInput.focus();
                
                emailInput.keydown(function () {
                    emailInput.parent().find("span.error").remove();
                });
            }
        });
        
    });
    
    var movieHasVote = function (e) {
        e.preventDefault();
    };
    var movieVote = function (e) {
         var that = this,
        t = $(that),
        vote = that.className.match(/(^|\s)v[123](\s|$)/g).toString().replace(/\D/g, ""),
        mId = document.getElementById("movieId"),
        mIdVal = mId ? mId.value : null,
        mov = t.parents(".movieScore");
        
        e.preventDefault();
        
        if (mIdVal) {
            $.getJSON("/Ajax/votemovie.ashx", {
                "movieID" : mIdVal,
                "vote" : vote
            }, function (json) {
                
                mov.find("a.v1 span").html(json.vote1 + "%");
                mov.find("a.v2 span").html(json.vote2 + "%");
                mov.find("a.v3 span").html(json.vote3 + "%");
                
                mov.find("div span").html(json.numberOfVotes);
                
                $("div.movieScore ol.notVoted a").unbind("click", movieVote);
                
                mov.find("ol.notVoted, div.notVoted").replaceClass("notVoted", "voted");
                
                $("div.movieScore ol.voted a").click(movieHasVote);
            });
        }
    };
    
    $("div.movieScore ol.notVoted a").bind("click", movieVote);
    $("div.movieScore ol.voted a").click(movieHasVote);
    
    if ($("div.productsTabs").length) {
        
        var tabContTest = $("div.productsTabs"),
            tabCont = tabContTest.length ? tabContTest[0] : null,
            prodTabTest = $("div.prodTab"),
            prodTab = prodTabTest.length ? prodTabTest[0] : null;
        
        $("div.productsTabs li a.suppl").click(function (e) {
            e.preventDefault();
            
            var t = $(this);
            
            $("div.productsTabs li a").parent().removeClass("active");
            
            t.parent().addClass("active");
            
            $("div.suppliers").css({
                display : "block"
            });
            $('.productInfo').parent().css({
                display : "none"
            });

            $('.cdFromByggla').hide()
        });

        $("div.productsTabs li a.byggla").click(function (e) {
            e.preventDefault();
            
            var t = $(this);
            
            $("div.productsTabs li a").parent().removeClass("active");
            
            t.parent().addClass("active");
            
            $("div.suppliers").hide();

            $('.productInfo').parent().css({
                display : "none"
            });

            $('.cdFromByggla').show()
        });
        
        $("div.productsTabs li a.prod").click(function (e) {
            e.preventDefault();
            
            var t = $(this);
            
            $("div.productsTabs li a").parent().removeClass("active");
            
            t.parent().addClass("active");
            
            $("div.suppliers").css({
                display : "none"
            });
            $('.productInfo').parent().css({
                display : "block"
            });

            $('.cdFromByggla').hide()
            
        });
    }
    
    //$("img[src^='http://load.ehandelscertifiering.se/']").parent().parent().addClass("cert");
});

$(window).load(function () {
    var ua = navigator.userAgent;
    
    $("img.browseNext, img.browsePrev").each(function () {
        var that = this,
        t = $(this),
        url = that.parentNode.href,
        ofs = t.offset(),
        top = ofs.top,
        left = ofs.left,
        middle = parseInt(that.offsetHeight / 2, 10),
        setTop = function (elem) {
            $(elem).find(".wrapper").css({
                height : parseInt(elem.offsetHeight - 30, 10) + "px",
                width : (elem.offsetWidth - 2) + "px"
            });
            
            $(elem).find("h1").each(function () {
                var that5 = this,
                pn = that5.parentNode.parentNode;

                if (that5.offsetWidth > pn.offsetWidth) {
                    pn.style.width = parseInt(that5.offsetWidth + 10, 10) + "px";
                }
            });
            
            if (!(/MSIE\s[67]/).test(ua)) {
                $(elem).find("img").css({
                    width : "100%"
                });
            }
            
            $(elem).find(".price").each(function () {
                var that = this,
                ih = this.innerHTML.toString();
                
                ih = ih.replace(/(\d+)([\.\,])(\d+)(\/\w+)/, "<div class=\"mainPrice\">$1</div><div class=\"suffix\"><div class=\"dec\">$3</div><div class=\"unit\">$4</div></div>");
                
                that.innerHTML = "";
                $(that).append(ih);
            });
            
            $(elem).find("a").each(function () {
                var url = this;
                $(this).parents(".productPreview").click(function (e) {
                    document.location = url;
                });
            });
            
            elem.style.top = parseInt(parseInt(top + middle, 10) - parseInt(elem.offsetHeight / 2, 10), 10) + "px";
        },
        addShadow = function (elem) {
            $(elem).find(".head, .price").each(function () {
                var that4 = this,
                shadow = that4.cloneNode(true);
                
                $(that4).addClass("shadow");
                
                that4.parentNode.appendChild(shadow);
            });
        }, 
        addCorners = function (elem, prev) {
            var closeAlt,
            tp = elem,
            e = $(elem),
            head = e.find("div.head")[0],
            midWrap;
            
            e.find("div.wrapper").css({
                height : "auto",
                width : "auto"
            });
            
            e.each(function () {
                this.style.width = parseInt(this.offsetWidth + 10, 10) + "px";
            });
            
            e.addClass("notCss3");
            
            e.wrapInner("<div class=\"riBo\"><div class=\"leBo\"><div class=\"midWrap\"></div></div></div>");
            e.prepend("<div class=\"popTop\"><div class=\"leCo\"></div><div class=\"riCo\"></div><div class=\"midFil\"></div></div>");
            e.append("<div class=\"popBottom\"><div class=\"leCo\"></div><div class=\"riCo\"></div><div class=\"midFil\"></div></div>");
            
            if (elem.offsetWidth < parseInt(head.offsetWidth + 5, 10)) {
                elem.style.width = parseInt(head.offsetWidth + 5, 10) + "px";
            }
            
            if (prev) {
                elem.style.left = parseInt(elem.offsetLeft, 10) + "px";
            }
            
            if ((/MSIE\s[7]/).test(ua)) {
                 $(elem).find("img").css({
                    width : "100%"
                });
            }
            
            midWrap = e.find("div.midWrap")[0];
            midWrap.style.height = parseInt(midWrap.offsetHeight - 25, 10) + "px";
        };
        
        if ((/browseNext/).test(that.className)) {
            $("div.productPreview.next").each(function () {
                var that2 = this,
                sto = null;
                
                setTop(that2);
                
                that2.style.left = parseInt((left - (that2.offsetWidth / 2)) + that.offsetWidth, 10) + "px";
                
                if (!styleIsSupported("box-shadow") || !styleIsSupported("border-radius")) {
                    addCorners(that2);
                }
                addShadow(that2);
                
                $(that2).css({
                    display : "none"
                });
            }).toggleFade(that);
            
        } else if ((/browsePrev/).test(that.className)) {
            $("div.productPreview.previous").each(function () {
                var that2 = this;
                setTop(that2);
                that2.style.left = parseInt(left - (that2.offsetWidth / 2), 10) + "px";
                
                if (!styleIsSupported("box-shadow") || !styleIsSupported("border-radius")) {
                    addCorners(that2, "prev");
                }
                
                addShadow(that2);
                
                $(that2).css({
                    display : "none"
                });
                
            }).toggleFade(that);
        } 
        
        
        $("div.productPreview *").addClass("isPreview");
    });
    
    function addQVfake () {
        var htmlStr = "",
        hasCss3 = function () {
            if (!styleIsSupported("border-radius") || !styleIsSupported("box-shadow")) {
                return false;
            } else {
                return true;
            }
        },
        maxWidth = 0,
        ipm,
        nlsp,
        spop;
        
        
        // top - start
        htmlStr = "<div class=\"liveSearchPopin inlinePopup newLiveSearchPopin\" style=\"display: block;\">";
        //htmlStr += "<div class=\"ipTop\"><img src=\"/image/icon.close.png\" class=\"ipClose\" alt=\"Stäng\"/></div>"; // org top 
        //htmlStr += "";
        
        // top - end
        
        // mid - start
       
        htmlStr += "<div class=\"ipMid\">";
        htmlStr += "<div id=\"QvExSearchCtl1_results\" class=\"ipMidPadding QwwJs_GlobalSearch-SearchResults\" style=\"\"><span style=\"cursor: pointer; float: right;\" onclick='document.getElementById(\"ctl00_LeftMenuContentPH_LeftProductMenu_TBSearchTextBox\").CloseSearch(true);' class=\"QwwJs_GlobalSearch-CloseSearchIcon\">[X]</span><div class=\"Byggmax-SearchResult-Category\">  <a href=\"http://www.byggmax.com/se-sv/Prod/Skivmaterial/Default.aspx\">Skivmaterial  </a> /  <a href=\"http://www.byggmax.com/se-sv/Prod/Skivmaterial/Trabaserade-Skivor/Default.aspx\"><span class=\"QwwJs_GlobalSearch-Searchword\">Trä</span>baserade skivor  </a></div><div class=\"Byggmax-SearchResult-DetailSection\"><div class=\"Byggmax-SearchResult-ProductRow even\">  <a href=\"http://www.byggmax.com/se-sv/Prod/PID-1001.aspx\">    <span class=\"Byggmax-SearchResult-Name\">Board    </span>    <span class=\"Byggmax-SearchResult-Description\">1001 - 3,2x1220x2440mm    </span> : <span class=\"purchasePrice\">52,95 /st </span>  </a></div><div class=\"Byggmax-SearchResult-ProductRow\">  <a href=\"http://www.byggmax.com/se-sv/Prod/PID-1002.aspx\">    <span class=\"Byggmax-SearchResult-Name\">Asfaltsboard    </span>    <span class=\"Byggmax-SearchResult-Description\">1002 - 12x1200x2740mm    </span> : <span class=\"purchasePrice\">105,00 /st </span>  </a></div><div class=\"Byggmax-SearchResult-ProductRow even\">  <a href=\"http://www.byggmax.com/se-sv/Prod/PID-1004.aspx\">    <span class=\"Byggmax-SearchResult-Name\">Formplywood    </span>    <span class=\"Byggmax-SearchResult-Description\">1004 - 12x1200x2500mm    </span> : <span class=\"purchasePrice\">389,00 /st </span><span> 130,00 /m2 </span>  </a></div><div class=\"Byggmax-SearchResult-ProductRow\">  <a href=\"http://www.byggmax.com/se-sv/Prod/PID-1005.aspx\">    <span class=\"Byggmax-SearchResult-Name\">Plywood P30    </span>    <span class=\"Byggmax-SearchResult-Description\">1005 - 12x1200x2440mm    </span> : <span class=\"purchasePrice\">189,00 /st </span>  </a></div><div class=\"Byggmax-SearchResult-ProductRow even\">  <a href=\"http://www.byggmax.com/se-sv/Prod/PID-1007.aspx\">    <span class=\"Byggmax-SearchResult-Name\">Board    </span>    <span class=\"Byggmax-SearchResult-Description\">1007 - Oljehärdad, 3,2x1220x2440mm    </span> : <span class=\"purchasePrice\">98,95 /st </span>  </a></div><div class=\"Byggmax-SearchResult-ProductRow\">  <a href=\"http://www.byggmax.com/se-sv/Prod/PID-1009.aspx\">    <span class=\"Byggmax-SearchResult-Name\">Osb skiva    </span>    <span class=\"Byggmax-SearchResult-Description\">1009 - 11x2440x1197mm    </span> : <span class=\"purchasePrice\">125,00 /st </span>  </a></div><div class=\"Byggmax-SearchResult-ProductRow even\">  <a href=\"http://www.byggmax.com/se-sv/Prod/PID-1012.aspx\">    <span class=\"Byggmax-SearchResult-Name\">Spånskiva    </span>    <span class=\"Byggmax-SearchResult-Description\">1012 - 12x1200x2500mm    </span> : <span class=\"purchasePrice\">94,95 /st </span>  </a></div><div class=\"Byggmax-SearchResult-ProductRow\">  <a href=\"http://www.byggmax.com/se-sv/Prod/PID-1022.aspx\">    <span class=\"Byggmax-SearchResult-Name\">Golvspånskiva    </span>    <span class=\"Byggmax-SearchResult-Description\">1022 - 22x600x2400mm    </span> : <span class=\"purchasePrice\">108,00 /st </span>  </a></div><div class=\"Byggmax-SearchResult-ProductRow even\">  <a href=\"http://www.byggmax.com/se-sv/Prod/PID-10080.aspx\">    <span class=\"Byggmax-SearchResult-Name\">MDF    </span>    <span class=\"Byggmax-SearchResult-Description\">10080 - 16x2440x1097mm    </span> : <span class=\"purchasePrice\">229,00 /st </span>  </a></div></div><div class=\"Byggmax-SearchResult-Category\">  <a href=\"http://www.byggmax.com/se-sv/Prod/Tra/Default.aspx\"><span class=\"QwwJs_GlobalSearch-Searchword\">Trä</span>  </a> /  <a href=\"http://www.byggmax.com/se-sv/Prod/Tra/Inomhuspanel/Default.aspx\">Inomhuspanel  </a></div><div class=\"Byggmax-SearchResult-DetailSection\"><div class=\"Byggmax-SearchResult-ProductRow even\">  <a href=\"http://www.byggmax.com/se-sv/Prod/PID-1024.aspx\">    <span class=\"Byggmax-SearchResult-Name\">Väggpanel v-spont    </span>    <span class=\"Byggmax-SearchResult-Description\">1024 - MDF obehandlad, 6x620x2420mm    </span> : <span class=\"purchasePrice\">119,95 /st </span><span> 79,95 /m2 </span>  </a></div><div class=\"Byggmax-SearchResult-ProductRow\">  <a href=\"http://www.byggmax.com/se-sv/Prod/PID-1025.aspx\">    <span class=\"Byggmax-SearchResult-Name\">Väggpanel v-spont    </span>    <span class=\"Byggmax-SearchResult-Description\">1025 - Äggvit, 6x620x2420    </span> : <span class=\"purchasePrice\">193,55 /st </span><span> 129,00 /m2 </span>  </a></div></div><div class=\"Byggmax-SearchResult-Category\">  <a href=\"http://www.byggmax.com/se-sv/Prod/Markprodukter/Default.aspx\">Markprodukter  </a> /  <a href=\"http://www.byggmax.com/se-sv/Prod/Markprodukter/Marksten-Plint/Default.aspx\">Marksten & Plint  </a></div><div class=\"Byggmax-SearchResult-DetailSection\"><div class=\"Byggmax-SearchResult-ProductRow even\">  <a href=\"http://www.byggmax.com/se-sv/Prod/PID-02195.aspx\">    <span class=\"Byggmax-SearchResult-Name\"><span class=\"QwwJs_GlobalSearch-Searchword\">Trä</span>dgårdssten grå struktur    </span>    <span class=\"Byggmax-SearchResult-Description\">02195 - Max, 210x140x40mm    </span> : <span class=\"purchasePrice\">2,64 /st </span><span> 89,95 /m2 </span>  </a></div><div class=\"Byggmax-SearchResult-ProductRow\">  <a href=\"http://www.byggmax.com/se-sv/Prod/PID-02197.aspx\">    <span class=\"Byggmax-SearchResult-Name\"><span class=\"QwwJs_GlobalSearch-Searchword\">Trä</span>dgårdssten terra struktur    </span>    <span class=\"Byggmax-SearchResult-Description\">02197 - Max, 210x140x40mm    </span> : <span class=\"purchasePrice\">4,38 /st </span><span> 149,00 /m2 </span>  </a></div></div><div class=\"Byggmax-SearchResult-Category\">  <a href=\"http://www.byggmax.com/se-sv/Prod/Golv/Default.aspx\">Golv  </a> /  <a href=\"http://www.byggmax.com/se-sv/Prod/Golv/Golv-Tillbehör/Default.aspx\">Tillbehör  </a></div><div class=\"Byggmax-SearchResult-DetailSection\"><div class=\"Byggmax-SearchResult-ProductRow even\">  <a href=\"http://www.byggmax.com/se-sv/Prod/PID-13015.aspx\">    <span class=\"Byggmax-SearchResult-Name\"><span class=\"QwwJs_GlobalSearch-Searchword\">Trä</span>kil    </span>    <span class=\"Byggmax-SearchResult-Description\">13015 - Till laminagolv    </span> : <span class=\"purchasePrice\">49,95 /st </span>  </a></div><div class=\"Byggmax-SearchResult-ProductRow\">  <a href=\"http://www.byggmax.com/se-sv/Prod/PID-13052.aspx\">    <span class=\"Byggmax-SearchResult-Name\">Golvsåpa    </span>    <span class=\"Byggmax-SearchResult-Description\">13052 - För <span class=\"QwwJs_GlobalSearch-Searchword\">trä</span>golv, 1L, UTGÅENDE    </span> : <span class=\"purchasePrice\">99,95 /st </span>  </a></div><div class=\"Byggmax-SearchResult-ProductRow even\">  <a href=\"http://www.byggmax.com/se-sv/Prod/PID-13054.aspx\">    <span class=\"Byggmax-SearchResult-Name\">Golvtvätt    </span>    <span class=\"Byggmax-SearchResult-Description\">13054 - För <span class=\"QwwJs_GlobalSearch-Searchword\">trä</span>golv, 1L, UTGÅENDE    </span> : <span class=\"purchasePrice\">139,00 /st </span>  </a></div><div class=\"Byggmax-SearchResult-ProductRow\">  <a href=\"http://www.byggmax.com/se-sv/Prod/PID-13058.aspx\">    <span class=\"Byggmax-SearchResult-Name\">Golvpasta    </span>    <span class=\"Byggmax-SearchResult-Description\">13058 - För <span class=\"QwwJs_GlobalSearch-Searchword\">trä</span>golv, 0,4L, UTGÅENDE    </span> : <span class=\"purchasePrice\">189,00 /st </span>  </a></div><div class=\"Byggmax-SearchResult-ProductRow even\">  <a href=\"http://www.byggmax.com/se-sv/Prod/PID-13062.aspx\">    <span class=\"Byggmax-SearchResult-Name\">Olja    </span>    <span class=\"Byggmax-SearchResult-Description\">13062 - För <span class=\"QwwJs_GlobalSearch-Searchword\">trä</span>golv, 1L    </span> : <span class=\"purchasePrice\">169,00 /st </span>  </a></div><div class=\"Byggmax-SearchResult-ProductRow\">  <a href=\"http://www.byggmax.com/se-sv/Prod/PID-13066.aspx\">    <span class=\"Byggmax-SearchResult-Name\">Olja    </span>    <span class=\"Byggmax-SearchResult-Description\">13066 - För <span class=\"QwwJs_GlobalSearch-Searchword\">trä</span>golv, 2,5L (Faxe), UTGÅENDE    </span> : <span class=\"purchasePrice\">339,00 /st </span>  </a></div><div class=\"Byggmax-SearchResult-ProductRow even\">  <a href=\"http://www.byggmax.com/se-sv/Prod/PID-18130.aspx\">    <span class=\"Byggmax-SearchResult-Name\">Plastiskt <span class=\"QwwJs_GlobalSearch-Searchword\">trä</span>    </span>    <span class=\"Byggmax-SearchResult-Description\">18130 - Natur, 375 gr., UTGÅENDE    </span> : <span class=\"purchasePrice\">37,95 /st </span><span> 101,20 /kg </span>  </a></div></div><div class=\"Byggmax-SearchResult-Category\">  <a href=\"http://www.byggmax.com/se-sv/Prod/Golv/Default.aspx\">Golv  </a> /  <a href=\"http://www.byggmax.com/se-sv/Prod/Golv/Sockel-Fanerad/Default.aspx\">Sockel-Fanerad  </a></div><div class=\"Byggmax-SearchResult-DetailSection\"><div class=\"Byggmax-SearchResult-ProductRow even\">  <a href=\"http://www.byggmax.com/se-sv/Prod/PID-13340.aspx\">    <span class=\"Byggmax-SearchResult-Name\">Tali <span class=\"QwwJs_GlobalSearch-Searchword\">trä</span>fanér    </span>    <span class=\"Byggmax-SearchResult-Description\">13340 - Sockel, 22x2200mm, UTGÅENDE    </span> : <span class=\"purchasePrice\">69,95 /st </span>  </a></div><div class=\"Byggmax-SearchResult-ProductRow\">  <a href=\"http://www.byggmax.com/se-sv/Prod/PID-13350.aspx\">    <span class=\"Byggmax-SearchResult-Name\">Ek <span class=\"QwwJs_GlobalSearch-Searchword\">trä</span>fanér    </span>    <span class=\"Byggmax-SearchResult-Description\">13350 - Sockel, 22x26x2200mm    </span> : <span class=\"purchasePrice\">69,95 /st </span>  </a></div><div class=\"Byggmax-SearchResult-ProductRow even\">  <a href=\"http://www.byggmax.com/se-sv/Prod/PID-13355.aspx\">    <span class=\"Byggmax-SearchResult-Name\">Ek <span class=\"QwwJs_GlobalSearch-Searchword\">trä</span>fanér    </span>    <span class=\"Byggmax-SearchResult-Description\">13355 - Sockel, 10x58x2200mm    </span> : <span class=\"purchasePrice\">79,95 /st </span>  </a></div><div class=\"Byggmax-SearchResult-ProductRow\">  <a href=\"http://www.byggmax.com/se-sv/Prod/PID-13360.aspx\">    <span class=\"Byggmax-SearchResult-Name\">Ek <span class=\"QwwJs_GlobalSearch-Searchword\">trä</span>fanér    </span>    <span class=\"Byggmax-SearchResult-Description\">13360 - Sockel, 19x78x2200mm    </span> : <span class=\"purchasePrice\">89,95 /st </span>  </a></div><div class=\"Byggmax-SearchResult-ProductRow even\">  <a href=\"http://www.byggmax.com/se-sv/Prod/PID-13365.aspx\">    <span class=\"Byggmax-SearchResult-Name\">Ek <span class=\"QwwJs_GlobalSearch-Searchword\">trä</span>fanér    </span>    <span class=\"Byggmax-SearchResult-Description\">13365 - Sockel, 17x60x2200mm    </span> : <span class=\"purchasePrice\">79,95 /st </span>  </a></div><div class=\"Byggmax-SearchResult-ProductRow\">  <a href=\"http://www.byggmax.com/se-sv/Prod/PID-13370.aspx\">    <span class=\"Byggmax-SearchResult-Name\">Ask <span class=\"QwwJs_GlobalSearch-Searchword\">trä</span>fanér    </span>    <span class=\"Byggmax-SearchResult-Description\">13370 - Sockel, 19x78x2200mm    </span> : <span class=\"purchasePrice\">89,95 /st </span>  </a></div><div class=\"Byggmax-SearchResult-ProductRow even\">  <a href=\"http://www.byggmax.com/se-sv/Prod/PID-13375.aspx\">    <span class=\"Byggmax-SearchResult-Name\">Ask <span class=\"QwwJs_GlobalSearch-Searchword\">trä</span>fanér    </span>    <span class=\"Byggmax-SearchResult-Description\">13375 - Sockel, 20x58x2200mm    </span> : <span class=\"purchasePrice\">79,95 /st </span>  </a></div></div><div class=\"Byggmax-SearchResult-Category\">  <a href=\"http://www.byggmax.com/se-sv/Prod/Golv/Default.aspx\">Golv  </a> /  <a href=\"http://www.byggmax.com/se-sv/Prod/Golv/Tragolv-Parkett/Default.aspx\"><span class=\"QwwJs_GlobalSearch-Searchword\">Trä</span>golv-Parkett  </a></div><div class=\"Byggmax-SearchResult-DetailSection\"><div class=\"Byggmax-SearchResult-ProductRow even\">  <a href=\"http://www.byggmax.com/se-sv/Prod/PID-13402.aspx\">    <span class=\"Byggmax-SearchResult-Name\">Ek 3-stav, kort    </span>    <span class=\"Byggmax-SearchResult-Description\">13402 - Parkettgolv, 14mm, 1,59m2/pkt, UTGÅENDE    </span> : <span class=\"purchasePrice\">284,18 /st </span><span> 179,00 /m2 </span>  </a></div><div class=\"Byggmax-SearchResult-ProductRow\">  <a href=\"http://www.byggmax.com/se-sv/Prod/PID-13405.aspx\">    <span class=\"Byggmax-SearchResult-Name\">Ek lackad 3-stav    </span>    <span class=\"Byggmax-SearchResult-Description\">13405 - Parkettgolv 15mm, click, 3,18m2/pkt    </span> : <span class=\"purchasePrice\">728,22 /st </span><span> 229,00 /m2 </span>  </a></div><div class=\"Byggmax-SearchResult-ProductRow even\">  <a href=\"http://www.byggmax.com/se-sv/Prod/PID-13406.aspx\">    <span class=\"Byggmax-SearchResult-Name\">Ek oljad 3-stav    </span>    <span class=\"Byggmax-SearchResult-Description\">13406 - Parkettgolv 15mm, click, 3,18m2/pkt    </span> : <span class=\"purchasePrice\">791,82 /st </span><span> 249,00 /m2 </span>  </a></div><div class=\"Byggmax-SearchResult-ProductRow\">  <a href=\"http://www.byggmax.com/se-sv/Prod/PID-13407.aspx\">    <span class=\"Byggmax-SearchResult-Name\">Ek lackad 4-stav    </span>    <span class=\"Byggmax-SearchResult-Description\">13407 - Parkettgolv 15mm, click, 3,18m2/pkt    </span> : <span class=\"purchasePrice\">632,81 /st </span><span> 199,00 /m2 </span>  </a></div><div class=\"Byggmax-SearchResult-ProductRow even\">  <a href=\"http://www.byggmax.com/se-sv/Prod/PID-13408.aspx\">    <span class=\"Byggmax-SearchResult-Name\">Ek plank    </span>    <span class=\"Byggmax-SearchResult-Description\">13408 - Parkettgolv, 14mm, click, 2,77m2/pkt    </span> : <span class=\"purchasePrice\">966,73 /st </span><span> 349,00 /m2 </span>  </a></div><div class=\"Byggmax-SearchResult-ProductRow\">  <a href=\"http://www.byggmax.com/se-sv/Prod/PID-13409.aspx\">    <span class=\"Byggmax-SearchResult-Name\">Ek select    </span>    <span class=\"Byggmax-SearchResult-Description\">13409 - Parkettgolv 15mm, click, 3,18m2/pkt    </span> : <span class=\"purchasePrice\">950,02 /st </span><span> 299,00 /m2 </span>  </a></div><div class=\"Byggmax-SearchResult-ProductRow even\">  <a href=\"http://www.byggmax.com/se-sv/Prod/PID-13410.aspx\">    <span class=\"Byggmax-SearchResult-Name\">Ek fasad oljad    </span>    <span class=\"Byggmax-SearchResult-Description\">13410 - Parkettgolv 14mm, click, 2,77m2/pkt    </span> : <span class=\"purchasePrice\">1 243,73 /st </span><span> 449,00 /m2 </span>  </a></div><div class=\"Byggmax-SearchResult-ProductRow\">  <a href=\"http://www.byggmax.com/se-sv/Prod/PID-13412.aspx\">    <span class=\"Byggmax-SearchResult-Name\">Ek borstad    </span>    <span class=\"Byggmax-SearchResult-Description\">13412 - Parkettgolv 14,5mm, click, 3,16m2/pkt, UTGÅENDE    </span> : <span class=\"purchasePrice\">913,24 /st </span><span> 289,00 /m2 </span>  </a></div><div class=\"Byggmax-SearchResult-ProductRow even\">  <a href=\"http://www.byggmax.com/se-sv/Prod/PID-13413.aspx\">    <span class=\"Byggmax-SearchResult-Name\">Ek fasad 1-stav    </span>    <span class=\"Byggmax-SearchResult-Description\">13413 - Parkettgolv14mm, click, smal, 2,00m2/pkt    </span> : <span class=\"purchasePrice\">858,00 /st </span><span> 429,00 /m2 </span>  </a></div><div class=\"Byggmax-SearchResult-ProductRow\">  <a href=\"http://www.byggmax.com/se-sv/Prod/PID-13418.aspx\">    <span class=\"Byggmax-SearchResult-Name\">Ek plank    </span>    <span class=\"Byggmax-SearchResult-Description\">13418 - Parkettgolv, 14mm, click, 1,37m2/pkt, UTGÅENDE    </span> : <span class=\"purchasePrice\">382,23 /st </span><span> 279,00 /m2 </span>  </a></div><div class=\"Byggmax-SearchResult-ProductRow even\">  <a href=\"http://www.byggmax.com/se-sv/Prod/PID-13422.aspx\">    <span class=\"Byggmax-SearchResult-Name\">Valnöt lackad 3-stav    </span>    <span class=\"Byggmax-SearchResult-Description\">13422 - Parkettgolv 15mm, click, 3,18m2/pkt    </span> : <span class=\"purchasePrice\">1 427,82 /st </span><span> 449,00 /m2 </span>  </a></div><div class=\"Byggmax-SearchResult-ProductRow\">  <a href=\"http://www.byggmax.com/se-sv/Prod/PID-13423.aspx\">    <span class=\"Byggmax-SearchResult-Name\">Ek 3-stav, kort    </span>    <span class=\"Byggmax-SearchResult-Description\">13423 - Parkettgolv 14mm, click, 1,58m2/pkt    </span> : <span class=\"purchasePrice\">284,18 /st </span><span> 179,00 /m2 </span>  </a></div><div class=\"Byggmax-SearchResult-ProductRow even\">  <a href=\"http://www.byggmax.com/se-sv/Prod/PID-13424.aspx\">    <span class=\"Byggmax-SearchResult-Name\">Ask vitlackad 3-stav    </span>    <span class=\"Byggmax-SearchResult-Description\">13424 - Parkettgolv 15mm, click, 3,18m2/pkt    </span> : <span class=\"purchasePrice\">823,62 /st </span><span> 259,00 /m2 </span>  </a></div><div class=\"Byggmax-SearchResult-ProductRow\">  <a href=\"http://www.byggmax.com/se-sv/Prod/PID-13425.aspx\">    <span class=\"Byggmax-SearchResult-Name\">Björk lackad 3-stav    </span>    <span class=\"Byggmax-SearchResult-Description\">13425 - Parkettgolv 15mm, click, 3,18m2/pkt    </span> : <span class=\"purchasePrice\">601,02 /st </span><span> 189,00 /m2 </span>  </a></div><div class=\"Byggmax-SearchResult-ProductRow even\">  <a href=\"http://www.byggmax.com/se-sv/Prod/PID-13426.aspx\">    <span class=\"Byggmax-SearchResult-Name\">Björk lackad 4-stav    </span>    <span class=\"Byggmax-SearchResult-Description\">13426 - Parkettgolv 15mm, click, 3,18m2/pkt, UTGÅENDE    </span> : <span class=\"purchasePrice\">505,62 /st </span><span> 159,00 /m2 </span>  </a></div><div class=\"Byggmax-SearchResult-ProductRow\">  <a href=\"http://www.byggmax.com/se-sv/Prod/PID-13435.aspx\">    <span class=\"Byggmax-SearchResult-Name\">Ask lackad 3-stav    </span>    <span class=\"Byggmax-SearchResult-Description\">13435 - Parkettgolv 15mm, click, 3,18m2/pkt    </span> : <span class=\"purchasePrice\">696,42 /st </span><span> 219,00 /m2 </span>  </a></div><div class=\"Byggmax-SearchResult-ProductRow even\">  <a href=\"http://www.byggmax.com/se-sv/Prod/PID-13437.aspx\">    <span class=\"Byggmax-SearchResult-Name\">Ask lackad 4-stav    </span>    <span class=\"Byggmax-SearchResult-Description\">13437 - Parkettgolv 15mm, click, 3,18m2/pkt    </span> : <span class=\"purchasePrice\">632,81 /st </span><span> 199,00 /m2 </span>  </a></div><div class=\"Byggmax-SearchResult-ProductRow\">  <a href=\"http://www.byggmax.com/se-sv/Prod/PID-13438.aspx\">    <span class=\"Byggmax-SearchResult-Name\">Ask plank lackad    </span>    <span class=\"Byggmax-SearchResult-Description\">13438 - Parkettgolv 14mm, click, 2,77m2/pkt, UTGÅENDE    </span> : <span class=\"purchasePrice\">1 160,63 /st </span><span> 419,00 /m2 </span>  </a></div><div class=\"Byggmax-SearchResult-ProductRow even\">  <a href=\"http://www.byggmax.com/se-sv/Prod/PID-13460.aspx\">    <span class=\"Byggmax-SearchResult-Name\">Jatobe lackad    </span>    <span class=\"Byggmax-SearchResult-Description\">13460 - Parkettgolv 15mm, click, 3,18m2/pkt, UTGÅENDE    </span> : <span class=\"purchasePrice\">1 078,02 /st </span><span> 339,00 /m2 </span>  </a></div><div class=\"Byggmax-SearchResult-ProductRow\">  <a href=\"http://www.byggmax.com/se-sv/Prod/PID-13492.aspx\">    <span class=\"Byggmax-SearchResult-Name\">Ask lackad 3-stav    </span>    <span class=\"Byggmax-SearchResult-Description\">13492 - Parkettgolv 10mm, click, 4,09 m2/pkt    </span> : <span class=\"purchasePrice\">732,11 /st </span><span> 179,00 /m2 </span>  </a></div><div class=\"Byggmax-SearchResult-ProductRow even\">  <a href=\"http://www.byggmax.com/se-sv/Prod/PID-13496.aspx\">    <span class=\"Byggmax-SearchResult-Name\">Ek plank 1-stav    </span>    <span class=\"Byggmax-SearchResult-Description\">13496 - Parkettgolv 14mm, click, 180cm bredd 2,77m2/pkt, UTGÅENDE    </span> : <span class=\"purchasePrice\">966,73 /st </span><span> 349,00 /m2 </span>  </a></div></div><div class=\"Byggmax-SearchResult-Category\">  <a href=\"http://www.byggmax.com/se-sv/Prod/Lim-Fog/Default.aspx\">Lim & Fog  </a> /  <a href=\"http://www.byggmax.com/se-sv/Prod/Lim-Fog/Lim/Default.aspx\">Lim  </a></div><div class=\"Byggmax-SearchResult-DetailSection\"><div class=\"Byggmax-SearchResult-ProductRow even\">  <a href=\"http://www.byggmax.com/se-sv/Prod/PID-18002.aspx\">    <span class=\"Byggmax-SearchResult-Name\"><span class=\"QwwJs_GlobalSearch-Searchword\">Trä</span>lim    </span>    <span class=\"Byggmax-SearchResult-Description\">18002 - Inne, 750ml    </span> : <span class=\"purchasePrice\">34,95 /st </span><span> 46,60 /l </span>  </a></div><div class=\"Byggmax-SearchResult-ProductRow\">  <a href=\"http://www.byggmax.com/se-sv/Prod/PID-18004.aspx\">    <span class=\"Byggmax-SearchResult-Name\"><span class=\"QwwJs_GlobalSearch-Searchword\">Trä</span>lim    </span>    <span class=\"Byggmax-SearchResult-Description\">18004 - Vinter, C10, 750ml    </span> : <span class=\"purchasePrice\">44,95 /st </span><span> 59,93 /l </span>  </a></div><div class=\"Byggmax-SearchResult-ProductRow even\">  <a href=\"http://www.byggmax.com/se-sv/Prod/PID-18006.aspx\">    <span class=\"Byggmax-SearchResult-Name\"><span class=\"QwwJs_GlobalSearch-Searchword\">Trä</span>lim    </span>    <span class=\"Byggmax-SearchResult-Description\">18006 - Ute, B3, 750ml    </span> : <span class=\"purchasePrice\">54,95 /st </span><span> 73,27 /l </span>  </a></div><div class=\"Byggmax-SearchResult-ProductRow\">  <a href=\"http://www.byggmax.com/se-sv/Prod/PID-18008.aspx\">    <span class=\"Byggmax-SearchResult-Name\"><span class=\"QwwJs_GlobalSearch-Searchword\">Trä</span>lim    </span>    <span class=\"Byggmax-SearchResult-Description\">18008 - Laminat, 750ml    </span> : <span class=\"purchasePrice\">34,95 /st </span><span> 46,60 /l </span>  </a></div></div><div class=\"Byggmax-SearchResult-Category\">  <a href=\"http://www.byggmax.com/se-sv/Prod/Malning/Default.aspx\">Målning  </a> /  <a href=\"http://www.byggmax.com/se-sv/Prod/Malning/Kemteknisk-Traolja/Default.aspx\">Kemteknisk & <span class=\"QwwJs_GlobalSearch-Searchword\">Trä</span>olja  </a></div><div class=\"Byggmax-SearchResult-DetailSection\"><div class=\"Byggmax-SearchResult-ProductRow even\">  <a href=\"http://www.byggmax.com/se-sv/Prod/PID-18402.aspx\">    <span class=\"Byggmax-SearchResult-Name\">Lacknafta    </span>    <span class=\"Byggmax-SearchResult-Description\">18402 - 1L    </span> : <span class=\"purchasePrice\">27,95 /st </span>  </a></div><div class=\"Byggmax-SearchResult-ProductRow\">  <a href=\"http://www.byggmax.com/se-sv/Prod/PID-18404.aspx\">    <span class=\"Byggmax-SearchResult-Name\">Lacknafta    </span>    <span class=\"Byggmax-SearchResult-Description\">18404 - 5L    </span> : <span class=\"purchasePrice\">109,00 /st </span><span> 21,80 /l </span>  </a></div><div class=\"Byggmax-SearchResult-ProductRow even\">  <a href=\"http://www.byggmax.com/se-sv/Prod/PID-18412.aspx\">    <span class=\"Byggmax-SearchResult-Name\">Fasadtvätt    </span>    <span class=\"Byggmax-SearchResult-Description\">18412 - 1L    </span> : <span class=\"purchasePrice\">39,95 /st </span>  </a></div><div class=\"Byggmax-SearchResult-ProductRow\">  <a href=\"http://www.byggmax.com/se-sv/Prod/PID-18414.aspx\">    <span class=\"Byggmax-SearchResult-Name\">Fasadtvätt    </span>    <span class=\"Byggmax-SearchResult-Description\">18414 - 5L    </span> : <span class=\"purchasePrice\">139,00 /st </span><span> 27,80 /l </span>  </a></div><div class=\"Byggmax-SearchResult-ProductRow even\">  <a href=\"http://www.byggmax.com/se-sv/Prod/PID-18422.aspx\">    <span class=\"Byggmax-SearchResult-Name\">Målartvätt    </span>    <span class=\"Byggmax-SearchResult-Description\">18422 - 1L    </span> : <span class=\"purchasePrice\">29,95 /st </span>  </a></div><div class=\"Byggmax-SearchResult-ProductRow\">  <a href=\"http://www.byggmax.com/se-sv/Prod/PID-18452.aspx\">    <span class=\"Byggmax-SearchResult-Name\"><span class=\"QwwJs_GlobalSearch-Searchword\">Trä</span>rent    </span>    <span class=\"Byggmax-SearchResult-Description\">18452 - 5L    </span> : <span class=\"purchasePrice\">99,95 /st </span><span> 19,99 /l </span>  </a></div><div class=\"Byggmax-SearchResult-ProductRow even\">  <a href=\"http://www.byggmax.com/se-sv/Prod/PID-18454.aspx\">    <span class=\"Byggmax-SearchResult-Name\">Takpannerengöring    </span>    <span class=\"Byggmax-SearchResult-Description\">18454 - 5L    </span> : <span class=\"purchasePrice\">349,00 /st </span><span> 69,80 /l </span>  </a></div><div class=\"Byggmax-SearchResult-ProductRow\">  <a href=\"http://www.byggmax.com/se-sv/Prod/PID-18462.aspx\">    <span class=\"Byggmax-SearchResult-Name\">Combiclean    </span>    <span class=\"Byggmax-SearchResult-Description\">18462 - Klorfri fasadtvätt, 1L    </span> : <span class=\"purchasePrice\">64,95 /st </span><span> 64,95 /l </span>  </a></div><div class=\"Byggmax-SearchResult-ProductRow even\">  <a href=\"http://www.byggmax.com/se-sv/Prod/PID-18464.aspx\">    <span class=\"Byggmax-SearchResult-Name\">Combiclean    </span>    <span class=\"Byggmax-SearchResult-Description\">18464 - Klorfri fasadtvätt, 5L    </span> : <span class=\"purchasePrice\">299,00 /st </span><span> 59,80 /l </span>  </a></div><div class=\"Byggmax-SearchResult-ProductRow\">  <a href=\"http://www.byggmax.com/se-sv/Prod/PID-19862.aspx\">    <span class=\"Byggmax-SearchResult-Name\"><span class=\"QwwJs_GlobalSearch-Searchword\">Trä</span>olja 3l, 35%    </span>    <span class=\"Byggmax-SearchResult-Description\">19862 - Utefärg    </span> : <span class=\"purchasePrice\">69,95 /st </span><span> 23,32 /l </span>  </a></div><div class=\"Byggmax-SearchResult-ProductRow even\">  <a href=\"http://www.byggmax.com/se-sv/Prod/PID-19864.aspx\">    <span class=\"Byggmax-SearchResult-Name\"><span class=\"QwwJs_GlobalSearch-Searchword\">Trä</span>olja 10 l 35%    </span>    <span class=\"Byggmax-SearchResult-Description\">19864 - Utefärg    </span> : <span class=\"purchasePrice\">199,00 /st </span><span> 19,90 /l </span>  </a></div><div class=\"Byggmax-SearchResult-ProductRow\">  <a href=\"http://www.byggmax.com/se-sv/Prod/PID-19866.aspx\">    <span class=\"Byggmax-SearchResult-Name\"><span class=\"QwwJs_GlobalSearch-Searchword\">Trä</span>olja    </span>    <span class=\"Byggmax-SearchResult-Description\">19866 - Lmf 3l    </span> : <span class=\"purchasePrice\">89,95 /st </span><span> 29,99 /l </span>  </a></div><div class=\"Byggmax-SearchResult-ProductRow even\">  <a href=\"http://www.byggmax.com/se-sv/Prod/PID-19867.aspx\">    <span class=\"Byggmax-SearchResult-Name\"><span class=\"QwwJs_GlobalSearch-Searchword\">Trä</span>olja brun 3l    </span>    <span class=\"Byggmax-SearchResult-Description\">19867 - Utefärg vattenburen    </span> : <span class=\"purchasePrice\">74,95 /st </span><span> 24,98 /l </span>  </a></div><div class=\"Byggmax-SearchResult-ProductRow\">  <a href=\"http://www.byggmax.com/se-sv/Prod/PID-19872.aspx\">    <span class=\"Byggmax-SearchResult-Name\">Slipersolja Svartbrun 5L    </span>    <span class=\"Byggmax-SearchResult-Description\">19872 - Utefärg    </span> : <span class=\"purchasePrice\">199,00 /st </span><span> 39,80 /l </span>  </a></div><div class=\"Byggmax-SearchResult-ProductRow even\">  <a href=\"http://www.byggmax.com/se-sv/Prod/PID-19874.aspx\">    <span class=\"Byggmax-SearchResult-Name\">Teakolja 0,5l    </span>    <span class=\"Byggmax-SearchResult-Description\">19874 - Utefärg    </span> : <span class=\"purchasePrice\">59,95 /st </span><span> 119,90 /l </span>  </a></div></div><div class=\"Byggmax-SearchResult-Category\">  <a href=\"http://www.byggmax.com/se-sv/Prod/Malning/Default.aspx\">Målning  </a> /  <a href=\"http://www.byggmax.com/se-sv/Prod/Malning/Farg-Utomhus/Default.aspx\">Färg-Utomhus  </a></div><div class=\"Byggmax-SearchResult-DetailSection\"><div class=\"Byggmax-SearchResult-ProductRow even\">  <a href=\"http://www.byggmax.com/se-sv/Prod/PID-19611.aspx\">    <span class=\"Byggmax-SearchResult-Name\"><span class=\"QwwJs_GlobalSearch-Searchword\">Trä</span>grund vit 1 l    </span>    <span class=\"Byggmax-SearchResult-Description\">19611 - Utefärg    </span> : <span class=\"purchasePrice\">74,95 /st </span>  </a></div><div class=\"Byggmax-SearchResult-ProductRow\">  <a href=\"http://www.byggmax.com/se-sv/Prod/PID-19612.aspx\">    <span class=\"Byggmax-SearchResult-Name\"><span class=\"QwwJs_GlobalSearch-Searchword\">Trä</span>grund, vit, 4l    </span>    <span class=\"Byggmax-SearchResult-Description\">19612 - Utefärg    </span> : <span class=\"purchasePrice\">199,00 /st </span><span> 49,75 /l </span>  </a></div><div class=\"Byggmax-SearchResult-ProductRow even\">  <a href=\"http://www.byggmax.com/se-sv/Prod/PID-19614.aspx\">    <span class=\"Byggmax-SearchResult-Name\"><span class=\"QwwJs_GlobalSearch-Searchword\">Trä</span>grund, vit, 10l    </span>    <span class=\"Byggmax-SearchResult-Description\">19614 - Utefärg    </span> : <span class=\"purchasePrice\">399,00 /st </span><span> 39,90 /l </span>  </a></div></div><a href=\"http://www.qlikview.com\" class=\"poweredbyQVLink\">  <img alt=\"powered by QlikView\" src=\"/image/powered.by.qlikview.png\" class=\"poweredbyQV\"/></a></div>";
        htmlStr += "</div>";
        // mid - end
        
        // bottom - start
        //htmlStr += "<div class=\"ipBottom\"> </div></div>";
        // bottom - end
          
        
        $(".productSearch").append(htmlStr);
        
        if (hasCss3()) {
            $("div.newLiveSearchPopin").addClass("hasCss3").append("<img src=\"/image/icon.close.png\" class=\"ipClose\" alt=\"Stäng\"/>");
            
        } else {
            $("div.newLiveSearchPopin").addClass("notCss3").append("<img src=\"/image/icon.close.png\" class=\"ipClose\" alt=\"Stäng\"/>");
            
            nlsp = $("div.newLiveSearchPopin.notCss3");
            
            ipm = nlsp.find("div.ipMid");
            
            ipm.wrap("<div class=\"riBo\"><div class=\"leBo\"></div></div>");
            
            $(ipm).find("div.Byggmax-SearchResult-ProductRow").each(function () {
                if (maxWidth < this.offsetWidth) {
                    maxWidth = this.offsetWidth;
                }
            });
            
            ipm.css({
                width : maxWidth + "px"
            });
            
            nlsp.prepend("<div class=\"ipdTop\"><div class=\"midFill\"></div><div class=\"leCo\"></div><div class=\"riCo\"></div></div>");
            nlsp.append("<div class=\"ipdBottom\"><div class=\"midFill\"></div><div class=\"leCo\"></div><div class=\"riCo\"></div></div>");
            
            nlsp.find("div.ipdTop, div.ipdBottom").each(function () {
                var pn = this.parentNode;
                
                if(this.offsetWidth < pn.offsetWidth) {
                    this.style.width = pn.offsetWidth + "px";
                }
            });
        }
        
        /*spop = $("div.newLiveSearchPopin");
        
        spop.find("img.ipClose").click(function () {
            spop.hide();
        });*/
    };
    
    //addQVfake();
    
});
/*
$(document).ready(function () {
    
    var aboutPlayer = "<div class=\"m0 byggprojekt previewContainer\">";
    
    aboutPlayer += "<div class=\"colMovie\">";
    
    aboutPlayer += "<input type=\"hidden\" name=\"moviepath\" value=\"http://epi.byggmax.com/Documents/Flash%20filmer%20preview/Byggprojekt/malning10sek.flv\"/>";
    aboutPlayer += "<input type=\"hidden\" name=\"cuepoint\" value=\"0\"/>";
    aboutPlayer += "<input type=\"hidden\" name=\"relmovie\" value=\"mInstructionMovie0\"/>";
    
    aboutPlayer += "<a class=\"colPlayerContainer popinMovieHover screenshot\" id=\"colPlayerContainer0instructionMovie\">";
    aboutPlayer += "<span style=\"width: 166px; height: 94px; position: absolute;\" class=\"op0 flashLinkOvly\"> <!-- --> </span>";
    aboutPlayer += "<img src=\"http://epi.byggmax.com/Global/ByggprojektReportageMontering/Preview%20bild%20166x94/malning_166x94.jpg\" alt=\"\"/>";
    aboutPlayer += "</a>";
    aboutPlayer += "<a href=\"http://www.byggmax.com/se-sv/Byggmax/Byggprojekt/Malning.aspx?cPoint=1226\" class=\"textLink\"> Att måla impregnerat virke.</a>";
        
    aboutPlayer += "</div>";
    
    aboutPlayer += "</div>";
    
    $("div.aboutSection div.body:first").append(aboutPlayer);
});
*/

(function () {
    var $ = jQuery,
        view;

    view = {
        init : function () {
            $('input, select').each(function(index, elem) {
                if (!$(this).attr('autocomplete')) {
                    $(this).attr('autocomplete', 'off');
                }
                //console.log($(this).attr('autocomplete'));
            });
        }
    }

    $(document).ready(function () {
        view.init();
    });

    jQuery.cache.search = function () {
        var that = this,
        i,
        result = [],
        getLength = function () {
            var k,
            count = 0;
            for (k in that) {
                if (parseInt(k, 10) && parseInt(k, 10) > count) {
                    count = parseInt(k, 10);
                }
            }
            
            return count;
        };
        
        that.length = getLength();
        
        alert(that.length);
        
        for (i = 0; i < that.length; i += 1) {
            if (that[i] && that[i].handle && that[i].handle.elem.id && that[i].handle.elem.id.toString() === arguments[0].toString()) {
                result.push(that[i]);
            }
        }
        
        return result;
    };
}());