﻿var onCarModelsLoaded, onCarYearModelsLoaded, onCarEnginesLoaded, onCarTypeLoaded;

$(document).ready(function () {
    //CLICKARU
    $('#getCarInfoByRegistrationNoButton').click(function () {
        $.getCarInfoByRegistrationNo($('#' + this.name).val());
        $("#selectArticleGroupListHolder").hide();
    });
    $('#getCarInfoByCassiNoButton').click(function () {
        $.getCarInfoByCassiNo($('#' + this.name).val());
        $("#selectArticleGroupListHolder").hide();
    });
});

function checkCarCodeOk(cc) {
    var ret;
    switch(cc) {
        case 'XXXXXX': ret = false; break;
        case '000000': ret = false; break;
        default: ret = true;
    }

    if (!ret) {
        $('#reg_chassi_search_information span').css('display', 'block');
        $('#carInformationTable').hide();
    }
    else
        $('#reg_chassi_search_information span').css('display', 'none');

    return ret;
}

$.getCarInfoByRegistrationNo = function (str, callback, callback2) {
    $.ajaxLoadingStatus({ text: $.tr('Hämtar sökresultat, var god vänta.') });
    $.ajax({
        type: "GET",
        contentType: "application/json",
        url: '/webservices/carproductsearch.svc/GetCarInfoByRegistrationNo?registrationNo=' + str,
        dataType: "json",
        processData: false,
        success: function (p) {
            if ($.ajaxErrorHandler(p)) {
                $.ajaxLoadingStatus({ create: false, update: false });
                if (p.d.CarInformation == null) {
                    alert("Kunde inte hitta ett fordon med angivet registeringsnummer.");
                }
                else {
                    //setting input to right value
                    $('#getCarInfoByRegistrationNoInput').val(str);

                    //cookies
                    var setCookieArray = $.cookieMonster({ set: 'getCarInfoByRegistrationNoLatestSearchList', value: str });
                    $('#getCarInfoByRegistrationNoLatestSearchList').updateLatestSearchList({ trigger: $.getCarInfoByRegistrationNo, list: setCookieArray });
                    gCarCode = p.d.CarInformation.Code;
                    // remove any selected vehicle parts
                    arrSave = undefined;
                    if (checkCarCodeOk(gCarCode)) {
                        getArticleClasses();
                        getArticleClassesV2();
                    }
                    $.createCarTable(p.d.CarInformation, false, true);
                    hashSerializer.updateValues({ site: 'car', vehicleSelection: 'reg', vehicleParameters: [str], dropDownIndicator: '', searchType: '', searchParameters: [] });
                    hashSerializer.setURLHash();
                    post_hash_to_product_detail = '#/car/reg/' + str;
                    //Biding button to reset all search variables
                    $.resetAllSearchVariables();

                    if ($.isFunction(callback))
                        callback();

                    if ($.isFunction(callback2))
                        callback2();
                }
            }

            p = undefined;
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            $.showErrorMessage($.tr('Någonting gick fel när sidan försökte hämta bilinformation via registreringsnummer'));
        }
    });
}

$.getCarInfoByCassiNo = function (str, callback, callback2) {
    $.ajaxLoadingStatus({ text: $.tr('Hämtar sökresultat, var god vänta.') });
    $.ajax({
        type: "GET",
        contentType: "application/json",
        url: '/webservices/carproductsearch.svc/GetCarInfoByCassiNo?chassiNo=' + str,
        dataType: "json",
        processData: false,
        success: function (p) {
            if ($.ajaxErrorHandler(p)) {
                //cookies
                $.ajaxLoadingStatus({ create: false, update: false });
                if (p.d.CarInformations == null || p.d.CarInformations.length == 0) {
                    alert("Kunde inte ett fordon med angivet chassinummer.");
                }
                else {
                    //setting input to right value
                    $('#getCarInfoByCassiNo').val(str);

                    var setCookieArray = $.cookieMonster({ set: 'getCarInfoByCassiNoLatestSearchList', value: str });
                    $('#getCarInfoByCassiNoLatestSearchList').updateLatestSearchList({ trigger: $.getCarInfoByCassiNo, list: setCookieArray });
                    gCarCode = p.d.CarInformations[0].Code;
                    // remove any selected vehicle parts
                    arrSave = undefined;
                    cl(p.d.CarInformations)
                    if (checkCarCodeOk(gCarCode)) {
                        getArticleClasses();
                    }
                    $.createCarTable(p.d.CarInformations, true);
                    hashSerializer.updateValues({ site: 'car', vehicleSelection: 'chassi', vehicleParameters: [str], dropDownIndicator: '', searchType: '', searchParameters: [] });
                    post_hash_to_product_detail = '#/car/chassi/' + str;
                    //Biding button to reset all search variables
                    $.resetAllSearchVariables();
                    if ($.isFunction(callback))
                        callback();

                    if ($.isFunction(callback2))
                        callback2();
                }
            }

            p = undefined;
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            $.showErrorMessage($.tr('Någonting gick fel när sidan försökte hämta bilinformation via chassinummer'));
        }
    });
}

$.createCarTable = function (c, minified, reg) {
    if (gCarCode != null) {
        $("#carFreeTextSearchInput").autocomplete({
            source: function (request, response) {
                $.ajax({
                    url: "/webservices/ProductService.svc/FreeSearchAutocomplete",
                    dataType: "json",
                    data: {
                        term: request.term
                    },
                    success: function (data) {
                        response($.map(data.d, function (item) {
                            return {
                                label: item,
                                value: item
                            }
                        }));
                    }
                });
            },
            minLength: 4
        });
    }

    var $table = $('<table />');
    var $row;
    var save = new Array();
    var ok1 = true;
    var ok2 = true;
    var ok3 = true;

    if (minified != undefined)
        minified = minified;
    else
        minified = false;

    //new row 1
    $row = [$('<tr />').appendTo($table), $('<tr />').appendTo($table)];
    //filling row 1
    var str, str2, str3;
    if (c.length != undefined) {
        for (var i in c) {
            if (i == 0) {
                str = c[i].CarLookup.Brand;
                str2 = c[i].CarLookup.Model;
                str3 = c[i].CarLookup.Year;
                save[i] = c[i];
            }
            else {
                for (var s in save) {
                    if (save[s].CarLookup.Brand == c[i].CarLookup.Brand)
                        ok1 = false;

                    if (save[s].CarLookup.Model == c[i].CarLookup.Model)
                        ok2 = false;

                    if (save[s].CarLookup.Year == c[i].CarLookup.Year)
                        ok3 = false;
                }

                if (ok1)
                    str += ', ' + c[i].CarLookup.Brand;
                if (ok2)
                    str2 += ', ' + c[i].CarLookup.Model;
                if (ok3)
                    str3 += ', ' + c[i].CarLookup.Year;

                ok1 = true;
                ok2 = true;
                ok3 = true;
            }
        }

        $row[0].append('<th>' + $.tr('Bilmärke') + '</th>');
        $row[1].append('<td>' + str + '</td>');
        $row[0].append('<th>' + $.tr('Bilmodell') + '</th>');
        $row[1].append('<td>' + str2 + '</td>');
        $row[0].append('<th>' + $.tr('Årsmodell') + '</th>');
        $row[1].append('<td>' + str3 + '</td>');

        c = c[0];
    }
    else {
        $row[0].append('<th>' + $.tr('Bilmärke') + '</th>');
        $row[1].append('<td>' + c.CarLookup.Brand + '</td>');
        $row[0].append('<th>' + $.tr('Bilmodell') + '</th>');
        $row[1].append('<td>' + c.CarLookup.Model + '</td>');
        $row[0].append('<th>' + $.tr('Årsmodell') + '</th>');
        $row[1].append('<td>' + c.CarLookup.Year + '</td>');
    }

    //image holder
    $row[0].append('<td style="text-align:right;" rowspan="8"><img src="' + $.getImage({ src: '/bilder/' + c.PictureFilename, width: 100, height: 100, crop: 5 }) + '" alt="" /></td>');

    //new row 2
    $row = [$('<tr />').appendTo($table), $('<tr />').appendTo($table)];
    //filling row 2
    $row[0].append('<th>' + $.tr('Motor') + '</th>');
    $row[1].append('<td>' + c.CarLookup.Engine + '</td>');
    if (minified) {
        $row[0].append('<th>&nbsp;</th>');
        $row[1].append('<td>&nbsp;</td>');
        $row[0].append('<th>&nbsp;</th>');
        $row[1].append('<td>&nbsp;</td>');
    }
    else {
        $row[0].append('<th>' + $.tr('Drivmedel') + '</th>');
        $row[1].append('<td>' + c.CarLookup.Fuel + '</td>');
        $row[0].append('<th>' + $.tr('Regnr') + '</th>');
        $row[1].append('<td>' + c.RegistrationNo + '</td>');
    }

    if (!minified) {
        //new row 3
        $row = [$('<tr />').appendTo($table), $('<tr />').appendTo($table)];
        //filling row 3
        $row[0].append('<th>' + $.tr('Chassinr') + '</th>');
        $row[1].append('<td>' + c.ChassiNo + '</td>');
        $row[0].append('<th>' + $.tr('Effekt (kw)') + '</th>');
        $row[1].append('<td>' + c.PowerOutput + '</td>');
        $row[0].append('<th>' + $.tr('Växellåda') + '</th>');
        $row[1].append('<td>' + c.TransmissionDescription + '</td>');

        //new row 4
        $row = [$('<tr />').appendTo($table), $('<tr />').appendTo($table)];
        //filling row 4
        $row[0].append('<th>' + $.tr('Längd') + '</th>');
        $row[1].append('<td>' + c.Length + '</td>');
        $row[0].append('<th>' + $.tr('Vikt') + '</th>');
        $row[1].append('<td>' + c.AllowedServiceWeight + '</td>');
        if ((reg != undefined) && reg) {
            $row[0].append('<th>&nbsp;</th>');
            $row[1].append('<td><a id="showMoreButton" href="">' + $.tr('Visa mer...') + '</a></td>');
        }
        else {
            $row[0].append('<th>&nbsp;</th>');
            $row[1].append('<td>&nbsp;</td>');
        }
    }

    $table.html($table.html().replace(/null/g, '-'));
    $table.html($table.html().replace(/undefined/g, '-'));
    $table.css({
        'width': '100%',
        'font-size': '10px'
    });
    $table.find('td').css({
        'padding': '0 0 10px',
        'width': '25%'
    });
    $('#carInformationTable').show().html($table);
    //$table.attr('id', 'carInformationTable');

    if ((reg != undefined) && reg) {
        $table = $('<table style="display:none;" id="extraCarInformation" />');

        //new row 1
        $row = [$('<tr />').appendTo($table), $('<tr />').appendTo($table)];
        //filling row 1
        $row[0].append('<th>' + $.tr('Kaross') + '</th>');
        $row[1].append('<td>' + c.Body + '</td>');
        $row[0].append('<th>' + $.tr('Ny motor') + '</th>');
        $row[1].append('<td>' + c.NewEngineDescription + '</td>');
        $row[0].append('<th>' + $.tr('Typgodkännande') + '</th>');
        $row[1].append('<td>' + c.TypeAffirmativeInformation + '</td>');
        $row[0].append('<th>' + $.tr('Information') + '</th>');
        $row[1].append('<td>' + c.Information + '</td>');

        //new row 2
        $row = [$('<tr />').appendTo($table), $('<tr />').appendTo($table)];
        //filling row 2
        $row[0].append('<th>' + $.tr('Växelmodell') + '</th>');
        $row[1].append('<td>' + c.TransmissionModel + '</td>');
        $row[0].append('<th>' + $.tr('Borr Slag') + '</th>');
        $row[1].append('<td>' + c.Stroke + '</td>');
        $row[0].append('<th>' + $.tr('Däckdim') + '</th>');
        $row[1].append('<td>' + c.WheelDimensions + '</td>');
        $row[0].append('<th>' + $.tr('Tillv-år') + '</th>');
        $row[1].append('<td>' + c.ProductionYear + '</td>');

        //new row 3
        $row = [$('<tr />').appendTo($table), $('<tr />').appendTo($table)];
        //filling row 3
        $row[0].append('<th>' + $.tr('Tillv-mån') + '</th>');
        $row[1].append('<td>' + c.ProductionMonth + '</td>');
        $row[0].append('<th>' + $.tr('Axelavstånd') + '</th>');
        $row[1].append('<td>' + c.AxelDistance + '</td>');
        $row[0].append('<th>' + $.tr('Drivning') + '</th>');
        $row[1].append('<td>' + c.DriveWheels + '</td>');
        $row[0].append('<th>' + $.tr('ABS') + '</th>');
        $row[1].append('<td>' + (c.HasABS ? '' + $.tr('Ja') + '' : '' + $.tr('Nej') + '') + '</td>');

        //new row 4
        $row = [$('<tr />').appendTo($table), $('<tr />').appendTo($table)];
        //filling row 4
        $row[0].append('<th>' + $.tr('AC') + '</th>');
        $row[1].append('<td>' + (c.HasAC ? '' + $.tr('Ja') + '' : '' + $.tr('Nej') + '') + '</td>');
        $row[0].append('<th>' + $.tr('Servo') + '</th>');
        $row[1].append('<td>' + (c.HasServo ? '' + $.tr('Ja') + '' : '' + $.tr('Nej') + '') + '</td>');
        $row[0].append('<th>' + $.tr('Totalvikt') + '</th>');
        $row[1].append('<td>' + c.AllowedTotalWeight + '</td>');
        $row[0].append('<th>&nbsp;</th>');
        $row[1].append('<td><a id="hideMoreButton" href="">' + $.tr('Dölj...') + '</a></td>');

        $table.html($table.html().replace(/null/g, '-'));
        $table.html($table.html().replace(/undefined/g, '-'));
        $table.css({
            'width': '100%',
            'font-size': '10px'
        }).find('td').css({
            'padding': '0 0 10px',
            'width': '25%'
        });

        $table.appendTo('#carInformationTable');

        $('#showMoreButton').click(function () {
            $('#extraCarInformation').show();
            $(this).hide();
            return false;
        });

        $('#hideMoreButton').click(function () {
            $('#extraCarInformation').hide();
            $('#showMoreButton').show();
            return false;
        });
    }
}

function getCarModels(brandId, yearModelId, modelYear) {
$.ajaxLoadingStatus({ text: $.tr('Hämtar sökresultat, var god vänta.') });
gBrandId = brandId;
gYearModelId = yearModelId;
$.ajax({
    type: "GET",
    contentType: "application/json",
    url: "/webservices/carproductsearch.svc/GetCarModels?brandId=" + brandId + "&yearModelId=" + yearModelId,
    dataType: "json",
    processData: false,
    success: function (p, textStatus, XMLHttpRequest) {
        if ($.ajaxErrorHandler(p)) {
            var models = p.d.Models;
            $('#ulModels').replaceWith('<ul id="ulModels"></ul>');
            for (var i = 0; i < models.length; i++) {
                $('#ulModels').append("<li><a href='' rel='" + models[i].ModelId + "' onclick='getCarEngineTypes(" + models[i].ModelId + "," + yearModelId + ",\"" + models[i].ModelName + "\");return false;'>" + models[i].ModelName + "</a></li>");
            }
            //swapping panels
            $('.form').swapPanelsByRegionAndSelectors({ swapFrom: '#ulYearModels', swapTo: '#ulModels', runSplitList: true });

            //STERT uppdating breadcrumb path   START
            crumbMonster(modelYear, { s2: true });
            //END   uppdating breadcrumb path   END

            $.ajaxLoadingStatus({ create: false, update: false });
            executeIfDefined(onCarModelsLoaded);
            onCarModelsLoaded = undefined;
        }

        p = undefined;
    },
    error: function (XMLHttpRequest, textStatus, errorThrown) {
        $.showErrorMessage($.tr('Någonting gick fel när sidan försökte hämta bilmodeller'));
    }
});
}

function getCarYearModels(brandId, brandName) {
$.ajaxLoadingStatus({ text: $.tr('Hämtar sökresultat, var god vänta.') });
gBrandId = brandId;
$.ajax({
    type: "GET",
    contentType: "application/json",
    url: "/webservices/carproductsearch.svc/GetCarYearModels?brandId=" + brandId,
    dataType: "json",
    processData: false,
    success: function (p) {
        if ($.ajaxErrorHandler(p)) {
            var yearModels = p.d.YearModels;
            $('#ulYearModels').replaceWith('<ul id="ulYearModels"></ul>');
            for (var i = 0; i < yearModels.length; i++) {
                $('#ulYearModels').append("<li><a href='' rel='" + yearModels[i].YearModelId + "' onclick='getCarModels(" + brandId + "," + yearModels[i].YearModelId + ",\"" + yearModels[i].Year + "\");return false;'>" + yearModels[i].Year + "</a></li>");
            }
            //swapping panels
            $('.form').swapPanelsByRegionAndSelectors({ swapFrom: '#CarModels', swapTo: '#ulYearModels', runSplitList: true });

            //STERT uppdating breadcrumb path   START
            crumbMonster(brandName, { s1: true });
            if ($('#getCarSearchPath').css('display') == 'none')
                $('#getCarSearchPath').show();
            //END   uppdating breadcrumb path   END

            $.ajaxLoadingStatus({ create: false, update: false });
            executeIfDefined(onCarYearModelsLoaded);
            onCarYearModelsLoaded = undefined;
        }

        p = undefined;
    },
    error: function (XMLHttpRequest, textStatus, errorThrown) {
        $.showErrorMessage($.tr('Någonting gick fel när sidan försökte hämta årsmodeller'));
    }
});
}



function getCarEngineTypes(modelId, yearModelId, ModelName) {
$.ajaxLoadingStatus({ text: $.tr('Hämtar sökresultat, var god vänta.') });
gYearModelId = yearModelId;
$.ajax({
    type: "GET",
    contentType: "application/json",
    url: "/webservices/carproductsearch.svc/GetCarEngineTypes?brandId=" + gBrandId + "&modelId=" + modelId + "&yearModelId=" + yearModelId,
    dataType: "json",
    processData: false,
    success: function (p) {
        if ($.ajaxErrorHandler(p)) {
            var engineTypes = p.d.EngineTypes;
            $('#ulEngineTypes').replaceWith('<ul id="ulEngineTypes"></ul>');
            for (var i = 0; i < engineTypes.length; i++) {
                $('#ulEngineTypes').append("<li><a href='' rel='" + engineTypes[i].EngineTypeId + "' onclick='getCarType(" + gBrandId + "," + modelId + "," + yearModelId + "," + engineTypes[i].EngineTypeId + ",\"" + engineTypes[i].EngineTypeName + "\");return false;'>" + engineTypes[i].EngineTypeName + "</a></li>");
            }
            //swapping panels
            $('.form').swapPanelsByRegionAndSelectors({ swapFrom: '#ulModels', swapTo: '#ulEngineTypes', runSplitList: true });

            //STERT uppdating breadcrumb path   START
            crumbMonster(ModelName, { s3: true });
            //END   uppdating breadcrumb path   END
            $.ajaxLoadingStatus({ create: false, update: false });
            executeIfDefined(onCarEnginesLoaded);
            onCarEnginesLoaded = undefined;
        }

        p = undefined;
    },
    error: function (XMLHttpRequest, textStatus, errorThrown) {
        $.showErrorMessage($.tr('Någonting gick fel när sidan försökte hämta motortyper'));
    }
});
}

function getCarType(brandId, modelId, yearModelId, engineTypeId, EngineTypeName, callback) {
    $.ajaxLoadingStatus({ text: $.tr('Hämtar sökresultat, var god vänta.') });
    $.ajax({
        type: "GET",
        contentType: "application/json",
        url: "/webservices/carproductsearch.svc/GetCarType?brandId=" + brandId + "&modelId=" + modelId + "&yearModelId=" + yearModelId + "&engineTypeId=" + engineTypeId,
        dataType: "json",
        processData: false,
        success: function (p) {
            if ($.ajaxErrorHandler(p)) {
                gCarCode = p.d.CarInformation.Code;
                //getArticleClasses();
                $.createCarTable(p.d.CarInformation, true);

                //STERT uppdating breadcrumb path   START
                if (EngineTypeName != undefined && EngineTypeName != '')
                    crumbMonster(EngineTypeName, { s4: true });
                getArticleClassesV2();
                //END   uppdating breadcrumb path   END                
                $.ajaxLoadingStatus({ create: false, update: false });

                hashSerializer.updateValues(
                    { site: 'car', vehicleSelection: 'code', vehicleParameters: [brandId, modelId, yearModelId, engineTypeId], 
                        dropDownIndicator: 'dd0', searchType: '', searchParameters: [] });
                hashSerializer.setURLHash();

                post_hash_to_product_detail = '#/car/code/dd0/' + brandId + '/' + modelId + '/' + yearModelId + '/' + engineTypeId;

                //Biding button to reset all search variables
                $.resetAllSearchVariables();

                //saving variables
                arrSave = [brandId, modelId, yearModelId, engineTypeId];

                if ($.isFunction(callback)) {
                    callback();
                }

                executeIfDefined(onCarTypeLoaded);
                onCarTypeLoaded = undefined;
            }

            p = undefined;
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            $.showErrorMessage($.tr('Någonting gick fel när sidan försökte hämta biltyper'));
        }
    });
}

function getArticleClasses() {
    $('#selectArticleClass').html('<option value="-1">' + $.tr('Välj reservdelsgrupp') + '</option>');
    for (i = 0, len = $articleClasses.length - 1; i < len; i++) // last one is empty entry
    {
        $('#selectArticleClass').append("<option value='" + $articleClasses[i].Id + "'>" + $articleClasses[i].Name + " (" + ($articleClasses[i].Groups.length - 1).toString() + ")" + "</option>");
    }
    enhanceClassSelect();
    loadGroups($('#selectArticleClass').multiselect("widget").find("input:checked").val());
}

function getArticleClassesV2() {
    $('#selectArticleClassUlList').replaceWith($('<ul id="selectArticleClassUlList"></ul>'));
    var article_class_list = $('#selectArticleClassUlList');

    //clearing list if function is run multiple times
    for (i = 0, len = $articleClasses.length - 1; i < len; i++) // last one is empty entry
    {
//        if ($articleClasses[i].SearchDirect != 'True' || gCarCode == undefined) {
//            article_class_list.append('<li><a class="showGroups" rel="' + $articleClasses[i].Id + '" href="">' + $articleClasses[i].Name + " (" + ($articleClasses[i].Groups.length - 1).toString() + ')</a></li>');
//        }
//        else {
            article_class_list.append('<li><a class="searchDirect" rel="' + $articleClasses[i].Id + '" href="">' + $articleClasses[i].Name + '</a></li>');
        //}
    }
    //binding links
    article_class_list.find('a').click(function () {
        if (gCarCode != undefined) {
            getProductsByArticleClass(this.rel);
        }
        else {
            loadGroupsV2(this.rel);
        }
        
        return false;
    });

//    article_class_list.find('a.searchDirect').click(function () {
//        getProductsByArticleClass(this.rel);
//        return false;
//    });

    //SPLITING LIST
    article_class_list.splitHtmlListV2();
}

function loadGroups(selectedValue) {
    var allowMultipleSelection = gCarCode != null;
    $('#selectArticleGroupHolder')
            .html('<select style="float:left;font-size:11px;width:194px;" id="selectArticleGroup"></select>')
    if (allowMultipleSelection) {
        $('#selectArticleGroupHolder').find("#selectArticleGroup").attr("multiple", "multiple");
    }
    var classGroups = findGroupsByClassId(selectedValue);
    var groupSelect = $('#selectArticleGroup');
    if (classGroups != null) {
        gAccessoryClassId = selectedValue
        for (var i = 0; i < classGroups.length - 1; i++) { // last one is empty entry
            groupSelect.append("<option value='" + classGroups[i].Id + "'>" + classGroups[i].Name + "</option>");
        }
    }
    else {
        groupSelect.append("<option value='-1'>" + $.tr('Reservdel') + "</option>");
    }
    enhanceGroupSelect(allowMultipleSelection);
}

function loadGroupsV2(selectedValue) {
    var article_group_list = $('#selectArticleGroupUlList');
    var article_group_list_holder = $('#selectArticleGroupListHolder');

    //RESETTING LIST IF THIS FUNCTION IS CALLED MULTIPLE TIMES
    article_group_list.replaceWith($('<ul id="' + article_group_list.attr('id') + '"></ul>'));
    article_group_list = $('#selectArticleGroupUlList');

    var allowMultipleSelection = gCarCode != null;

    var classGroups = findGroupsByClassId(selectedValue);
    //var groupSelect = $('#selectArticleGroup');
    if (classGroups != null) {
        gAccessoryClassId = selectedValue
        for (var i = 0; i < classGroups.length - 1; i++) { // last one is empty entry
            //groupSelect.append("<option value='" + classGroups[i].Id + "'>" + classGroups[i].Name + "</option>");
            article_group_list.append('<li><a rel="' + classGroups[i].Id + '" href="">' + classGroups[i].Name + '</a></li>');
        }
        //showing container
        article_group_list_holder.show();
    }
    else {
        article_group_list_holder.hide();
        //groupSelect.append("<option value='-1'>" + $.tr('Reservdel') + "</option>");
    }

    //sliting list
    article_group_list.splitHtmlListV2({ adjustcolumn: -1 });

    //reassigning article_group_list
    article_group_list = $('#' + article_group_list.attr('id'));

    //IF CAR CODE IS DEFINED WE NEED A LIST WITH MULTIPLE SELECTS
    var ieclass = $.exeptionbrowser(8) ? ' ieinput' : '';
    if (allowMultipleSelection) {
        article_group_list.find('a').each(function () {
            $(this).css({ 'float': 'left', 'margin': '2px 0 0 5px' });
            $(this).before('<input class="cargroupcheckbox' + ieclass + '" style="float:left;" type="checkbox" value="' + this.rel + '" />');
            $(this).after('<div class="clear">&nbsp;</div>');
            $(this).click(function () {
                if ($('input:checkbox[value=' + this.rel + ']').attr('checked') == true) {
                    $('input:checkbox[value=' + this.rel + ']').attr('checked', false);
                } else {
                    $('input:checkbox[value=' + this.rel + ']').attr('checked', true);
                    
                    if ($('.cargroupcheckbox:checked').length > 10) {
                        alert('Du får endast välja max 10 grupper');
                        $('input:checkbox[value=' + this.rel + ']').attr('checked', false);
                    }
                }
                
                return false;
            });
        });
        $('.cargroupcheckbox').change(function () {
            if ($('.cargroupcheckbox:checked').length > 10) {
                alert('Du får endast välja max 10 grupper');
                this.checked ? $(this).attr('checked', false) : '';
            }
        });
    }
    else {
        article_group_list.find('a').click(function () {
            getProductsByArticleGroups(undefined, undefined, undefined, undefined, this.rel);
            return false;
        });
    }
}

function enhanceClassSelect() {
$('#selectArticleClass').multiselect({
    selectedText: $.tr('# av # valda'),
    header: false,
    noneSelectedText: $.tr('Välj grupp'),
    multiple: false,
    selectedList: 1,
    click: function (event, ui) {
        if (ui.checked) {
            loadGroups(ui.value);
        }
        $(this).multiselect("close");
    }
});
}

function enhanceGroupSelect(allowMultiple) {
$('#selectArticleGroup').multiselect({
    selectedText: (allowMultiple) ? $.tr('# av 10 valda (# totalt)') : $.tr('# vald (# totalt)'),
    header: (allowMultiple) ? $.tr('Välj upp till 10 delar') : $.tr('Välj en del'),
    noneSelectedText: (allowMultiple) ? $.tr('Välj del(ar)') : $.tr('Välj en del'),
    multiple: allowMultiple,
    selectedList: 0,
    click: function (event, ui) {
        if (ui.checked) {
            cancelEventIfTooManySelections(this, event);
        }
    }
});
}

function cancelEventIfTooManySelections(list, event) {
if ($(list).multiselect("getChecked").length > 10) {
    alert($.tr('Du kan inte välja fler än 10 delar.'));
    event.preventDefault();
}
}

function findGroupsByClassId(classId) {
for (i = 0, len = $articleClasses.length; i < len; i++) {
    if ($articleClasses[i].Id == classId)
        return $articleClasses[i].Groups;
}
return null;
}

function getProductsByArticleClass(articleClassId) {
    
    if (articleClassId.indexOf("class") > -1) {
        articleClassId = articleClassId.substr(5);
    }

    var classGroups = findGroupsByClassId(articleClassId);
    var selectedGroupIds = new Array();
    for (i = 0; i < classGroups.length - 1 ; i++) {
        selectedGroupIds.push(classGroups[i].Id);
    }
    var jsonGroups = JSON.stringify(selectedGroupIds);
    $.clearFilterInput();
    $.ajaxLoadingStatus({ text: $.tr('Hämtar sökresultat, var god vänta.') });
    $.ajax({
        type: "GET",
        contentType: "application/json",
        url: "/webservices/carproductsearch.svc/GetProductsByArticleGroups?productCode=" + gCarCode + "&articleGroups=" + jsonGroups + '&pageSize=' + getPageSize(),
        dataType: "json",
        processData: false,
        success: function (p) {
            if ($.ajaxErrorHandler(p)) {
                $.globalProductList(p.d);
                updatePager();
                $.ajaxLoadingStatus({ create: false, update: false });
                var updateValues = { site: 'car', searchType: '', dropDownIndicator: '', searchParameters: ['class' + articleClassId] };
                if (gCarCode != undefined) {
                    if (arrSave != undefined) {
                        updateValues.vehicleParameters = [arrSave[0], arrSave[1], arrSave[2], arrSave[3], gCarCode];
                        updateValues.dropDownIndicator = 'dd1';
                    }
                }
                else {
                    updateValues.searchType = 'dropdown';
                }
                hashSerializer.updateValues(updateValues);
                hashSerializer.setURLHash(updateValues);
            }
            
            p = undefined;
            //Biding button to reset all search variables
            $.resetAllSearchVariables();
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            $.showErrorMessage($.tr('Någonting gick fel när sidan försökte hämta artikelklasser'));
        }
    });

}

//function getArticleGroupsFromCache() {
// $.ajax({
//     type: "GET",
//     contentType: "application/json",
//     url: "/webservices/carproductsearch.svc/GetArticleGroupsFromCache",
//     dataType: "json",
//     processData: false,
//     success: function (p) {
//         alert(p.d);
//         
//     },
//     error: function (XMLHttpRequest, textStatus, errorThrown) {
//         $.showErrorMessage($.tr('Någonting gick fel när sidan försökte hämta artikelklasser'));
//     }
// });

//}

var newhash, lastKnownLocation;
function getProductsByArticleGroups(directsearch, cc, jg, regchassi, single_art_group) {
    if (jg != undefined && jg.indexOf('class') > -1) {
        getProductsByArticleClass(jg);
        return;
    }
    if (directsearch != undefined) {
        if (directsearch && (regchassi == undefined)) {
            gCarCode = cc;
            jsonGroups = jg;
        }
        if (directsearch && (regchassi != undefined) && regchassi) {
            jsonGroups = jg;
        }
    }
    else {
        var selectedGroups = new Array();
        if (single_art_group != undefined) {
            selectedGroups = [single_art_group];
        } else {
            $('#selectArticleGroupUlList input:checkbox:checked').each(function () {
                selectedGroups.push(this.value);
            });
        }
        var jsonGroups = JSON.stringify(selectedGroups);
    }
    $.clearFilterInput();
    $.ajaxLoadingStatus({ text: $.tr('Hämtar sökresultat, var god vänta.') });
    $.ajax({
        type: "GET",
        contentType: "application/json",
        url: "/webservices/carproductsearch.svc/GetProductsByArticleGroups?productCode=" + gCarCode + "&articleGroups=" + jsonGroups + '&pageSize=' + getPageSize(),
        dataType: "json",
        processData: false,
        success: function (p) {
            if ($.ajaxErrorHandler(p)) {
                $.globalProductList(p.d);
                updatePager();
                $.ajaxLoadingStatus({ create: false, update: false });
                var updateValues = { site: 'car', searchType: '', dropDownIndicator: '', searchParameters: [jsonGroups] };
                if (gCarCode != undefined) {
                    if (arrSave != undefined) {
                        updateValues.vehicleParameters = [arrSave[0], arrSave[1], arrSave[2], arrSave[3], gCarCode];
                        updateValues.dropDownIndicator = 'dd1';
                    }
                }
                else {
                    updateValues.searchType = 'dropdown';
                }
                hashSerializer.updateValues(updateValues);
                hashSerializer.setURLHash();
            }
            p = undefined;
            //Biding button to reset all search variables
            $.resetAllSearchVariables();
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            $.showErrorMessage($.tr('Någonting gick fel när sidan försökte hämta artikelklasser'));
        }
    });
}
