/// <reference path="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js" />
/// <reference path="jquery-ui-1.8.10.custom.min.js" />
/// <reference path="jquery.scrollTo-min.js" /

function trim(str) {
    str = str.replace(/^\s+/, '');
    for (var i = str.length - 1; i >= 0; i--) {
        if (/\S/.test(str.charAt(i))) {
            str = str.substring(0, i + 1);
            break;
        }
    }
    return str;
}


function submitenter(myfield, e) {
    var keycode;
    if (window.event) keycode = window.event.keyCode;
    else if (e) keycode = e.which;
    else return true;
    if (keycode == 13) {
        myfield.form.submit();
        return false;
    }
    else
        return true;
}

function Anthem_Error(result) {
    if (result.error != 'NORESPONSE')
        alert('Anthem_Error was invoked with the following error message: ' + result.error);
}

function toggleItem(id) {
    jQuery("#" + id).toggle();
}


function productImageChange(imageObj, largeImageId) {
    jQuery("#" + largeImageId).attr("src") = imageObj.src.replace("/medium/", "/large/");
}

function productImageChangeCustom(imageObj, largeImageId, folder) {
    jQuery("#" + largeImageId).attr("src", imageObj.src.replace("/medium/", "/" + folder + "/"));
}

function toggleImages(containerID) {
    containerID = "#" + containerID;
    var images = jQuery(containerID).find('img');
    images.each(function () {
        var image = jQuery(this);
        if (image.attr("id").indexOf('largeImage') != -1 && image.is(":visible")) {
            jQuery(containerID).css({
                'margin-left': '5px',
                'float': 'right'
            });
        }
        else if (image.attr("id").indexOf('largeImage') != -1 && !image.is(":visible")) {
            jQuery(containerID).css({
                'margin-left': '0px',
                'float': 'left'
            });
        }
        image.toggle();
    });
}

function fireSearch(searchObj) {
    
    window.location = "/Pages/Search.aspx?search=" + encodeURIComponent(jQuery(searchObj).val());
}

function fireSearchExtra(searchObj,extraParam1,extraParam2,extraParam3) {
    var qString = "";
    if (extraParam1 != null) {
        qString = qString + "&filter1=" + jQuery("#" + extraParam1).val();
    }
    if (extraParam2 != null) {
        qString = qString + "&filter2=" + jQuery("#" + extraParam2).val();
    }
    if (extraParam3 != null) {
        qString = qString + "&filter3=" + jQuery("#" + extraParam3).val();
    }
    window.location = "/Pages/Search.aspx?search=" + encodeURIComponent(jQuery(searchObj).val()) + qString;
}

function updateDeliveryCountry(obj) {
    var selectedText = jQuery(obj).find(":selected").text();
    jQuery("#deliveryCountry").html(selectedText);
}

function changePaymentOption(input) {

    jQuery("#paymentDiv").find("div.creditpopup").hide();
    jQuery("#paymentDiv").find("div.creditsecure").hide();
    jQuery("#paymentDiv").find("div.creditquickpay").hide();
    jQuery("#paymentDiv").find("div.bank").hide();
    jQuery("#paymentDiv").find("div.cod").hide();
    jQuery("#paymentDiv").find("div.account").hide();
    jQuery("#paymentDiv").find("div.account2").hide();
    jQuery("#paymentDiv").find("div.account3").hide();
    jQuery("#paymentDiv").find("div.financingpay").hide();
    jQuery("#paymentDiv").find("div.paybybill").hide();
    jQuery("#financingDetailsDiv").hide();
    jQuery("#submitButtons").find("input").hide();


    var paymentOption = input.value;

    switch (paymentOption) {
        case "1":
            jQuery("#paymentDiv").find("div.creditpopup").show();
            jQuery("#paymentDiv").find("div.creditsecure").show();
            jQuery("#paymentDiv").find("div.creditquickpay").show();
            jQuery("#submitButtons").find("input.creditSubmit").show();
            jQuery("#submitButtons").find("input.quickpaySubmit").show();
            break;
        case "2":
            jQuery("#paymentDiv").find("div.bank").show();
            jQuery("#submitButtons").find("input.bankSubmit").show();
            break;
        case "3":
            jQuery("#paymentDiv").find("div.cod").show();
            jQuery("#submitButtons").find("input.codSubmit").show();
            break;
        case "4":
            jQuery("#paymentDiv").find("div.account").show();
            jQuery("#submitButtons").find("input.accountSubmit").show();
            break;
        case "11":
            jQuery("#paymentDiv").find("div.account2").show();
            jQuery("#submitButtons").find("input.account2Submit").show();
            break;
        case "12":
            jQuery("#paymentDiv").find("div.account3").show();
            jQuery("#submitButtons").find("input.account3Submit").show();
            break;
        case "13":
            jQuery("#paymentDiv").find("div.financingpay").show();
            jQuery("#financingDetailsDiv").show();
            jQuery("#financingDetailsDiv").find("div.financingpay").show();
            jQuery("#submitButtons").find("input.financingSubmit").show();
        case "14":
            jQuery("#paymentDiv").find("div.paybybill").show();
            jQuery("#submitButtons").find("input.payByBillSubmit").show();
            break;
    }
}

function prodlist2_addItem(button, itemGuid) {

    button = jQuery(button);
    button.parents(".prodlist2_variantTable").first().parent().nextAll(".prodlist2_Result").first().hide();
    button.parents(".prodlist2_variantTable").first().parent().nextAll(".prodlist2_ajaxload").first().show();

    var resultDiv = button.parents(".prodlist2_variantTable").first().parent().nextAll(".prodlist2_Result").first();

    var url = '/Pages/ProductList_View2_proto.aspx';

    var pars = 'function=addItem&itemGuid=' + itemGuid + "&resultDiv=" + resultDiv.attr("id");
    resultDiv.load(url, pars);
}

function prodlist2_addItem_result(divId, cartCountText, cartPriceText) {
    divObj = jQuery("#" + divId);

    divObj.prev().hide();

    divObj.show();
    divObj.effect("highlight", "slow");
}

function updateSmallCart(cartCountText, cartPriceText) {
    jQuery('#smallCartCount').find("span:eq(1)").html(cartCountText);
    jQuery('#smallCartPrice').find("span:eq(1)").html(cartPriceText);

    jQuery('#smallCartCount').effect("highlight", "slow");
    jQuery('#smallCartPrice').effect("highlight", "slow");
}

function prodlist1_addItem_PreCallBack(button) {
    button = jQuery(button);
    var orderResult = button.parents('.divPricesOrder').first().nextAll('.divPricesOrderResult').first();

    if (orderResult.length == 0) {
        button.parents('.divPricesOrder').first().after('<div class="divPricesOrderResult"><div class="text"></div><div class="ajaxload" style="float: right; margin: 0;" /></div>');
        orderResult = button.parents('.divPricesOrder').first().nextAll('.divPricesOrderResult').first();
    }

    orderResult.find('.text').first().html("");
    orderResult.find('.ajaxload').first().show();
}

function locationGridAddressToggle(obj) {
    var addressDiv = jQuery(obj).parents('tr').first().find('.locationGridAddress').first();

    if (addressDiv.is(":visible")) {
        jQuery(obj).parents('tr').first().find('td.locationGridColImg img').first().attr("src", "/images/navigate_right.png");
        addressDiv.slideUp(500);
    }
    else {
        jQuery(obj).parents('tr').first().find('td.locationGridColImg img').first().attr("src", "/images/navigate_down.png");
        addressDiv.slideDown(500);
    }
}
/* Item Sets */
function itemSetShowLoad(obj) {
    jQuery(obj).parents(".itemSetRow").first().find(".ajaxload").first().show();
}
function itemSetShowAddItemLoad(obj) {
    var orderResult = jQuery(obj).parents('.itemSetRow').first().find('.itemSetOrderResult').first();

    var orderResultText = orderResult.find('.itemSetOrderResultText').first();
    if (orderResultText.length > 0) { orderResultText.hide() }

    orderResult.show();
    orderResult.find('.ajaxload').first().show();
}

function itemSetShowAddSetLoad(obj) {
    var orderResult = jQuery(obj).parents('.itemSetInfo').first().find('.itemSetOrderResult').first();

    var orderResultText = orderResult.find('.itemSetOrderResultText').first();
    if (orderResultText != null) { orderResultText.hide() }

    orderResult.show();
    orderResult.find('.ajaxload').first().show();
}


function itemSetShowAddSet2Load(obj) {
    var orderResult = jQuery(obj).parents('.itemSetTotal').first().find('.itemSetOrderResult').first();

    var orderResultText = orderResult.find('.itemSetOrderResultText').first();
    if (orderResultText != null) { orderResultText.hide() }

    orderResult.show();
    orderResult.find('.ajaxload').first().show();
}

/* Method to highlight controls. The parameter "element" should be something readable by jQuery. */
function highlightElement(element) {
    jQuery(element).effect("highlight", "slow");
}


/* Method used for password fields */
function changeInputType(
	  oldElm,
	  iType,
	  iValue,
	  blankValue,
	  noFocus) {
    if (!oldElm || !oldElm.parentNode || (iType.length < 4) ||
		!document.getElementById || !document.createElement) return;
    var isMSIE = jQuery.browser.msie;
    if (!isMSIE) {
        var newElm = document.createElement('input');
        newElm.type = iType;
    } else {
        var newElm = document.createElement('span');
        newElm.innerHTML = '<input type="' + iType + '" name="' + oldElm.name + '">';
        newElm = newElm.firstChild;
    }
    var props = ['name', 'id', 'className', 'size', 'tabIndex', 'accessKey'];
    for (var i = 0, l = props.length; i < l; i++) {
        if (oldElm[props[i]]) newElm[props[i]] = oldElm[props[i]];
    }
    newElm.onfocus = function () {
        return function () {
            if (this.hasFocus) return;
            var newElm = changeInputType(this, 'password', iValue,
		  (this.value.toLowerCase() == iValue.toLowerCase()) ? true : false);
            if (newElm) newElm.hasFocus = true;
        }
    } ();
    newElm.onblur = function () {
        return function () {
            if (this.hasFocus)
                if (this.value == '' || (this.value.toLowerCase() == iValue.toLowerCase())) {
                    changeInputType(this, 'text', iValue, false, true);
                }
        }
    } ();
    newElm.hasFocus = false;
    if (!blankValue) newElm.value = iValue;
    oldElm.parentNode.replaceChild(newElm, oldElm);
    if (!isMSIE && !blankValue) newElm.value = iValue;
    if (!noFocus || typeof (noFocus) == 'undefined') {
        window.tempElm = newElm;
        setTimeout("tempElm.hasFocus=true;tempElm.focus();", 1);
    }
    return newElm;
}

/* loadevents */
jQuery(window).load(
    function () {
        // Find all elements that use that given CSS class
        var elements = jQuery("ul.linkList");
        elements.each(
            function () {
                var ul = jQuery(this);
                ul.find('li').each(
                function () {
                    var li = jQuery(this);
                    // Assign the onclick method to the element
                    li.click(liClickLink);
                    li.mouseover(function () { jQuery(this).addClass("over"); });
                    li.mouseout(function () { jQuery(this).removeClass("over"); });
                });
            }
        );

        // Find all elements that use that given CSS class
        var elements = jQuery("div.productItemPic").find("div.overlayList");
        elements.click(overlayClickLink);

		//Find related images with overlay and enable clicking on the overlay
		jQuery('div.relatedProductImage .overlayList').click(overlayClickLinkRelated);
    }
);

function liClickLink() {
    document.location = jQuery(this).find('a').first().attr("href");
}

function overlayClickLink(event) {
    var link = jQuery(this).parent().find(".highslide");
    if (link.length > 0)
        return hs.expand(link.get(0), hsconfig1);
}

function overlayClickLinkRelated(event) {
    var elm = jQuery(this);
	var link = elm.closest('div.relatedProductImage').find('a').attr('href');
    if (link)
        window.location = link;
}

var lastQuery;

var quickorder = false;
var doDisableEnter = false;

var superSearch =
{
    elements: {
        textBox: null,
        submitBtn: null,
        results: null,
        resultsContent: null
    },
    settings: {
        minQueryLength: 3,
        searchUrl: '/pages/search_prototype.aspx'
    },
    initializeSearch: function () {

        //Hvis supersøgeren er tændt
        if (jQuery('#ssBox').length > 0) {
            superSearch.elements.textBox = jQuery('#ssBox').find('.ssBoxTextDiv input');
            superSearch.elements.submitBtn = jQuery('#ssBox').find('.ssBoxButtonDiv input');
            superSearch.elements.results = jQuery('#ssResult');
            superSearch.elements.resultsContent = jQuery('#ssResultContent');
            //superSearch.elements.textBox.focus();

            superSearch.elements.textBox.keyup(superSearch.ssTextBoxOnKeyUp);
            superSearch.elements.textBox.keydown(superSearch.ssTextBoxOnKeyDown);
            superSearch.elements.textBox.keypress(superSearch.ssTextBoxOnKeyPress);
            superSearch.elements.textBox.blur(superSearch.ssTextBoxOnBlur);
            superSearch.elements.submitBtn.click(superSearch.ssSubmitBtnOnClick);

            superSearch.elements.textBox.focus(superSearch.ssTextBoxOnFocus);

            superSearch.elements.textBox.attr("autocomplete", "off");
        }
    },
    ssTextBoxOnKeyUp: function (e) {
        // arrow up(38) or down(40) or enter(13)
        if (e.keyCode == 38 || e.keyCode == 40 || e.keyCode == 13 || e.keyCode == 27)
            if (e.keyCode == 38) {
                //alert("op");
                ssResultNavigation('up');
            }
        if (e.keyCode == 40) {
            //alert("ned");
            ssResultNavigation('down');
        }
        if (e.keyCode == 13) {
            if (ssResultLink != '') {
                clearOnHref();
                document.location.href = ssResultLink;
            }
        }
        if (e.keyCode == 27) {
            superSearch.hideResults();
            lastQuery = '';
            jQuery(superSearch.elements.textBox).blur();
        }
        else {
            var query = trim(jQuery(superSearch.elements.textBox).val());
            //alert(query);
            if (query.length >= superSearch.settings.minQueryLength && lastQuery != query) {
                superSearch.timer = clearTimeout(superSearch.timer);
                superSearch.timer = setTimeout("callQuery();", 500);
                lastQuery = query
            } else if (query.length < superSearch.settings.minQueryLength) {
                superSearch.timer = clearTimeout(superSearch.timer);
                superSearch.hideResults();
                lastQuery = '';
            }
        }
    },
    ssTextBoxOnKeyDown: function () {

    },
    ssTextBoxOnKeyPress: function (e) {
        if (e.keyCode == 13) {
            if (!quickorder && !doDisableEnter)
                fireSearch(this);
            e.preventDefault();
        }
    },
    ssTextBoxOnBlur: function () {
        setTimeout('if (clickeditem != true){superSearch.hideResults();lastQuery = \'\';}', 200);
    },
    ssTextBoxOnFocus: function () {
        if (jQuery(superSearch.elements.textBox).val() != '' && jQuery(superSearch.elements.textBox).val() != jQuery(superSearch.elements.textBox).attr("title")) {
            var query = trim(jQuery(superSearch.elements.textBox).val());
            superSearch.performSearch(query);
            lastQuery = query;
        }
    },
    ssTextBoxOnKeyBlur: function () {

    },
    ssSubmitBtnOnClick: function (e) {
        fireSearch(superSearch.elements.textBox);
        e.preventDefault();
    },
    showResults: function () {
        if (!jQuery(superSearch.elements.results).is(":visible"))
            jQuery(superSearch.elements.results).fadeIn(200);
        ssResultArrayId = [];
        ssResultArrayHref = [];
        ssResultArray = [];
        ssResultsToArray();
        clickeditem = false;
    }
    ,
    hideResults: function () {
        if (jQuery(superSearch.elements.results).is(":visible")) {
            jQuery(superSearch.elements.results).fadeOut(200);
            clearResultNavigation();
        }
    },
    performSearch: function (query) {
        var parameters = "q=" + encodeURIComponent(query);
        var ajaxError = false;
        jQuery('#ssBox').find('img').css("display", "block");

        jQuery("#ssResult").find("li").unbind("mousemove", lookForLiInResult);
        jQuery("#ssResult").find("li").unbind("click", goToOnClick);

        jQuery(superSearch.elements.resultsContent).load(superSearch.settings.searchUrl, parameters,
                    function (response, status, xhr) {
                        // On complete
                        if (status == "error")
                            superSearch.perform500Response();
                        else
                            superSearch.performSearchOnSuccess();
                    });
    },
    perform500Response: function () {
        var pamaters = "error=true";
        jQuery(superSearch.elements.resultsContent).load(superSearch.settings.searchUrl, pamaters,
            function (response, status, xhr) {
                superSearch.performSearchOnSuccess();
            });
    },
    performSearchOnSuccess: function (response) {
        setTimeout(hideSearchLoadingImage, 500);
        if (jQuery(superSearch.elements.results).html().length > 0) {
            superSearch.showResults();
            jQuery("#ssResult").find("li").bind("mousemove", lookForLiInResult);
            jQuery("#ssResult").find("li").bind("click", goToOnClick);
			jQuery("#ssResult").find("div.ssResultSeeAll").bind("click", goToSearchPage);
        } else {
            superSearch.hideResults();
            jQuery("#ssResult").find("li").unbind("mousemove", lookForLiInResult);
            jQuery("#ssResult").find("li").unbind("click", goToOnClick);
			jQuery("#ssResult").find("div.ssResultSeeAll").unbind("click", goToSearchPage);
        }
    }
    /* Super Search methods */
}

function hideSearchLoadingImage() {
    jQuery("#ssBox").find(".ssBoxLoaderIcon img").hide();
}

jQuery(window).load(superSearch.initializeSearch);

function callQuery() {
    superSearch.performSearch(jQuery(superSearch.elements.textBox).val());
}

function lookForLiInResult(event) {
    var elt = jQuery(this);
    if (ssResultCursor != ssResultArrayId.indexOf(elt.attr('id'))) {
        ssResultCursor = ssResultArrayId.indexOf(elt.attr('id'));
        ssActivateItem(elt.attr('id'));
    }
}

var clickeditem = false;
function goToOnClick(event) {
    clickeditem = true;
    ssGoToItem(jQuery(this).attr('id'));
}

function goToSearchPage(event)
{
	window.location = jQuery(this).find("a").attr("href");
}

function AjaxBackButtonRefresh() {
    jQuery(window).load(function () {
        var e = document.getElementById("refreshed");
        if (e.value == "no") e.value = "yes";
        else {
            e.value = "yes"; // necessary to make IE update correctly...
            refreshSmallCart(); 
        }
    });
}

function refreshSmallCart() {
    jQuery.getJSON('/Pages/Utility/SmallCart_ajax.aspx?' + Math.round(new Date().getTime()), function (data) {
        updateCarts(data.CartCount, data.CartPrice, data.CartFinancedPrice);
    });
}

function updateCarts(cartCountText, cartPriceText, cartFinancedPrice) {
    jQuery('#smallCartCount').find("span:eq(1)").html(cartCountText);
    jQuery('#smallCartPrice').find("span:eq(1)").html(cartPriceText);
    jQuery('#smallCartFinancingPrice').find("span:eq(1)").html(cartFinancedPrice);

    jQuery('#topSmallCartCount').find("span:eq(1)").html(cartCountText);
    jQuery('#topSmallCartPrice').find("span:eq(1)").html(cartPriceText);
    jQuery('#topSmallCartFinancingPrice').find("span:eq(1)").html(cartFinancedPrice);
}

var ssResultArrayId = [];
var ssResultArrayHref = [];
var ssResultArray = [];
var ssResultCursor = -1;
var ssResultLink = '';

function ssResultNavigation(dir) {
    if (dir == 'up') {
        ssResultCursor--;
        if (ssResultCursor > -1) {
            ssResultLink = ssResultArray[1][ssResultCursor];
            ssActivateItem(ssResultArray[0][ssResultCursor]);
        } else {
            ssResultCursor++;
        }
    } else if (dir == 'down') {
        ssResultCursor++
        if (ssResultCursor < ssResultArrayId.length) {
            ssResultLink = ssResultArray[1][ssResultCursor];
            ssActivateItem(ssResultArray[0][ssResultCursor]);
        } else {
            ssResultCursor--;
        }
    }

}

function ssResultsToArray() {
    var resultListsIds = ['#searchResultCheckList_1', '#searchResultGroup_1', '#searchResultItem_1', '#searchResultIdea_1'];

    for (var i = 0; i < resultListsIds.length; i++) {
        if (jQuery(resultListsIds[i]).length > 0) {
            var ssGroupUl = jQuery(resultListsIds[i]).parents('ul').first().children();
            for (ssg = 0; ssg < ssGroupUl.length; ssg++) {
                var id = jQuery(ssGroupUl[ssg]).attr('id');
                ssResultArrayId.push(id);
                var resultItem = jQuery("#" + id);
                ssResultArrayHref.push(resultItem.find('a').first().attr('href'));
            }
        }
    }
    
    ssResultArray = [ssResultArrayId, ssResultArrayHref];
}


function ssActivateItem(id) {
    for (ssAI = 0; ssAI < ssResultArrayId.length; ssAI++) {
        jQuery("#" + ssResultArrayId[ssAI]).get(0).className = 'item';
    }
    jQuery("#" + id).get(0).className = 'itemActive';
}

function ssActivateItemOver(obj) {
    ssActivateItem(jQuery(obj).attr('id'));
}

function ssGoToItem(id) {
    clearOnHref()
    document.location.href = jQuery("#" + id).find('a').first().attr('href');
}

function ssGoToItemClick(obj) {
    ssGoToItem(obj.readAttribute('id'));
}

function clearResultNavigation() {
    ssResultArrayId = [];
    ssResultArrayHref = [];
    ssResultArray = [];
    ssResultCursor = -1;
}

function clearOnHref() {
    superSearch.elements.textBox.blur();
    clearResultNavigation();
    setTimeout('superSearch.hideResults();', 200);
}

/* textbox default text handling */
function remSetValues() {
    var eToWatch = jQuery('input.keepValue');
    eToWatch.each(function () {
        var obj = jQuery(this);
        if (obj.attr("type") == 'password') {
            changeInputType(obj.get(0), 'text', obj.attr("title"), false, true);
        }
        else {
            obj.focus(function () {
                var element = jQuery(this);
                if (element.val() == element.attr('title'))
                { element.val('') };
            });
            obj.blur(function (event) {
                var element = jQuery(this);
                if (element.val() == '')
                { element.val(element.attr('title')) };
            });
        }
    });
}

jQuery(window).load(remSetValues);

var ProductVariantFiltering = {
    showAjaxLoader: function (variantGridViewId) {
        var tbody = jQuery("#" + variantGridViewId).find('tbody').first();
        var loaderOverlay = jQuery("#variantLoaderOverlay");
        //Element.clonePosition(loaderOverlay, tbody);
        loaderOverlay.css({
            'position': "absolute",
            'width': jQuery("#" + variantGridViewId).width() + "px",
            'height': jQuery("#" + variantGridViewId).width() + "px"
        });
        var gridHeaderHeight = jQuery(tbody).find('.header').first().height();
        var loaderAnimation = loaderOverlay.select('.loaderAnimation').first();
        loaderAnimation.css({ 'margin-top': (gridHeaderHeight + 10) + "px" });
        loaderOverlay.show();
    },
    hideAjaxLoader: function () {
        jQuery('#variantLoaderOverlay').hide();
    }
};

//Top drop down menu script for IE6/added functionality for others
jQuery(function () {
    //Check if menu is enabled
    if (jQuery('#topDropDownMenu').length > 0) {
        var c = 0;
        jQuery('li.expanderMenu').each(function () {
            //Event handlers
            jQuery(this).mouseenter(handleDropDownMenuOver);
            jQuery(this).mouseleave(handleDropDownMenuOut);
            jQuery(this).attr("id", "topmenu_" + c);
            c++;
        });
    }
});
function tryParse(input, fallback) {
    if (input.toString().match(/^(\d)/) != null) {
        input = parseInt(input);
        return input;
    }
    else return fallback;
}
var constAdd = 0;
var disableTopMenuCalculation = false;
function handleDropDownMenuOver() {
    var elm = jQuery(this);
    if (!elm.hasClass('expanderMenu')) {
        elm = elm.find('li.expanderMenu');
    };
    //remove classes from menu items no longer hovered over
    jQuery('li.expanderMenu').each(function () {
        var obj = jQuery(this);
        if (obj.attr("id") != elm.attr("id"))
            obj.removeClass('showAsHover');
        obj.removeClass('toBeHidden');
    });
    //IE6 needs this class
    elm.addClass('showAsHover');

    //REV attribute is read to see if the calculation has already been made
    if (elm.attr('rev') != 'true' && !disableTopMenuCalculation)
    {
        var intTotaltWidthOfDL = 0;
        //Get total width of all DL's in the menu
        elm.find('dl').each(function () {
            tmpElm = jQuery(this);
            intTotaltWidthOfDL += tryParse(tmpElm.width(), 0);
            intTotaltWidthOfDL += tryParse(tmpElm.css('padding-left').replace('px', ''), 0);
            intTotaltWidthOfDL += tryParse(tmpElm.css('padding-right').replace('px', ''), 0);
            intTotaltWidthOfDL += tryParse(tmpElm.css('border-left-width').replace('px', ''), 0);
            intTotaltWidthOfDL += tryParse(tmpElm.css('border-right-width').replace('px', ''), 0);
        });
        var tmpGroup = elm.find('.menuThirdWrap, .menuSecondWrap, .menuFirstWrap');
        tmpGroup.each(function () {
            tmpElm = jQuery(this);
            intTotaltWidthOfDL += tryParse(tmpElm.css('padding-left').replace('px', ''), 0);
            intTotaltWidthOfDL += tryParse(tmpElm.css('padding-right').replace('px', ''), 0);
            intTotaltWidthOfDL += tryParse(tmpElm.css('border-left-width').replace('px', ''), 0);
            intTotaltWidthOfDL += tryParse(tmpElm.css('border-right-width').replace('px', ''), 0);
        });
        //This constant needs to be added
        intTotaltWidthOfDL += constAdd;
        if (intTotaltWidthOfDL > constAdd) {
            //Get dimensions and positions
            var intTotalWidthOfContainer = jQuery('div.menu').first().width();
            var elmMenuContainer = elm.find('div.menuContainer').first();
            var intPosMenuBox = elmMenuContainer.position().left;
            var intBoxCurrentWidth = elmMenuContainer.width();
            if (intPosMenuBox > (intTotalWidthOfContainer - intTotaltWidthOfDL)) {
                //Here we have determined that the box needs to be moved to the left
                elmMenuContainer.css("margin-left", ((intTotalWidthOfContainer - intTotaltWidthOfDL) - intPosMenuBox) + 'px');
            }
            //IE6: We also set the width manually, as IE6 doesn't just make it wider by itself as other browser, when moved to the left
            elmMenuContainer.css("width", intTotaltWidthOfDL + 'px');

            //Check if it's done correctly... Should be optimized!
            var done = false;
            var group = elm.find('dl');
            var tmpNo = group.first().position().top;
            var c = 1;
            while (!done && c <= 15) {
                var tmpFlag = false;
                elm.find('dl').each(function () {
                    if (jQuery(this).position().top > tmpNo) {
                        tmpFlag = true
                    }
                });
                if (!tmpFlag) {
                    done = true;
                } else {
                    elmMenuContainer.css("width", intTotaltWidthOfDL + c + 'px');
                }
                c++;
            }
            if (c > 15) {
                //Too many iterations - must be a vertical menu, reset all changes made by this script, and flag to disable
                elmMenuContainer.css({ 'width': 'auto', 'margin-left': '0px' });
                disableTopMenuCalculation = true;
            }

        }
        //REV attribute is set to avoid wasting CPU :)
        elm.attr('rev', 'true');
    }
}

function handleDropDownMenuOut() {
    //Purely for IE6 - it needs a class as li:hover is unsupported
    var elm = jQuery(this)
    if (!elm.hasClass('expanderMenu')) {
        elm = elm.find('li.expanderMenu');
    };
    elm.addClass('toBeHidden');
    setTimeout(cleanMenu, 500);
}

function cleanMenu() {
    jQuery('.toBeHidden').removeClass('toBeHidden showAsHover');
}

// Code needed for sharebox
jQuery(document).ready(function (event) {
    if (jQuery('#shareBoxTipImg').length > 0) {
        clearFriendTip();
        jQuery(window).resize(function () { setTimeout('moveTipper();', 0); });
        jQuery('.shareBox div img.shareIcon').mouseover(handleMouseOver);
        jQuery('.shareBox div img.shareIcon').mouseover(handleMouseOut);
    }
});
function handleMouseOver(e) {
    window.sTimer = clearTimeout(window.sTimer);
    jQuery('#shareBoxTitle').show().attr("src", e.target.src.replace(".png", "_msg.png"));
}
function handleMouseOut(e) {
    window.sTimer = setTimeout("jQuery('#shareBoxTitle').hide();", 1000);
}
var tipperVisible = false;

function startTip() {
    moveTipper();
    jQuery("#shareBoxTip").toggle(200);
}
function moveTipper() {
    var boxPos = jQuery('#shareBoxTipImg').position();
    var boxWidth = jQuery('#shareBoxTipImg').width();
    var elmForDims = jQuery('.centerContent, .centerContentProductNoRight').first();
    var contWidth = elmForDims.width();
    var intBoxRightEdge = -contWidth + (boxPos.left + boxWidth);
    var intBoxTopEdge = boxPos.top + 15;
    jQuery('#shareBoxTip').css({ 'right': intBoxRightEdge + 'px', 'top': intBoxTopEdge + 'px' });
}

function handleTipSuccess(response) {
    var strStatus = response.responseText;
    jQuery('#shareBoxTipUpdater').html(strStatus);
    jQuery('#shareBoxTipUpdater').css('color', '#539957').show();
    setTimeout("jQuery('#shareBoxTip').hide(200);", 1500);
    setTimeout('clearFriendTip();', 1700);
}

function clearFriendTip() {
    //$('shareBoxTipForm').reset(); //Disabled since the form does not exist. (Quick fix)
    jQuery('#shareBoxTipUpdater').html("");
}

//Show more text
function showMoreInfoText(obj) {
    jQuery(obj).parents('div').first().hide();
    jQuery(obj).parents("div:eq(1)").find("div:eq(1)").show();
}

// Shortens all more info texts
jQuery(window).load(function () {
    jQuery('.moreInfoText').each(function () {
        jQuery(this).find('div').first().show();
        jQuery(this).find('div:eq(1)').hide();
    });
});

function disableEnter(myfield, e) {
    var keycode;
    if (window.event) keycode = window.event.keyCode;
    else if (e) keycode = e.which;
    else return true;
    if (keycode == 13) {
        return false;
    }
    else
        return true;
}

function openItemFlash(sender, flashfile) {
    //var dim = document.viewport.getDimensions();
    var width = 800;
    var height = 800;
    if ($(window).width() < 800)
        width = $(window).width() - 10;

    if ($(window).height() < 800)
        height = $(window).height() - 10;

    return hs.htmlExpand(sender, {
        src: flashfile,
        objectType: 'swf',
        width: width,
        objectWidth: width,
        objectHeight: height - 50,
        preserveContent: false,
        wrapperClassName: 'no-footer',
        allowSizeReduction: false,
        maincontentText: 'You need to upgrade your Flash player'
    });
}

// BEGIN Functionality for the frontpage slideshow

var clockDelay = 0, clockPosition = 0, clockTimeout;

function initFrontpageSlideshow(interval, speed, effect) {
    if (interval == 0) interval = 5000;
    if (effect == '') effect = 'scrollHorz';
    if (speed == 0) speed = 600;
    clockDelay = interval / 9;

    trimCaptions();

    $("#mainSlideshow").cycle({
        fx: effect,
        timeout: interval,
        speed: speed,
        easing: "easeInQuart",
        pager: "#mainSlideshowNavigation",
        after: function (curr, next, opts) {
            onAfterSlide(curr, next, opts);
        },
        before: resetClock
    });
    $(".mainSlideshowCaptions").cycle({
        timeout: interval,
        speed: speed,
        cleartypeNoBg: true,
        before: onBeforeCaptionSlide
    });
}

function onAfterSlide(curr, next, opts) {
    var caption = (opts.currSlide + 1);
    $(".mainSlideshowPager").html(caption + "/" + opts.slideCount);
}

function onBeforeCaptionSlide(currSlideElement, nextSlideElement, options, forwardFlag) {
    if ($(nextSlideElement).find("span").text() == "")
        $(".mainSlideshowCaptionsBG").fadeOut();
    else if ($(".mainSlideshowCaptionsBG").is(":hidden"))
        $(".mainSlideshowCaptionsBG").fadeTo("slow", 0.5);
}

function moveClock() {
    if(clockPosition - 16 > -143) clockPosition -= 16;
    else clockPosition = 0;
    $("#mainSlideshowClock").css("background-position", clockPosition + "px 0");
    clockTimeout = setTimeout("moveClock()", clockDelay);
}

function resetClock(){
    clearTimeout(clockTimeout);
    clockPosition = 0;
    $("#mainSlideshowClock").css("background-position", "0 0");
    clockTimeout = setTimeout("moveClock()", clockDelay);
}

function trimCaptions() {
    $(".mainSlideshowCaptions").append('<span id="tempSpan" style="position: absolute; top: -5000px; overflow: hidden; white-space: nowrap">');
    $(".mainSlideshowCaptions").find(".inner-slide").each(function () {
        var span = $(this).find("span");
        var text = span.text();
        $("#tempSpan").text(text);
        var spanPaddingLeft = $(span).parent().css("padding-left");
        spanPaddingLeft = Number(spanPaddingLeft.substr(0, spanPaddingLeft.length - 2));
        while ($("#tempSpan").width() > $(".mainSlideshowContainer").width() - spanPaddingLeft - 40) {
            text = $("#tempSpan").text();
            text = text.substr(0, text.length - 4) + "...";
            $("#tempSpan").text(text);
        }
        span.text(text);
    });
    $("#tempSpan").remove();
}

// END Functionality for the frontpage slideshow

function anteconsTrackEvent(category, action, label, acevent, site, item) {
    // If Google Analytics is enabled, track the event here.
    if (typeof _gaq != 'undefined') {
        _gaq.push(['_trackEvent', category, action, label]);
    }

    // Track the click in Antecons.
    $.post(
            '/Pages/Utility/RecommendationTracker.aspx',
            { 'useraction': action, 'acevent': acevent, 'site': site, 'item': item }
        );
}

function anteconsClick(link, category, action, label, acevent, site, item) {
    anteconsTrackEvent(category, action, label, acevent, site, item);

    // Transfer the user to the correct page,
    // allowing some time to process the above requests.
    setTimeout('document.location = "' + link.href + '"', 500)
}

// START Methods for Modal Cart Dialog

var disableDisplayModelCartDialog = false;
var modalCartDialogDisplayTimeInSeconds = 5;
var modalCartDialogTimeout;

function displayModalCartDialog(buttonId, sourceItemGuid, relatedCartLineEntityGuid) {
    if (!getCookie('do_not_show_modal_cart_dialog') && !disableDisplayModelCartDialog) {

        // Original functionality with no related items
        if (relatedCartLineEntityGuid == null || relatedCartLineEntityGuid == "") {
            clearTimeout(modalCartDialogTimeout);
            modalCartDialogTimeout = setTimeout("$('#modalDialogCloseButton').click();", (modalCartDialogDisplayTimeInSeconds * 1000));
            var obj = document.getElementById(buttonId);
            return hs.htmlExpand(obj, { width: 511, contentId: 'modalOuterShadowDiv', outlineType: null, dimmingOpacity: 0, align: 'center' }); //align: 'auto' displays the dialog with center in the button.
        }
        // New functionality with related items
        else {
            $.getJSON('/Pages/Utility/ModalCartDialogRelatedItems_ajax.aspx?sourceItemGuid=' + sourceItemGuid,
            function (data) {
                if (data.length > 0) {
                    $("#modalRelatedContainer").css("display", "block");
                    $("#full_list_button").attr("href", "/Pages/ProductListAccessories.aspx?itemGuid=" + sourceItemGuid + "&MasterCartLineGuid=" + relatedCartLineEntityGuid);

                    // Prevent the modal dialog to close automatically when related items are displayed
                    modalCartDialogDisplayTimeInSeconds = 86400;
                    $("div#modalMessage").hide();
                }

                if (data[0] != null) { $("#relatedItemPlaceholder_0").html(generateItemCardFromJsonItemData(data[0], relatedCartLineEntityGuid)); }
                if (data[1] != null) { $("#relatedItemPlaceholder_1").html(generateItemCardFromJsonItemData(data[1], relatedCartLineEntityGuid)); }
                if (data[2] != null) { $("#relatedItemPlaceholder_2").html(generateItemCardFromJsonItemData(data[2], relatedCartLineEntityGuid)); }
                if (data[3] != null) { $("#relatedItemPlaceholder_3").html(generateItemCardFromJsonItemData(data[3], relatedCartLineEntityGuid)); }
                if (data[4] != null) { $("#relatedItemPlaceholder_4").html(generateItemCardFromJsonItemData(data[4], relatedCartLineEntityGuid)); }

                clearTimeout(modalCartDialogTimeout);
                modalCartDialogTimeout = setTimeout("$('#modalDialogCloseButton').click();", (modalCartDialogDisplayTimeInSeconds * 1000));
                var obj = document.getElementById(buttonId);
                return hs.htmlExpand(obj, { width: 511, contentId: 'modalOuterShadowDiv', outlineType: null, dimmingOpacity: 0, align: 'center' }); //align: 'auto' displays the dialog with center in the button.
            });
        }
    }
}

function generateItemCardFromJsonItemData(data, relatedCartLineEntityGuid) {
    var itemGuid = data.ItemGuid;
    var productName = data.ProductName;
    var productVariantName = data.ProductVariantName;
    var productDescription = data.ProductDescription;
    var itemNo = data.ItemNo;
    var itemPrice = data.ItemPrice;
    var itemPriceFinanced = data.ItemPriceFinanced;
    var itemNavigateUrl = data.ItemHyperLink + "?MasterCartLineGuid=" + relatedCartLineEntityGuid; // Note, that for some product URLs, where a variant is specified, the ? character is already present in the URL
    //var itemImageUrl = itemImageUrl != null ? data.ItemImageUrl : "/images/noimage_medium.jpg";
    var itemImageUrl = itemImageUrl != null ? data.ItemImageUrl : "";

    var returnString = '';
    returnString += '<div class="modalItemPic">';
    returnString += '    <a href="' + itemNavigateUrl + '"><img src="' + itemImageUrl + '" alt="" /></a>';
    returnString += '</div>';
    returnString += '<div class="modalItemName"><a href="' + itemNavigateUrl + '">' + productName + '</a></div>';
    returnString += '<!--div class="modalItemDescription"><a href="' + itemNavigateUrl + '">' + productDescription + '</a></div-->';
    returnString += '<div class="modalItemPrice"><a href="' + itemNavigateUrl + '">' + itemPrice + '</a></div>';
    returnString += '<div class="modalItemButton"><a href="' + itemNavigateUrl + '">Info/Køb</a></div>';

    return returnString;
}

function handleNeverShowAgain(obj) {
    var cookie_name = "do_not_show_modal_cart_dialog";
    if (obj.checked)
    {
        setCookie(cookie_name, "true", 365);
    }
    else {
        deleteCookie(cookie_name);
    }
}

// END Methods for Modal Cart Dialog

// START General Cookie methods
function setCookie(c_name, value, exdays) {
    var exdate = new Date();
    exdate.setDate(exdate.getDate() + exdays);
    var c_value = escape(value) + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString());
    document.cookie = c_name + "=" + c_value;
}

function deleteCookie(c_name) {
    setCookie(c_name, "", -1);
}

function getCookie(c_name) {
    var i, x, y, ARRcookies = document.cookie.split(";");
    for (i = 0; i < ARRcookies.length; i++) {
        x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
        y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
        x = x.replace(/^\s+|\s+$/g, "");
        if (x == c_name) {
            return unescape(y);
        }
    }
}

function checkCookie() {
    var username = getCookie("username");
    if (username != null && username != "") {
        alert("Welcome again " + username);
    }
    else {
        username = prompt("Please enter your name:", "");
        if (username != null && username != "") {
            setCookie("username", username, 365);
        }
    }
}

// END General Cookie methods

