﻿var rs_asp_id_prefix;
var selectedPaymentPeriodMonths;
var selectedPaymentPeriod;
var selectedPostsPerPage;
var selectedSortIndex;
var selectedListType;
var productGroupTypeId;
var tireListShown;
var defaultTirePrdGrpId;
var rimProductShownInFlash;
var rimFileShownInFlash;
var accTypeId;
var noSearchMsg;
var prevSearchBrand;
var prevSearchModel;
var prevSearchBoltCircle;
var prevSearchSize;
var prevSearchManufacturer;
var resetSearch;
var pageGoto;
var initialScroll;
var contScrollBefore;
var arrPrdDisc;
var moreImagesTimer;
var offerSearch;

function hideSearchBtn(msg) {
    document.getElementById(rs_asp_id_prefix + "divSearchBtn").style.backgroundImage = "url(/Img/rim_search/rimMenuSpriteBlue.png)";
    document.getElementById(rs_asp_id_prefix + "divSearchBtn").style.backgroundPosition = "-70px -146px";
    $("#" + rs_asp_id_prefix + "divSearchBtn").css("cursor", "default");
    document.getElementById(rs_asp_id_prefix + "hdBtn").value = '0';
    noSearchMsg = msg;
}

function showSearchBtn() {
    document.getElementById(rs_asp_id_prefix + "divSearchBtn").style.backgroundImage = "url(/Img/rim_search/rimMenuSpriteBlue.png)";
    document.getElementById(rs_asp_id_prefix + "divSearchBtn").style.backgroundPosition = "0px -146px";
    $("#" + rs_asp_id_prefix + "divSearchBtn").css("cursor", "pointer");
    document.getElementById(rs_asp_id_prefix + "hdBtn").value = '1';
}

function selectBrand(ddl) {
    $("#" + rs_asp_id_prefix + "lblBoltCircle").html("");
    $("#divStep1boltCircle").hide();

    var brandId = ddl[ddl.selectedIndex].value;

    if (brandId == 0) {
        $("#" + rs_asp_id_prefix + "ddlModels").attr("disabled", true);
        $("#" + rs_asp_id_prefix + "ddlModels").html('<option value="0">2. Välj modell</option>');
        selectModel2($("#" + rs_asp_id_prefix + "ddlModels").val());
    } else {
        loadingShow("Hämtar bilmodeller...", document.getElementById('loadingtxt'), document.getElementById('loading'));
        $("#" + rs_asp_id_prefix + "ddlModels").html('<option value="-1">Laddar...</option>');
        $("#" + rs_asp_id_prefix + "ddlModels").addSelectOptions("/Common/VehicleDataHandler.ashx?action=vehicleModelsByBrandForDropdown&brandId=" + brandId, function() {
            selectModel2($("#" + rs_asp_id_prefix + "ddlModels").val());
        });
    }
}

function selectModel1(ddl) {
    var modelId = ddl[ddl.selectedIndex].value;
    selectModel2(modelId);
}

function displayBoltSize(modelId) {
    loadingShow("Hämtar bultcirkel...", document.getElementById('loadingtxt'), document.getElementById('loading'));
    $.get("/Common/VehicleDataHandler.ashx?action=getBoltCircle&id=" + modelId, function(res) {
        if (res != '') {
            $("#" + rs_asp_id_prefix + "lblBoltCircle").html(res);
            document.getElementById('divStep1boltCircle').style.display = 'block';
            //document.getElementById('divStep1boltCircle').style.width = '106px';//'76px';
        } else {
            $("#" + rs_asp_id_prefix + "lblBoltCircle").html("");
            document.getElementById('divStep1boltCircle').style.display = 'none';
        }
        loadingHide(document.getElementById('loading'));
    });
}

function selectModel2(modelId) {
    loadingShow("Hämtar storlekar...", document.getElementById('loadingtxt'), document.getElementById('loading'));

    $("#" + rs_asp_id_prefix + "norimsconnected").hide();
    showSearchBtn();
    if (modelId == 0) modelId = 999;

    if (resetSearch == 1) {
        $("#" + rs_asp_id_prefix + "ddlModels").selectedValue(prevSearchModel);
        modelId = $("#" + rs_asp_id_prefix + "ddlModels").val();
    }
    var brandId = $("#" + rs_asp_id_prefix + "ddlBrands").val();

    if (modelId == 999 && brandId == 999) {
        $("#" + rs_asp_id_prefix + "divStep2boltCircle").show();
        var bcid = $("#" + rs_asp_id_prefix + "ddlBoltCircle").val();
        if (bcid == -1) hideSearchBtn("Du måste även välja en bultcirkel eller [ALLA] för att kunna söka.");
    } else {
        $("#" + rs_asp_id_prefix + "divStep2boltCircle").hide();
    }

    if (modelId == 999) {
        selectBoltCircle();
        if (brandId == 0) {
            $("#" + rs_asp_id_prefix + "ddlModels").attr("disabled", true);
            hideSearchBtn("Du måste välja din bil eller [ALLA] för att kunna söka.");
        } else if (brandId == 999) {
            $("#" + rs_asp_id_prefix + "ddlModels").get(0).selectedIndex = 1;
            $("#" + rs_asp_id_prefix + "ddlModels").attr("disabled", true);
        } else {
            $("#" + rs_asp_id_prefix + "ddlModels").attr("disabled", false);
            hideSearchBtn("Du måste välja din bilmodell också för att kunna söka.");
            $("#" + rs_asp_id_prefix + "lblBoltCircle").html("");
            $("#divStep1boltCircle").hide();
        }
    } else {
        displayBoltSize(modelId);

        $("#" + rs_asp_id_prefix + "ddlModels").attr("disabled", false);
        $("#" + rs_asp_id_prefix + "ddlSize").html('<option value="-1">Laddar...</option>');
        $("#" + rs_asp_id_prefix + "ddlSize").addSelectOptions("/Common/VehicleDataHandler.ashx?action=rimSizeInchesForDropdown&typeId=" + productGroupTypeId + "&modelId=" + modelId, function() {
            selectInch();
        });
    }
}

function selectInch() {
    loadingShow("Hämtar tillverkare...", document.getElementById('loadingtxt'), document.getElementById('loading'));

    if (resetSearch == 1) {
        $("#" + rs_asp_id_prefix + "ddlSize").selectedValue(prevSearchSize);
    }

    var inch = $("#" + rs_asp_id_prefix + "ddlSize").val();
    var bcid = $("#" + rs_asp_id_prefix + "ddlBoltCircle").val();
    var modelId = $("#" + rs_asp_id_prefix + "ddlModels").val();
    $("#" + rs_asp_id_prefix + "ddlManufacturer").addSelectOptions("/Common/VehicleDataHandler.ashx?action=productGroupRimManufacturerForDropdown&typeId=" + productGroupTypeId + "&bcid=" + bcid + "&inch=" + inch + "&modelId=" + modelId, function() {
        loadingHide(document.getElementById('loading'));
        if (resetSearch == 1) {
            $("#" + rs_asp_id_prefix + "ddlManufacturer").selectedValue(prevSearchManufacturer);
            submitSearch(pageGoto, null, 0, false);
        }
    });
}

function selectBoltCircle() {
    loadingShow("Hämtar storlekar...", document.getElementById('loadingtxt'), document.getElementById('loading'));

    if (resetSearch == 1) {
        $("#" + rs_asp_id_prefix + "ddlBoltCircle").selectedValue(prevSearchBoltCircle);
    }

    var bcid = $("#" + rs_asp_id_prefix + "ddlBoltCircle").val();
    if (bcid == -1) {
        hideSearchBtn("Du måste även välja en bultcirkel eller [ALLA] för att kunna söka.");
    } else {
        showSearchBtn();
    }
    $("#" + rs_asp_id_prefix + "ddlSize").html('<option value="-1">Laddar...</option>');

    $("#" + rs_asp_id_prefix + "ddlSize").addSelectOptions("/Common/VehicleDataHandler.ashx?action=boltCircleInchesForDropdown&typeId=" + productGroupTypeId + "&boltCircleId=" + bcid, function() {
        $("#" + rs_asp_id_prefix + "ddlSize").prepend('<option value="0" selected="selected">[ALLA]</option>');
        selectInch();
        loadingHide(document.getElementById('loading'));
    });
}

function getSelectedModelId() {
    return $("#" + rs_asp_id_prefix + "ddlModels").val();
}

function selectPayment(ddl) {
    var n = ddl[ddl.selectedIndex].value;
    if (n != selectedPaymentPeriod) {
        loadingShow("Räknar om priser...", document.getElementById('loadingtxt'), document.getElementById('loading'));
        selectedPaymentPeriod = n;

        switch (n) {
            case 0: selectedPaymentPeriodMonths = 3; break;
            case 1: selectedPaymentPeriodMonths = 6; break;
            case 2: selectedPaymentPeriodMonths = 12; break;
            case 4: selectedPaymentPeriodMonths = 24; break;
            case 5: selectedPaymentPeriodMonths = 36; break;
            default: selectedPaymentPeriodMonths = 24; break;
        }
        
        $.get("/Common/CommonDataHandler.ashx?method=setPaymentPeriodCookie&period=" + selectedPaymentPeriodMonths, function() {
        });

        // 0 thumbs, 1 list, 2 detail
        if (selectedListType == 2) {
            // rims
            $.each($(".itm"), function() {
                var itmid = this.id.replace("itm_", "");
                var pid = $(this).find("#id_" + itmid).val();
                var qty = $(this).find("#qty_" + itmid).val();
                qty = (qty.length > 0) ? new Number(qty) : 0;

                setPaymentPeriodPrice(itmid, pid);

                var rimprice = $(this).find("#price_" + itmid).val();

                // tires
                $.each($(this).siblings("#tires_" + itmid).find(".tirelistvehiclerim .tirelisttbl .tirelistitm"), function() {
                    var tireid = this.id.replace("tireitm_" + itmid + "_", "");
                    var tireqty = qty;
                    
                    $.getJSON("/Common/VehicleDataHandler.ashx?action=getTireAndRimPaymentPeriodPrice&id=" + tireid + "&period=" + n + "&qty=" + tireqty + "&rimqty=" + qty + "&rimprice=" + rimprice, function(res) {
                        var tp = new Number(res.product.priceTireExact);
                        var tppm = new Number(res.product.pricePerMonthExact);

                        $("#tirepricebig_" + itmid + "_" + tireid).html(res.product.priceTireTotal);
                        $("#tireprice_" + itmid + "_" + tireid).html(res.product.priceTire);
                        $("#tirepricepaym_" + itmid + "_" + tireid).html(res.product.pricePerMonth + ":-");
                        $("#tirepricepaymperiod_" + itmid + "_" + tireid).html(res.product.periodMonths);

                        if (res.product.periodMonths < 36) {
                            $("#tirenoint_" + itmid + "_" + tireid).show();
                        } else {
                            $("#tirenoint_" + itmid + "_" + tireid).hide();
                        }
                    });
                });
            });
        }
        loadingHide(document.getElementById('loading'));
    }
}

function selectPostsPerPage(n) {
    if (n != selectedPostsPerPage) {
        selectedPostsPerPage = n;
        submitSearch(1, null, 0, false);
    }
}

function selectSortIndex(n) {
    if (n != selectedSortIndex) {
        selectedSortIndex = n;
        submitSearch(1, null, 0, false);
    }
}

function selectAccessorySortIndex(n) {
    location.href = "/tillbehor/Default.aspx?typeId=" + accTypeId + "&sortIndex=" + n;
}

function btnAccessoryClickBuy(itmid, that) {
    var qty = $("#qty_" + itmid).val();
    var pid = $("#id_" + itmid).val();

    var discountPresent = false;
    for (var k = 0; k < arrPrdDisc.length; k++) {
        if (arrPrdDisc[k] == pid) {
            discountPresent = true;
            break;
        }
    }

    addToCart(pid, qty, 0, discountPresent);
    $("#injectQty").html(qty);
    showHoverMsgQty(that);
    setTimeout("hideHoverMsgQty()", 2200);
}

function changeAccessoryQuantity(tb, itmid) {
    var qty = tb.value;
    qty = (qty.length > 0) ? new Number(qty) : 0;

    var price = $("#price_" + itmid).val();

    // show "kr/st" instead of "kr/1st"
    qtystring = (qty == 1) ? "" : qty;

    var discountPresent = false;
    for (var k = 0; k < arrPrdDisc.length; k++) {
        if (arrPrdDisc[k] == itmid) {
            discountPresent = true;
            break;
        }
    }

    if (discountPresent == true) {
        // visa priset annorlunda bara + flagga
        var pricediscount = $("#pricediscount_" + itmid).val();
        $("#pricebig_" + itmid).html("<strike style='color:#808080'>" + Math.round(price * qty) + ":-</strike> <span style='color:#ff0000'>" + Math.round(pricediscount * qty) + ":-<span style='color:black; font-size:12px;'> /" + qtystring + " st</span></span>");
        $("#pricesmall_" + itmid).html("(<strike style='color:#808080'>" + price + ":-</strike> <span style='color:#ff0000'>" + pricediscount + ":-<span style='color:black;'> /st</span> inkl. moms)");
    } else {
        $("#pricebig_" + itmid).html(Math.round(price * qty) + ":-<span style='color:black; font-size:12px;'> /" + qtystring + "st</span>");
        $("#pricesmall_" + itmid).html("(" + price + ":-<span style=\"color:black;\"> /st</span> inkl. moms)");
    }
}

function selectListType(n) {
    if (n != selectedListType) {
        $("#lt" + n).css("background-image", "url(/Img/rim_search/listtype_" + n + "_1.png)");
        $("#lt" + selectedListType).css("background-image", "url(/Img/rim_search/listtype_" + selectedListType + "_0.png)");
        selectedListType = n;
        submitSearch(1, null, 0, false);
    }
}

function switchPage(page) {
    resetSearch = 1;
    pageGoto = page;

    var thisSearchBrand = $("#" + rs_asp_id_prefix + "ddlBrands").val();
    var thisSearchModel = $("#" + rs_asp_id_prefix + "ddlModels").val();
    var thisSearchBoltCircle = ($("#" + rs_asp_id_prefix + "divStep2boltCircle").css("display") == "none") ? "0" : $("#" + rs_asp_id_prefix + "ddlBoltCircle").val();
    var thisSearchSize = $("#" + rs_asp_id_prefix + "ddlSize").val();
    var thisSearchManufacturer = $("#" + rs_asp_id_prefix + "ddlManufacturer").val();

    if (thisSearchBrand != prevSearchBrand) {
        $("#" + rs_asp_id_prefix + "ddlBrands").selectedValue(prevSearchBrand);
        selectBrand($("#" + rs_asp_id_prefix + "ddlBrands").get(0));
    } else if (thisSearchModel != prevSearchModel) {
        selectModel2(prevSearchModel);
    } else if (thisSearchBoltCircle != prevSearchBoltCircle) {
        selectBoltCircle();
    } else if (thisSearchSize != prevSearchSize) {
        selectInch();
    } else if (thisSearchManufacturer != prevSearchManufacturer) {
        $("#" + rs_asp_id_prefix + "ddlManufacturer").selectedValue(prevSearchManufacturer);
        submitSearch(page, null, 0, false);
    } else {
        // nothing's changed, just submit
        submitSearch(page, null, 0, false);
    }

    document.getElementById('divMainPageContents').scrollTop = 0;
}

function submitSearchPrecise(page, productGroupId, inchSize, offer, width, withoutRimSelect) {
    submitSearch(page, productGroupId, inchSize+"&width="+width, offer, withoutRimSelect);
}

function submitSearch(page, productGroupId, inchSize, offer, withoutRimSelect) {
    // scroll to top of page
    //window.scroll(0, 0);
    var seasonSearch = 0; //Should be taken from the season choice, that customer made..
    
    var modelId = $("#" + rs_asp_id_prefix + "ddlModels").val();

    if (withoutRimSelect == null) withoutRimSelect = false;
    if (modelId == 0) modelId = 999;

    //var srcBtnImg = $("#" + rs_asp_id_prefix + "divSearchBtn").attr("src");
    var srcBtnImg = document.getElementById(rs_asp_id_prefix + "divSearchBtn").style.backgroundImage;
    $(".nocar").fadeOut(1000);
    $("#noOffers").fadeOut(1000);
    $("#seoTextNoIntro").fadeOut(1000);

    if ($("#" + rs_asp_id_prefix + "ddlSize").get(0).length <= 1 && modelId != 999) {
        // car selected but no inches, so no rims connected
        $("#" + rs_asp_id_prefix + "norimsconnected").show();
        hideSearchBtn("Den här bilmodellen har speciella förutsättningar för att få fälgarna att passa.\nRing oss så hjälper vi dig att hitta rätt fälgar till din bil.");
        $("#searchResults").html("");
        $("#pager1").hide();
        $("#pager2").hide();
    } else if (document.getElementById(rs_asp_id_prefix + "hdBtn").value == '1' || (productGroupId != null && productGroupId > 0)) {
        loadingShow("Söker fälgar...", document.getElementById('loadingtxt'), document.getElementById('loading'));
        var bcid = ($("#" + rs_asp_id_prefix + "divStep2boltCircle").css("display") == "none") ? "0" : $("#" + rs_asp_id_prefix + "ddlBoltCircle").val();
        var qs = "?brandId=" + $("#" + rs_asp_id_prefix + "ddlBrands").val()
		               + "&modelId=" + modelId
		               + "&boltCircle=" + bcid
		               + "&productGroupIdProductType=" + productGroupTypeId
		               + "&productGroupIdManufacturer=" + $("#" + rs_asp_id_prefix + "ddlManufacturer").val()
		               + "&inch=" + (productGroupId != null ? inchSize : (document.getElementById(rs_asp_id_prefix + 'ddlSize')[document.getElementById(rs_asp_id_prefix + 'ddlSize').selectedIndex].value))
                       + "&payment=" + selectedPaymentPeriod
                       + "&ppp=" + selectedPostsPerPage
                       + "&p=" + page
                       + "&sortIndex=" + selectedSortIndex
                       + "&woRimSel=" + withoutRimSelect
                       + "&season=" + seasonSearch
                       + "&sc=1";

        var url;
        if (selectedListType == 0) {
            url = "/Rim/ListThumbs.aspx" + qs;
        } else if (selectedListType == 1) {
            url = "/Rim/ListList.aspx" + qs;
        } else if (selectedListType == 2) {
            url = "/Rim/ListDetail.aspx" + qs;
        }
        if (productGroupId != null)
            url += "&productGroupId=" + productGroupId;

        offerSearch = offer;
		
		if (offer == true)
            url += "&offer=true";
        else
            url += "&offer=false";

        $.get(url, function(res) {
            $("#searchResults").html(res);
            if (productGroupId > 0 && $("#rimsearchPages_Posts").html() == "1") {
                $("#noOffers").hide();
            }
            else if (productGroupId > 0 && $("#rimsearchPages_Posts").html() != "1") {
                $("#noOffers").show();
            } else
                $("#noOffers").hide();

            loadingHide(document.getElementById('loading'));

            prevSearchBrand = $("#" + rs_asp_id_prefix + "ddlBrands").val();
            prevSearchModel = modelId;
            prevSearchBoltCircle = bcid;
            prevSearchSize = $("#" + rs_asp_id_prefix + "ddlSize").val();
            prevSearchManufacturer = $("#" + rs_asp_id_prefix + "ddlManufacturer").val();
            resetSearch = 0;

            var noOfPages = new Number($("#rimsearchPages_TotalPages").html());
            if (noOfPages > 1) {
                loadingShow("Laddar navigation...", document.getElementById('loadingtxt'), document.getElementById('loading'));

                $("#pager1").show();
                $("#pager2").show();
                $.get("/Common/VehicleDataHandler.ashx?action=getPagerLinks2&page=" + $("#rimsearchPages_CurrentPage").html() + "&pages=" + $("#rimsearchPages_TotalPages").html() + "&posts=" + $("#rimsearchPages_Posts").html(), function(res) {
                    $("#pager1").html(res);
                    $("#pager2").html(res);
                    loadingHide(document.getElementById('loading'));
                });
            } else {
                $("#pager1").hide();
                $("#pager2").hide();
            }

            if (initialScroll > 0) {
                setTimeout("document.getElementById('divMainPageContents').scrollTop=" + initialScroll, 500);
                initialScroll = 0;
            }

            switchVehicleModel(modelId);
        });
    } else {
        alert(noSearchMsg);
    }
}

function btnClickBuy(itmid, that, withoutRimSelect) {
    var qty = $("#qty_" + itmid).val();
    var pid = $("#id_" + itmid).val();
    var modelid = $("#" + rs_asp_id_prefix + "ddlModels").val();
    if (withoutRimSelect == null) withoutRimSelect = false;

    if ((modelid == "999" || modelid == "0") && offerSearch == true) {
        $("#selectCarModal").show();
    } else {
        var accessoryPresent = false;
        for (var k = 0; k < arrPrdAcc.length; k++) {
            if (arrPrdAcc[k] == pid) {
                accessoryPresent = true;
                break;
            }
        }

        if (accessoryPresent == true) {
            // show popup
            $("#accessoryPop").show();
            $("#modalOverlay").show();

            // get name of selected car
            var brandDdl = $("#" + rs_asp_id_prefix + "ddlBrands").get(0);
            var modelDdl = $("#" + rs_asp_id_prefix + "ddlModels").get(0);
            var brand = brandDdl[brandDdl.selectedIndex].text;
            var model = modelDdl[modelDdl.selectedIndex].text;
            var modelId = $("#" + rs_asp_id_prefix + "ddlModels").val();

            // title
            $("#acessoryPopTitle").html("Följande tillbehör/tjänster behövs för att produkten skall passa på: " + brand + " " + model);
            $("#acessoryPopItemId").val(itmid);

            // get accessory list
            $("#acessoryPopList").html("<span style='font-style:italic;color:#808080;padding-left:8px'>Laddar tillbehör...</span>");
            $.get("/Rim/AccessoryList.aspx?modelid=" + modelId + "&productid=" + pid + "&qty=" + qty, function(res) {
                $("#acessoryPopList").html(res);
            });
        } else {
            var discountPresent = false;
            for (var k = 0; k < arrPrdDisc.length; k++) {
                if (arrPrdDisc[k] == pid) {
                    discountPresent = true;
                    break;
                }
            }

            addToCart(pid, qty, modelid, discountPresent, withoutRimSelect);
            $("#injectQty").html(qty);
            showHoverMsgQty(that);
            setTimeout("hideHoverMsgQty()", 2200);
        }
    }
}

function btnClickBuyAccessories(that) {
    // get data
    var itmid = $("#acessoryPopItemId").val();
    var qty = $("#qty_" + itmid).val();
    var pid = $("#id_" + itmid).val();
    var price = $("#price_" + itmid).val();
    var modelid = $("#" + rs_asp_id_prefix + "ddlModels").val();

    // add the actual rim to cart
    var productIds = pid + "|";
    var qtys = qty + "|";

    // loop through accessories
    $("#acessoryPopList #acctbl tr td .acccount").each(function() {
        // get accessory data
        var accpid = this.id.replace("acccount_", "");
        var acccount = this.innerHTML;
        // add accessory to cart
        productIds += accpid + "|";
        qtys += acccount + "|";
    });

    addToCartMultiple(productIds, qtys, modelid, true)

    $("#injectQty").html(qty);
    showHoverMsgQty(that);
    setTimeout("multipleByersBoul('" + that.id + "')", 2200);
}

function multipleByersBoul(that) {
    // hide pop            
    $("#modalOverlay").hide()
    $("#accessoryPop").hide();
    hideHoverMsgQty(document.getElementById(that));
}

function btnClickBuyTire(itmid, tireid, disc, that, withoutRimSelect) {
    // get data
    var pid = $("#id_" + itmid).val();
    var qty = $("#qty_" + itmid).val();
    var modelid = $("#" + rs_asp_id_prefix + "ddlModels").val();

    if (withoutRimSelect == null) withoutRimSelect = false;

    var accessoryPresent = false;
    for (var k = 0; k < arrPrdAcc.length; k++) {
        if (arrPrdAcc[k] == pid) {
            accessoryPresent = true;
            break;
        }
    }

    if (accessoryPresent == true) {
        // show popup
        $("#accessoryPopTire").show();
        $("#modalOverlay").show();

        // get name of selected car
        var brandDdl = $("#" + rs_asp_id_prefix + "ddlBrands").get(0);
        var modelDdl = $("#" + rs_asp_id_prefix + "ddlModels").get(0);
        var brand = brandDdl[brandDdl.selectedIndex].text;
        var model = modelDdl[modelDdl.selectedIndex].text;
        var modelId = $("#" + rs_asp_id_prefix + "ddlModels").val();

        // title
        $("#acessoryPopTireTitle").html("Följande tillbehör/tjänster behövs för att fälgen skall passa på: " + brand + " " + model);
        $("#acessoryPopTireItemId").val(itmid);
        $("#acessoryPopTireTireId").val(tireid);
        $("#acessoryPopTireDiscount").val(disc);

        // get accessory list
        $("#acessoryPopTireList").html("<span style='font-style:italic;color:#808080;padding-left:8px'>Laddar tillbehör...</span>");
        $.get("/Rim/AccessoryList.aspx?modelid=" + modelId + "&productid=" + pid + "&qty=" + qty, function(res) {
            $("#acessoryPopTireList").html(res);
        });

    } else {
        // add the rim and tire to cart
        var productIds = pid + "|" + tireid + "|";
        var qtys = qty + "|" + qty + "|";

        addToCartMultiple(productIds, qtys, modelid, disc, withoutRimSelect)
        $("#injectQty").html(qty);
        showHoverMsgQty(that);
        setTimeout("multipleByersBoul('" + that.id + "')", 2200);
    }
}

function btnClickBuyAccessoriesAndTires(that) {
    // get data
    var itmid = $("#acessoryPopTireItemId").val();
    var pid = $("#id_" + itmid).val();
    var tireid = $("#acessoryPopTireTireId").val();
    var disc = $("#acessoryPopTireDiscount").val();
    var qty = $("#qty_" + itmid).val();
    var modelid = $("#" + rs_asp_id_prefix + "ddlModels").val();

    // add the rim and tire to cart
    var productIds = pid + "|" + tireid + "|";
    var qtys = qty + "|" + qty + "|";

    // loop through accessories
    $("#acessoryPopTireList #acctbl tr td .acccount").each(function() {
        // get accessory data
        var accpid = this.id.replace("acccount_", "");
        var acccount = this.innerHTML;
        // add accessory to cart
        productIds += accpid + "|";
        qtys += acccount + "|";
    });

    addToCartMultiple(productIds, qtys, modelid, disc)
    $("#injectQty").html(qty);
    showHoverMsgQty(that);
    setTimeout("multipleByersBoul('" + that.id + "')", 2200);

    // hide pop
    $("#accessoryPopTire").hide();
    $("#modalOverlay").hide()
}

function showAccessoryFlagTooltip(d, itmid) {
    $("#accessoryFlagList").html("<span style='font-style:italic;color:#808080'>Laddar tillbehör...</span>");
    showHoverAccessoryFlag(d);
    var tooltipTopBefore = $('#tooltip_AccessoryFlag').position().top;
    var scrollTopBefore = $(document).scrollTop();

    var qty = $("#qty_" + itmid).val();
    var pid = $("#id_" + itmid).val();
    var modelId = $("#" + rs_asp_id_prefix + "ddlModels").val();

    // get accessory list
    $.get("/Rim/AccessoryListTooltip.aspx?modelid=" + modelId + "&productid=" + pid + "&qty=" + qty, function(res) {
        var textHeightBefore = $("#accessoryFlagList").outerHeight();
        $("#accessoryFlagList").html(res);
        var textHeightAfter = $("#accessoryFlagList").outerHeight();

        // move the tooltip up by as many rows that were now added (added after the tooltip was positioned)
        if ($.browser.msie) {
            //include scroll top as well, but only in ie
            $("#tooltip_AccessoryFlag").css("top", (tooltipTopBefore + scrollTopBefore) + (textHeightBefore - textHeightAfter) + "px");
        } else {
            $("#tooltip_AccessoryFlag").css("top", tooltipTopBefore + (textHeightBefore - textHeightAfter) + "px");
        }
    });
}

function switchInchDetail(pid, inch, widths, withoutRimSelect) {
    contScrollBefore = document.getElementById('divMainPageContents').scrollTop;

    $("#widths_" + pid).html("");
    $.each($("#inches_" + pid + " > div"), function() {
        var classname = ($(this).html() == inch) ? "inch1" : "inch0";
        $(this).attr("class", classname);
    });

    showRimInFlash(pid, $("#pictureflashid_" + pid).val());
    var arrWidths = widths.split(":");

    if (arrWidths.length == 1) {
        $("#widthlabel_" + pid).hide();
        $("#widths_" + pid).hide();

        var widthValue = arrWidths[0].split("|");
        switchWidthDetail(pid, widthValue[0], widthValue[1], false, withoutRimSelect);
        setTimeout("document.getElementById('divMainPageContents').scrollTop=" + contScrollBefore, 500);
    } else {
        $("#widthlabel_" + pid).show();
        $("#widths_" + pid).show();

        for (var i = 0; i < arrWidths.length; i++) {
            var widthValue = arrWidths[i].split("|");
            $("#widths_" + pid).append("<div class=\"inch0\" onclick=\"switchWidthDetail(" + pid + ",'" + widthValue[0] + "','" + widthValue[1] + "',true)\">" + widthValue[0] + "</div>");
            if (i == 0) switchWidthDetail(pid, widthValue[0], widthValue[1], false);
        }
        //setTimeout("document.getElementById('divMainPageContents').scrollTop=" + contScrollBefore, 500);
    }
}

function switchWidthDetail(pid, width, pidw, doScroll, withoutRimSelect) {
    if (doScroll == true) {
        contScrollBefore = document.getElementById('divMainPageContents').scrollTo;
    }

    loadingShow("Byter storlek...", document.getElementById('loadingtxt'), document.getElementById('loading'));

    $("#id_" + pid).val(pidw);
    var qty = $("#qty_" + pid).val();
    qty = (qty.length > 0) ? new Number(qty) : 0;

    $.each($("#widths_" + pid + " > div"), function() {
        var classname = ($(this).html() == width) ? "inch1" : "inch0";
        $(this).attr("class", classname);
    });

    // ajax-call that fetches price etc for product with id pidw
    $.getJSON("/Common/VehicleDataHandler.ashx?action=getProductBasicData&id=" + pidw, function(res) {
        if (res.result.IsOk == true) {
            var p = new Number(res.product.SellingPriceVat);

            // show "kr/st" instead of "kr/1st"
            qtystring = (qty == "1") ? "" : qty;

            $("#price_" + pid).val(p);
            $("#name_" + pid).html(res.product.Name);
            $("#desc_" + pid).html(res.description);

            if ($("#tiredisplay_" + pid).val() == "1") {
                $("#tiredisplay_" + pid).val("0")
                fetchRimTires(pid, false, withoutRimSelect);
            }

            var accessoryPresent = false;
            for (var k = 0; k < arrPrdAcc.length; k++) {
                if (arrPrdAcc[k] == pidw) {
                    accessoryPresent = true;
                    break;
                }
            }

            if (accessoryPresent == true) {
                $("#accessories_" + pid).show();
            } else {
                $("#accessories_" + pid).hide();
            }

            var discountPresent = false;
            for (var k = 0; k < arrPrdDisc.length; k++) {
                if (arrPrdDisc[k] == pidw) {
                    getDiscountPrice(pid, pidw, qty, qtystring, p);
                    discountPresent = true;
                    break;
                }
            }

            if (discountPresent == false) {
                $.getJSON("/Common/ProductDataHandler.ashx?action=getProductQuantityPrice&id=" + pidw + "&period=" + selectedPaymentPeriod + "&qty=" + qty, function(res) {
                    if (res.result.IsOk == true) {
                        $("#pricebig_" + pid).html(res.product.priceTotal + ":-<span style='color:black; font-size:12px;'> /" + qtystring + " st</span>");
                        $("#pricesmall_" + pid).html("(" + res.product.price + ":-<span style='color:black;'> /st</span> inkl. moms)");
                        $("#discountflag_" + pid).hide();

                        if (res.product.periodMonths < 36) {
                            $("#pricepaym_" + pid).html(res.product.pricePerMonth + ":-<span style='color:black; font-size:12px;'> /mån</span> Räntefri");
                        } else {
                            $("#pricepaym_" + pid).html(res.product.pricePerMonth + ":-<span style='color:black; font-size:12px;'> /mån</span>");
                        }
                        $("#paymperiod_" + pid).html("Delbetalning " + res.product.periodMonths + " mån");
                        $("#pricepermonth_" + pid).val(res.product.pricePerMonthExact);
                    }
                });
            }

            // change id in the link href to /fälg/detalj/
            var lnkhref = $("#lnk_" + pid).attr("href");
            lnkhref = lnkhref.replace(/inch=[0-9]+/, "inch=" + res.product.RimInch);
            lnkhref = lnkhref.replace(/width=[0-9\,\.]+/, "width=" + width);
            lnkhref = lnkhref.replace(/Detalj\/[a-z0-9\-]+\/[0-9]+/i, "Detalj/" + res.urlname + "/" + res.product.ProductGroupId);
            $("#lnk_" + pid).attr("href", lnkhref);
        }

        loadingHide(document.getElementById('loading'));
        if (doScroll == true) {
            setTimeout("document.getElementById('divMainPageContents').scrollTop=" + contScrollBefore, 500);
        }
    });
}

function changeQuantityDetail(tb, itmid) {
    var qty = tb.value;
    qty = (qty.length > 0) ? new Number(qty) : 0;

    var pid = $("#id_" + itmid).val();
    var price = $("#price_" + itmid).val();

    // show "kr/st" instead of "kr/1st"
    qtystring = (qty == 1) ? "" : qty;

    var discountPresent = false;
    for (var k = 0; k < arrPrdDisc.length; k++) {
        if (arrPrdDisc[k] == pid) {
            getDiscountPrice(itmid, pid, qty, qtystring, price);
            discountPresent = true;
            break;
        }
    }

    if (discountPresent == false) {
        $.getJSON("/Common/ProductDataHandler.ashx?action=getProductQuantityPrice&id=" + pid + "&period=" + selectedPaymentPeriod + "&qty=" + qty, function(res) {
            if (res.result.IsOk == true) {
                $("#pricebig_" + itmid).html(res.product.priceTotal + ":-<span style='color:black; font-size:12px;'> /" + qtystring + " st</span>");
                $("#pricesmall_" + itmid).html("(" + res.product.price + ":-<span style='color:black;'> /st</span> inkl. moms)");

                if (res.product.periodMonths < 36) {
                    $("#pricepaym_" + itmid).html(res.product.pricePerMonth + ":-<span style='color:black; font-size:12px;'> /mån</span> Räntefri");
                } else {
                    $("#pricepaym_" + itmid).html(res.product.pricePerMonth + ":-<span style='color:black; font-size:12px;'> /mån</span>");
                }
                $("#paymperiod_" + itmid).html("Delbetalning " + res.product.periodMonths + " mån");
                $("#pricepermonth_" + itmid).val(res.product.pricePerMonthExact);
            }
        });
    }

    $("#tirelstrimqty_" + itmid).html(qty);
    $("#tirelstrimqty2_" + itmid).html(qty);

    $.each($("#tires_" + itmid).find(".tirelistvehiclerim .tirelisttbl .tirelistitm"), function() {
        var tireid = this.id.replace("tireitm_" + itmid + "_", "");

        $.getJSON("/Common/VehicleDataHandler.ashx?action=getTireAndRimPaymentPeriodPrice&id=" + tireid + "&period=" + selectedPaymentPeriod + "&qty=" + qty + "&rimqty=" + qty + "&rimprice=" + price, function(res) {
            $("#tireqty1_" + itmid + "_" + tireid).html(qty);
            $("#tireqty2_" + itmid + "_" + tireid).html(qty);
            $("#tireprice_" + itmid + "_" + tireid).html(res.product.priceTire);
            $("#tirepricetot_" + itmid + "_" + tireid).html(res.product.priceTotal + ":-");
            $("#tirepricepaym_" + itmid + "_" + tireid).html(res.product.pricePerMonth + ":-");
            $("#tirepricepaymperiod_" + itmid + "_" + tireid).html(res.product.periodMonths);

            if (res.product.periodMonths < 36) {
                $("#tirenoint_" + itmid + "_" + tireid).show();
            } else {
                $("#tirenoint_" + itmid + "_" + tireid).hide();
            }
        });
    });
}

function getDiscountPrice(itmid, pid, qty, qtystring, p) {
    loadingShow("Hämtar reapris...", document.getElementById('loadingtxt'), document.getElementById('loading'));
    $.ajax({
        type: "GET",
        url: "/Common/ProductDataHandler.ashx?action=getDiscountPrice&id=" + pid + "&qty=" + qty + "&period=" + selectedPaymentPeriod,
        dataType: "json",
        success: function(res, textStatus) {
            if (res.result.IsOk == true) {
                $("#pricebig_" + itmid).html("<strike style='color:#808080'>" + res.product.priceTotal + ":-</strike> <span style='color:#ff0000'>" + res.product.discountPriceTotal + ":-<span style='color:black; font-size:12px;'> /" + qtystring + " st</span></span>");
                $("#pricesmall_" + itmid).html("(<strike style='color:#808080'>" + res.product.price + ":-</strike> <span style='color:#ff0000'>" + res.product.discountPrice + ":-<span style=\"color:black;\"> /st</span></span> inkl. moms)");
                $("#pricediscount_" + itmid).val(res.product.discountPriceExact);

                if (selectedPaymentPeriodMonths < 36) {
                    $("#pricepaym_" + itmid).html(res.product.pricePerMonth + ":-<span style='color:black; font-size:12px;'> /mån</span> Räntefri");
                } else {
                    $("#pricepaym_" + itmid).html(res.product.pricePerMonth + ":-<span style='color:black; font-size:12px;'> /mån</span>");
                }
                $("#paymperiod_" + itmid).html("Delbetalning " + res.product.periodMonths + " mån");
                $("#discountflag_" + itmid).show();
            }
            loadingHide(document.getElementById('loading'));
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            loadingHide(document.getElementById('loading'));
        }
    });
}

function setPaymentPeriodPrice(itmid, pid) {
    var qty = $("#qty_" + itmid).val();

    $.getJSON("/Common/VehicleDataHandler.ashx?action=getPaymentPeriodPrice&id=" + pid + "&period=" + selectedPaymentPeriod + "&qty=" + qty, function(res) {
        var p = new Number(res.product.priceExact);
        var ppm = new Number(res.product.pricePerMonthExact);
        if (res.product.periodMonths < 36) {
            $("#pricepaym_" + itmid).html(res.product.pricePerMonth + ":-<span style='color:black; font-size:12px;'> /mån</span> Räntefri");
        } else {
            $("#pricepaym_" + itmid).html(res.product.pricePerMonth + ":-<span style='color:black; font-size:12px;'> /mån</span>");
        }
        $("#paymperiod_" + itmid).html("Delbetalning " + res.product.periodMonths + " mån");
        $("#pricepermonth_" + itmid).val(res.product.pricePerMonthExact);
    });
}

function changeTireQuantity(itmid, tb, tireid) {
    var rimqty = $("#qty_" + itmid).val();
    var rimprice = $("#price_" + itmid).val();

    var qty = tb.value;
    qty = (qty.length > 0) ? new Number(qty) : 0;

    $.getJSON("/Common/VehicleDataHandler.ashx?action=getTireAndRimPaymentPeriodPrice&id=" + tireid + "&period=" + selectedPaymentPeriod + "&qty=" + qty + "&rimqty=" + rimqty + "&rimprice=" + rimprice, function(res) {
        var p = new Number(res.product.price);
        var ppm = new Number(res.product.pricePerMonth);
        $("#tireqty_" + itmid + "_" + tireid).html(qty);
        $("#tirepricebig_" + itmid + "_" + tireid).html(Math.round(p * qty));
        $("#tirepricepaym_" + itmid + "_" + tireid).html(Math.round(ppm) + ":-");
    });
}

function fetchRimTires(itmid, doScroll, withoutRimSelect) {
    if ($("#tiredisplay_" + itmid).val() == "0") {
        if (doScroll == true) {
            contScrollBefore = document.getElementById('divMainPageContents').scrollTop;
        }
        loadingShow("Laddar däck...", document.getElementById('loadingtxt'), document.getElementById('loading'));

        // hide previous tirelist
        if (tireListShown > 0) {
            $("#tires_" + tireListShown).html("");
            $("#tiredisplay_" + tireListShown).val("0");
            tireListShown = 0;
        }

        var inch = 16;
        $.each($("#inches_" + itmid + " > div"), function() {
            if ($(this).attr("class") == "inch1") {
                inch = $(this).html();
            }
        });

        var pid = $("#id_" + itmid).val();
        var modelid = getSelectedModelId();
        var prdgrpid = defaultTirePrdGrpId;
        var prio = 1;
        var rimname = $("#name_" + itmid).html();
        var qty = $("#qty_" + itmid).val();
        //var price = $("#price_" + itmid).val();

        var price = $("#pricediscount_" + itmid).val();
        if (price == '0')
            price = $("#price_" + itmid).val();

        var url = "/Tire/ListVehicleRim.aspx";

        $.get(url, { "itmid": itmid, "productid": pid, "modelid": modelid, "productgroupid": prdgrpid, "prio": prio, "qty": qty, "inch": inch, "rimname": rimname, "paymentmonths": selectedPaymentPeriodMonths, "rimprice": price, "sortIndex": selectedSortIndex, "woRimSel": withoutRimSelect }, function(res) {
            $("#tires_" + itmid).html(res);
            $("#tiredisplay_" + itmid).val("1");
            tireListShown = itmid;
            loadingHide(document.getElementById('loading'));

            if (doScroll == true) {
                setTimeout("document.getElementById('divMainPageContents').scrollTop=" + contScrollBefore, 500);
            }
        });
    } else {
        $("#tires_" + itmid).html("");
        $("#tiredisplay_" + itmid).val("0");
    }
}

function fetchRimTiresType(itmid, prdgrpid, prio, tblid, inch, rimprice, withoutRimSelect) {
    loadingShow("Laddar däck...", document.getElementById('loadingtxt'), document.getElementById('loading'));
    $("#tiremsg_" + itmid).html("Laddar däck...");
    $("#tirelisttbl_" + itmid).hide();
    if (prio == null)
        prio = 0;

    var pid = $("#id_" + itmid).val();
    var modelid = getSelectedModelId();
    var rimname = $("#name_" + itmid).html();
    var qty = $("#qty_" + itmid).val();
    //var price = $("#price_" + itmid).val();

    var price = $("#pricediscount_" + itmid).val();
    if (price == '0')
        price = $("#price_" + itmid).val();

    var url = "/Tire/ListVehicleRim.aspx";

    $.get(url, { "itmid": itmid, "productid": pid, "modelid": modelid, "productgroupid": prdgrpid, "prio": prio, "qty": qty, "inch": inch, "rimname": rimname, "paymentmonths": selectedPaymentPeriodMonths, "rimprice": price, "sortIndex": selectedSortIndex, "woRimSel": withoutRimSelect }, function(res) {
        $("#tires_" + itmid).html(res);
        loadingHide(document.getElementById('loading'));
    });
}

function showRimInFlash(itmid, fid) {
    pageTracker._trackPageview("falg-pa-bil");

    var inch = 16;
    $.each($("#inches_" + itmid + " > div"), function() {
        if ($(this).attr("class") == "inch1") {
            inch = $(this).html();
        }
    });
    setRimSize(inch);
    
    var pid = $("#id_" + itmid).val();
    if (pid != rimProductShownInFlash) {
        rimProductShownInFlash = pid;

        var rimFileToShowInFlash;
        if (fid > 0) {
            rimFileToShowInFlash = "/picture/product/prd" + fid + ".swf";
        } else {
            rimFileToShowInFlash = "/flash/DefaultRim.swf";
        }

        if (rimFileToShowInFlash != rimFileShownInFlash) {
            transferRimToFlash(rimFileToShowInFlash);
            rimFileShownInFlash = rimFileToShowInFlash;
        }
    }
}

function switchMoreImages(pid) {
    if ($("#tooltip_MoreRimImages" + pid).css("top") != "-1000px") {
        var imagesTotal = new Number($("#imgno_" + pid + "_total").html());
        var activeImage = new Number($("#imgno_" + pid + "_active").html());

        var nextImage = activeImage + 1;
        if (nextImage > imagesTotal) nextImage = 1;

        $("#img_" + pid + "_" + activeImage).fadeOut(500);
        $("#img_" + pid + "_" + nextImage).fadeIn(500);

        $("#imgno_" + pid + "_active").html(nextImage);

        clearTimeout(moreImagesTimer);
        moreImagesTimer = setTimeout("switchMoreImages(" + pid + ")", 2000);
    }
}

function showHoverBuyTire(btn, itmid) {
    var qty = $("#qty_" + itmid).val();
    $("#buytiretooltip_qty1").html(qty);
    $("#buytiretooltip_qty2").html(qty);
    showHoverBuyTirePack(btn);
}

function carModalSelectBrand(ddl) {
    var brandId = ddl[ddl.selectedIndex].value

    loadingShow("Hämtar bilmodeller...", document.getElementById("loadingtxt"), document.getElementById("loading"));
    $("#selectCarModalDdlModels").html('<option value="-1">Laddar...</option>');
    $("#selectCarModalDdlModels").addSelectOptions("/Common/VehicleDataHandler.ashx?action=vehicleModelsByBrandForDropdown&includeAll=false&excludeSelModel=true&includeSelect=false&brandId=" + brandId, function() {
        loadingHide(document.getElementById("loading"));
    });
}

function selectCarModalDoSelect(brandDdl, modelDdl) {
    var brandId = $("#" + brandDdl).val();
    var modelId = $("#" + modelDdl).val();
    var url = location.href + "&brandid=" + brandId + "&modelid=" + modelId;
    location.href = url;
}
