﻿var ts_asp_id_prefix;
var DEFAULTINCH;
var DEFAULTWIDTH;
var DEFAULTPROFILE;
var searchType;
var selectedPaymentPeriodMonths;
var selectedPaymentPeriod;
var selectedPostsPerPage;
var selectedSortIndex;
var selectedListType;
var productGroupTypeId;
var rimListShown;
var noSearchMsg;
var prevSearchType;
var prevSearchBrand;
var prevSearchModel;
var prevSearchSize;
var prevSearchTireSizeRec;
var prevSearchWidth;
var prevSearchProfile;
var prevSearchManufacturer;
var resetSearch;
var pageGoto;
var hasSearched;
var initialScroll;
var offerSearch;

function showSearchFormCar() {
    searchType = 1;
    $("#divSearchByVehicle").show();
    $("#divSearchByTireSize").hide();
    
    document.getElementById(ts_asp_id_prefix + 'divTireSubMenuCar').setAttribute("class", "TireSubMenuCarActive");
    document.getElementById(ts_asp_id_prefix + 'divTireSubMenuSize').setAttribute("class", "TireSubMenuSizeInactive");
}

function showSearchFormSize(resetCar) {
    searchType = 2;
    $("#divSearchByVehicle").hide();
    $("#divSearchByTireSize").show();
    
    document.getElementById(ts_asp_id_prefix + 'divTireSubMenuCar').setAttribute("class", "TireSubMenuCarInactive");
    document.getElementById(ts_asp_id_prefix + 'divTireSubMenuSize').setAttribute("class", "TireSubMenuSizeActive");
}

function hideSearchBtn1(msg) {
    document.getElementById(ts_asp_id_prefix + "divSearchBtn1").style.backgroundImage = "url(/Img/tire_search/tireMenuSpriteBlue.png)";
    document.getElementById(ts_asp_id_prefix + "divSearchBtn1").style.backgroundPosition = '-68px -199px';
    $("#" + ts_asp_id_prefix + "divSearchBtn1").css("cursor","default");
    document.getElementById(ts_asp_id_prefix + "hdBtn1").value = '0';
    noSearchMsg = msg;
}

function hideSearchBtn2(msg) {
    document.getElementById(ts_asp_id_prefix + "divSearchBtn2").style.backgroundImage = "url(/Img/tire_search/tireMenuSpriteBlue.png)";
    document.getElementById(ts_asp_id_prefix + "divSearchBtn2").style.backgroundPosition = '-68px -199px';
    $("#" + ts_asp_id_prefix + "divSearchBtn2").css("cursor","default");
    document.getElementById(ts_asp_id_prefix + "hdBtn2").value = '0';
    noSearchMsg = msg;
}

function showSearchBtn1() {
    document.getElementById(ts_asp_id_prefix + "divSearchBtn1").style.backgroundImage = "url(/Img/tire_search/tireMenuSpriteBlue.png)";
    document.getElementById(ts_asp_id_prefix + "divSearchBtn1").style.backgroundPosition = '0px -199px';
    document.getElementById(ts_asp_id_prefix + "hdBtn1").value = '1';
    $("#" + ts_asp_id_prefix + "divSearchBtn1").css("cursor","pointer");
}

function showSearchBtn2() {
    document.getElementById(ts_asp_id_prefix + "divSearchBtn2").style.backgroundImage = "url(/Img/tire_search/tireMenuSpriteBlue.png)";
    document.getElementById(ts_asp_id_prefix + "divSearchBtn2").style.backgroundPosition = '0px -199px';
    document.getElementById(ts_asp_id_prefix + "hdBtn2").value = '1';
    $("#" + ts_asp_id_prefix + "divSearchBtn2").css("cursor","pointer");
}

function selectBrand(ddl) {
    var brandId = ddl[ddl.selectedIndex].value
    
    var modelDropId = "#" + ts_asp_id_prefix + "ddlModels";
    
    loadingShow("Hämtar bilmodeller...",document.getElementById('loadingtxt'),document.getElementById('loading'));
    $(modelDropId).html('<option value="-1">Laddar...</option>');
    $(modelDropId).addSelectOptions("/Common/VehicleDataHandler.ashx?action=vehicleModelsByBrandForDropdown&brandId=" + brandId, function() {
        loadingHide(document.getElementById('loading'));
        selectModel2($(modelDropId).val());
    });
}

function getScrollY() {
    var yScroll = document.getElementById('divMainPageContents').scrollTop();
}

function selectModel1(ddl) {
    var modelId = ddl[ddl.selectedIndex].value;
    selectModel2(modelId);
}

function selectModel2(modelId) {
    var sizeDropId = "#" + ts_asp_id_prefix + "ddlSize1";
    
    var brandId = $("#" + ts_asp_id_prefix + "ddlBrands").val();
    
    if (resetSearch==1) {
        $("#" + ts_asp_id_prefix + "ddlModels").selectedValue(prevSearchModel);
        modelId = $("#" + ts_asp_id_prefix + "ddlModels").val();
    }
    
    if (brandId==999) {
        $("#" + ts_asp_id_prefix + "ddlModels").get(0).selectedIndex = 1;
        $("#" + ts_asp_id_prefix + "ddlModels").attr("disabled", true);
    } else if (brandId==0) {
        $("#" + ts_asp_id_prefix + "ddlModels").attr("disabled", true);
    } else {
        $("#" + ts_asp_id_prefix + "ddlModels").attr("disabled", false);
    }
    
    var modelId = $("#" + ts_asp_id_prefix + "ddlModels").val();
    
    if (modelId==0) {
        if (brandId==0) {
            hideSearchBtn1("Du måste välja din bil eller [ALLA] för att kunna söka.");
        } else {
            hideSearchBtn1("Du måste även välja din bilmodell för att kunna söka.");
        }
    } else {
        if (modelId==999 && resetSearch==1) {
            selectInch2();
        } else {
            showSearchBtn1();
            
            loadingShow("Hämtar storlekar...",document.getElementById('loadingtxt'),document.getElementById('loading'));
            $(sizeDropId).html('<option value="-1">Laddar...</option>');
            $(sizeDropId).addSelectOptions("/Common/VehicleDataHandler.ashx?action=tireSizeInchesForDropdown&typeId=" + productGroupTypeId + "&modelId=" + modelId, function() {
                loadingHide(document.getElementById('loading'));
                $(sizeDropId).selectedValue(DEFAULTINCH);
                selectInch1();
            });
        }
    }
}

function selectInch1() {
    var modelId = $("#" + ts_asp_id_prefix + "ddlModels").val();

    if (resetSearch==1) {
        $("#" + ts_asp_id_prefix + "ddlSize1").selectedValue(prevSearchSize);
    }

    loadTireSizePrio();
}

function selectInch2() {
    if (resetSearch==1) {
        $("#" + ts_asp_id_prefix + "ddlSize2").selectedValue(prevSearchSize);
    }

    var inch = $("#" + ts_asp_id_prefix + "ddlSize2").val();
    
    loadingShow("Hämtar storlekar...",document.getElementById('loadingtxt'),document.getElementById('loading'));

    $("#" + ts_asp_id_prefix + "ddlWidth").addSelectOptions("/Common/VehicleDataHandler.ashx?action=tireSizeWidthForDropdown&typeId=" + productGroupTypeId + "&inch=" + inch, function() {
        $("#" + ts_asp_id_prefix + "ddlWidth").selectedValue(DEFAULTWIDTH);
        selectWidth();
    });
}

function loadTireSizePrio() {
    loadingShow("Hämtar storlekar...",document.getElementById('loadingtxt'),document.getElementById('loading'));
    
    var modelId = $("#" + ts_asp_id_prefix + "ddlModels").val();
    var inch = $("#" + ts_asp_id_prefix + "ddlSize1").val();
    
    $("#" + ts_asp_id_prefix + "ddlTireSizePrio").html('<option value="-1">Laddar...</option>');
    $("#" + ts_asp_id_prefix + "ddlTireSizePrio").addSelectOptions("/Common/VehicleDataHandler.ashx?action=vehicleModelTireSizePrioForDropdown&typeId=" + productGroupTypeId + "&modelId=" + modelId + "&inch=" + inch, function() {
        if (resetSearch==1) {
            $("#" + ts_asp_id_prefix + "ddlTireSizePrio").selectedValue(prevSearchTireSizeRec);
        }
        
        loadManufacturers(inch, "#" + ts_asp_id_prefix + "ddlManufacturer1");
    });
}

function loadManufacturers(inch, targetDropdownId) {
    loadingShow("Hämtar tillverkare...",document.getElementById('loadingtxt'),document.getElementById('loading'));
    
    var modelId = $("#" + ts_asp_id_prefix + "ddlModels").val();
    var tireSizePrio = $("#" + ts_asp_id_prefix + "ddlTireSizePrio").val();
    var width = $("#" + ts_asp_id_prefix + "ddlWidth").val();
    var tireSizePrio = $("#" + ts_asp_id_prefix + "ddlTireSizePrio").val();
    var profile = $("#" + ts_asp_id_prefix + "ddlProfile").val();
    
    if (searchType == 2) {
        modelId = 999;
        tireSizePrio = 0;
    }
    
    $(targetDropdownId).html('<option value="-1">Laddar...</option>');
    $(targetDropdownId).addSelectOptions("/Common/VehicleDataHandler.ashx?action=productGroupTireManufacturerForDropdown&typeId=" + productGroupTypeId + "&inch=" + inch + "&modelId=" + modelId + "&tireSizePrio=" + tireSizePrio + "&width=" + width + "&profile=" + profile, function() {
        loadingHide(document.getElementById('loading'));
        if (resetSearch==1) {
            $(targetDropdownId).selectedValue(prevSearchManufacturer);
            submitSearch(pageGoto);
        }
    });
}

function selectWidth() {
    loadingShow("Hämtar storlekar...",document.getElementById('loadingtxt'),document.getElementById('loading'));
    
    if (resetSearch==1) {
        $("#" + ts_asp_id_prefix + "ddlWidth").selectedValue(prevSearchWidth);
    }
    
    var inch = $("#" + ts_asp_id_prefix + "ddlSize2").val();
    var width = $("#" + ts_asp_id_prefix + "ddlWidth").val();

    $("#" + ts_asp_id_prefix + "ddlProfile").addSelectOptions("/Common/VehicleDataHandler.ashx?action=tireSizeProfileForDropdown&typeId=" + productGroupTypeId + "&inch=" + inch + "&width=" + width, function() {
        if (resetSearch==1) {
            $("#" + ts_asp_id_prefix + "ddlProfile").selectedValue(prevSearchProfile);
        } else {
            $("#" + ts_asp_id_prefix + "ddlProfile").selectedValue(DEFAULTPROFILE);
        }
        
        loadManufacturers(inch, "#" + ts_asp_id_prefix + "ddlManufacturer2");
    });
}

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) {
		    // tires
            $.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);
            });
		}
        loadingHide(document.getElementById('loading'));
	}
}

function selectPostsPerPage(n) {
	if (n != selectedPostsPerPage) {
		selectedPostsPerPage = n;
		if (hasSearched==1) submitSearch(1);
	}
}

function selectSortIndex(n) {
	if (n != selectedSortIndex) {
		selectedSortIndex = n;
		if (hasSearched==1) submitSearch(1);
	}
}

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;
		if (hasSearched==1) submitSearch(1);
	}
}

function switchPage(page) {		    
    resetSearch = 1;
    pageGoto = page;

    var thisSearchBrand = $("#" + ts_asp_id_prefix + "ddlBrands").val();
    var thisSearchModel = $("#" + ts_asp_id_prefix + "ddlModels").val();
    var thisSearchSize = (searchType==1) ? $("#" + ts_asp_id_prefix + "ddlSize1").val() : $("#" + ts_asp_id_prefix + "ddlSize2").val();
    var thisSearchTireSizeRec = $("#" + ts_asp_id_prefix + "ddlTireSizePrio").val();
    var thisSearchWidth = $("#" + ts_asp_id_prefix + "ddlWidth").val();
    var thisSearchProfile = $("#" + ts_asp_id_prefix + "ddlProfile").val();
    var thisSearchManufacturer = (searchType==1) ? $("#" + ts_asp_id_prefix + "ddlManufacturer1").val() : $("#" + ts_asp_id_prefix + "ddlManufacturer2").val();
    
    if (prevSearchType==1) {
        showSearchFormCar();
        
        if (thisSearchBrand != prevSearchBrand) {
            $("#" + ts_asp_id_prefix + "ddlBrands").selectedValue(prevSearchBrand);
            selectBrand($("#" + ts_asp_id_prefix + "ddlBrands").get(0));
        } else if (thisSearchModel != prevSearchModel) {
            selectModel2(prevSearchModel);
        } else if (thisSearchSize != prevSearchSize) {
            selectInch1();
        } else if (thisSearchTireSizeRec != prevSearchTireSizeRec) {
            loadManufacturers(thisSearchSize, (searchType==1) ? "#" + ts_asp_id_prefix + "ddlManufacturer1" : "#" + ts_asp_id_prefix + "ddlManufacturer2");
        } else if (thisSearchManufacturer != prevSearchManufacturer) {
            $("#" + ts_asp_id_prefix + "ddlManufacturer1").selectedValue(prevSearchManufacturer);
            submitSearch(page);
        } else {
            // nothing's changed, just submit
            submitSearch(page);
        }
    } else {
        showSearchFormSize(false);

        //if (thisSearchBrand != 999 || thisSearchModel != 999) {
        //    $("#" + ts_asp_id_prefix + "ddlBrands").selectedValue("999");
        //    selectBrand($("#" + ts_asp_id_prefix + "ddlBrands").get(0));
        //} else
        if (thisSearchSize != prevSearchSize) {
            $("#" + ts_asp_id_prefix + "ddlSize2").selectedValue(prevSearchSize);
            selectInch2();
        } else if (thisSearchWidth != prevSearchWidth) {
            $("#" + ts_asp_id_prefix + "ddlWidth").selectedValue(prevSearchWidth);
            selectWidth();
        } else if (thisSearchProfile != prevSearchProfile) {
            $("#" + ts_asp_id_prefix + "ddlProfile").selectedValue(prevSearchProfile);
            loadManufacturers(prevSearchSize, "#" + ts_asp_id_prefix + "ddlManufacturer2");
        } else if (thisSearchManufacturer != prevSearchManufacturer) {
            $("#" + ts_asp_id_prefix + "ddlManufacturer2").selectedValue(prevSearchManufacturer);
            submitSearch(page);
        } else {
            // nothing's changed, just submit
            submitSearch(page);
        }
    }
    document.getElementById('divMainPageContents').scrollTop = 0;
}

function submitSearchPrecise(page, productGroupId, inchSize, width, profile, withoutRimSelect) {
    submitSearch(page, productGroupId, inchSize, width, profile, withoutRimSelect, true)
}

function submitSearch(page, productGroupId, inchSize, width, profile, withoutRimSelect, offer) {
    var modelId = $("#" + ts_asp_id_prefix + "ddlModels").val();

    if (searchType==1 && modelId==999) {
        showSearchFormSize(false);
    }

    offerSearch = offer;
    
    if (withoutRimSelect == null) withoutRimSelect = false;
    if (modelId==0) modelId=999;
    
    if ((searchType==1 && document.getElementById(ts_asp_id_prefix + "hdBtn1").value == '1') ||
        (searchType==2 && document.getElementById(ts_asp_id_prefix + "hdBtn2").value == '1') || productGroupId>0) {
        loadingShow("Söker däck...",document.getElementById('loadingtxt'),document.getElementById('loading'));
	    
        if (searchType==2) {
            modelId=999;
        }
	    
        // scroll to top of page
        window.scroll(0, 0);
        $("#" + ts_asp_id_prefix + "nocar").fadeOut(1000);
        $("#seoTextNoIntro").fadeOut(1000);

        var inch = (searchType==1) ? $("#" + ts_asp_id_prefix + "ddlSize1").val() : $("#" + ts_asp_id_prefix + "ddlSize2").val();
        var manuf = (searchType==1) ? $("#" + ts_asp_id_prefix + "ddlManufacturer1").val() : $("#" + ts_asp_id_prefix + "ddlManufacturer2").val();
	    
        var qs = "?brandId=" + $("#" + ts_asp_id_prefix + "ddlBrands").val()
               + "&modelId=" + modelId
               + "&inch=" + (productGroupId!=null?inchSize:inch)
               + "&prio=" + $("#" + ts_asp_id_prefix + "ddlTireSizePrio").val()
               + "&width=" + (width==null?$("#" + ts_asp_id_prefix + "ddlWidth").val():width)
               + "&profile=" + (profile==null?$("#" + ts_asp_id_prefix + "ddlProfile").val():profile)
               + "&manufacturerId=" + manuf
               + "&productGroupIdProductType=" + productGroupTypeId
               + "&payment=" + selectedPaymentPeriod
               + "&ppp=" + selectedPostsPerPage
               + "&p=" + page
               + "&sortIndex=" + selectedSortIndex
               + "&woRimSel=" + withoutRimSelect
               + "&sc=1";

        var url;
        
        if (selectedListType == 0) {
            url = "/Tire/ListThumbs.aspx" + qs;
        } else if (selectedListType == 1) {
            url = "/Tire/ListList.aspx" + qs;
        } else if (selectedListType == 2) {
            url = "/Tire/ListDetail.aspx" + qs;
        }
        
        if(productGroupId!=null)
            url += "&productGroupId="+productGroupId;

        $.get(url, function(res) {
            $("#searchResults").html(res);
            
            loadingHide(document.getElementById("loading"));

            if (productGroupId > 0 && $("#tiresearchPages_Posts").html() != "0") {
                $("#noOffers").hide();
            }
            else if (productGroupId > 0 && $("#tiresearchPages_Posts").html() == "0") {
                $("#noOffers").show();
            } else {
                $("#noOffers").hide();
            }
	        
            prevSearchBrand = $("#" + ts_asp_id_prefix + "ddlBrands").val();
            prevSearchModel = $("#" + ts_asp_id_prefix + "ddlModels").val();
            prevSearchTireSizeRec = $("#" + ts_asp_id_prefix + "ddlTireSizePrio").val();
            prevSearchWidth = $("#" + ts_asp_id_prefix + "ddlWidth").val();
            prevSearchProfile = $("#" + ts_asp_id_prefix + "ddlProfile").val();
            prevSearchSize = (searchType==1) ? $("#" + ts_asp_id_prefix + "ddlSize1").val() : $("#" + ts_asp_id_prefix + "ddlSize2").val();
            prevSearchManufacturer = (searchType==1) ? $("#" + ts_asp_id_prefix + "ddlManufacturer1").val() : $("#" + ts_asp_id_prefix + "ddlManufacturer2").val();
            prevSearchType = searchType;
            resetSearch = 0;
            hasSearched = 1;
            
            var noOfPages = new Number($("#tiresearchPages_TotalPages").html());
            if (noOfPages > 1) {
                $.get("/Common/VehicleDataHandler.ashx?action=getPagerLinks2&page=" + $("#tiresearchPages_CurrentPage").html() + "&pages=" + $("#tiresearchPages_TotalPages").html() + "&posts=" + $("#tiresearchPages_Posts").html(), function(res) {
                    $("#pager1").show();
                    $("#pager2").show();
                    $("#pager1").html(res);
                    $("#pager2").html(res);
                });
            } else {
                $("#pager1").hide();
                $("#pager2").hide();
            }
            
            if (initialScroll > 0) {
                setTimeout("document.getElementById('divMainPageContents').scrollTop=" + initialScroll, 500);
                initialScroll = 0;
            }
	        
	        if (prevSearchModel != 0)
                switchVehicleModel(prevSearchModel);
        });
    } else if(productGroupId<=0) {
        alert(noSearchMsg);
    }
}

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) {
        loadingShow("Hämtar delbetalningspris...", document.getElementById('loadingtxt'), document.getElementById('loading'));
        $.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);
                $("#discountflag_" + itmid).hide();
                loadingHide(document.getElementById('loading'));
            }
        });
    }
}

function switchWidthDetail(pid, width, pidw, classnamepre) {
    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($("#sizes_" + pid + " > div"), function() {
        var classname = classnamepre;
        if ($(this).html() == width) {
            classname += "1";
        } else {
            // check if this width has a discount, if so, show in another color, to highlight
            var widthPid = $(this).attr("id").replace("tw","");
            var widthDiscountPresent = false;
            for (var k = 0; k < arrPrdDisc.length; k++) {
                if (arrPrdDisc[k] == widthPid) {
                    widthDiscountPresent = true;
                    break;
                }
            }
            if (widthDiscountPresent==true) {
                classname += "discount0";
            } else {
                classname += "0";
            }
        }
        $(this).attr("class",classname);
    });

    $.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);
            $("#tirelstrimqty_" + pid).html(qty);

            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) {
                loadingShow("Hämtar delbetalningspris...", document.getElementById('loadingtxt'), document.getElementById('loading'));
                $.getJSON("/Common/ProductDataHandler.ashx?action=getProductQuantityPrice&id=" + pid + "&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)");

                        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);
                        $("#discountflag_" + pid).hide();
                        loadingHide(document.getElementById('loading'));
                    }
                });
            }

            if ($("#tiredisplay_" + pid).val() == "1") {
                $("#tiredisplay_" + pid).val("0")
                fetchRimTires(pid);
            }

            // change id in the link href to /däck/detalj/
            var lnkhref = $("#lnk_" + pid).attr("href");
            lnkhref = lnkhref.replace(/inch=[0-9]+/, "inch=" + res.product.TireInch);
            lnkhref = lnkhref.replace(/Detalj\/[a-z0-9\-]+\/[0-9]+/i, "Detalj/" + res.urlname + "/" + res.product.ProductGroupId);
            $("#lnk_" + pid).attr("href", lnkhref);
        }
        else
        {
            alert(res.result.Message);
        }
        loadingHide(document.getElementById('loading'));
    }); 
    loadingHide(document.getElementById('loading'));
}

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)");

                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 getSelectedModelId() {
    return $("#" + ts_asp_id_prefix + "ddlModels").val();
}

function fetchTireRims(itmid) {
    if ($("#rimdisplay_" + itmid).val() == "0") {
        loadingShow("Laddar däck...",document.getElementById('loadingtxt'),document.getElementById('loading'));
        
        // hide previous tirelist
        if (rimListShown > 0) {
            $("#rims_" + rimListShown).html("");
            $("#rimdisplay_" + rimListShown).val("0");
            rimListShown = 0;
        }
	    
        var pid = $("#id_" + itmid).val();
        var modelid = getSelectedModelId();
        var tirename = $("#name_" + itmid).html();
        var qty = $("#qty_" + itmid).val()
        
        var url = "/Rim/ListVehicleTire.aspx";
        
        $.get(url, { "itmid":itmid, "productid":pid, "modelid":modelid, "qty":qty, "tirename":tirename, "paymentmonths":selectedPaymentPeriodMonths }, function(res) {
            $("#rims_" + itmid).html(res);
            $("#rimdisplay_" + itmid).val("1");
            rimListShown = itmid;
            loadingHide(document.getElementById('loading'));
        });
    } else {
        $("#rims_" + itmid).html("");
        $("#rimdisplay_" + itmid).val("0");
    }
}

function btnClickBuy(itmid, elem, withoutRimSelect) {
    var id = $("#id_" + itmid).val();
    var qty = $("#qty_" + itmid).val();
    var modelid = $("#" + ts_asp_id_prefix + "ddlModels").val();

    if (modelid == "0" || prevSearchType == 2) modelid = "999";
    if (withoutRimSelect == null) withoutRimSelect = false;

    if (modelid == "999" && offerSearch == true) {
        $("#selectCarModal").show();
    } else {
        var discountPresent = false;
        for (var k = 0; k < arrPrdDisc.length; k++) {
            if (arrPrdDisc[k] == id) {
                discountPresent = true;
                break;
            }
        }

        addToCart(id, qty, modelid, discountPresent, withoutRimSelect);
        $("#injectQty").html(qty);
        showHoverMsgQty(elem);

        setTimeout("hideHoverMsgQty()", 2200);
    }
}

var moreImagesTimer = 0;
function switchMoreImages(pid) {
    if ($("#tooltip_MoreTireImages" + 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 setPaymentPeriodPrice(itmid, pid) {
    var qty = $("#qty_" + itmid).val();
    loadingShow("Hämtar delbetalningspris...",document.getElementById('loadingtxt'),document.getElementById('loading'));
    $.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);
        loadingHide(document.getElementById('loading'));
    });
}

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;
}

