var KEY = {
		UP: 38,
		DOWN: 40,
		ESC: 27,
		PAGEUP: 33,
		PAGEDOWN: 34,
        ENTER: 13,
        LEFT: 37,
        RIGHT: 39
	};

var prefecturesCarAmount = [];
var prefecturesDealersAmount = [];
var prefecturesNames = [];
var areasNames = [];
var areasAliases = [];
var areasPrefectures = [];
var areasCarsAmount = [];
var areasDealersAmount = [];
var prefAliases = [];
var oldSuggestionBoxValue;
var textMessages = [];

function submitLang(lang) {
    var form = document.getElementById("htmlSearchForm");
    if (form) {
        form.elements["lang"].value = lang;
        form.elements["method"].value = "lang";
        form.submit();
        return false;
    }
    return false;
}
function submitMain(startSearch) {
    var form = document.getElementById("htmlSearchForm");
    if (form) {
        form.elements['startSearch'].value = startSearch;
        form.elements["method"].value = "search";
        form.submit();
        return false;
    }
    return false;
}

function resetMainSL(){


    var form = document.getElementById("htmlSearchForm");
    if (form) {
        form.reset();
        initDefaultGradeText();

        if (form.excludeRepairedCars != undefined) {
            form.excludeRepairedCars.checked = false;
        }

        if (form.excludeAskPriceCars != undefined) {
            form.excludeAskPriceCars.checked = false;
        }

        if (form.excludeCarsForTheCountry != undefined) {
            form.excludeCarsForTheCountry.checked = false;
        }
        if(wbSearch) {
            wbSearch.refreshCheckboxes();
        }

    }

    $("select[name='yearFrom']").val("");
    $("select[name='yearTo']").val("");

    $("select[name='mileageFrom']").val("");
    $("select[name='mileageTo']").val("");

    $("select[name='priceFrom']").val("");
    $("select[name='priceTo']").val("");

    prefectureSelector.reset();
    //bodySelect.reset();
    clearGrade();
    modelWindowUtil.reset();

    $("#manufacturerSearchId").val(textMessages["defaultManufacturers"]);
    $("#manufacturerSearchIdValue").val("");

    $("#manufacturerCarsCount").val("");

    $("select[name='dsForm.distance']").val("");
    $("input[name='dsForm.zipFirstPart']").val("");
    $("input[name='dsForm.zipSecondPart']").val("");

    return false;
}

function resetMain(){

     return resetMainSL();
}
function delHistory(id) {
        var form = document.getElementById("htmlSearchForm");
        if (form) {
            form.elements["method"].value = "delHistory";
            form.elements["historyId"].value = id;
            form.submit();
            return false;
        }
    return false;
}
function runHistory(id) {
    var form = document.getElementById("htmlSearchForm");
    if (form) {
        form.elements["method"].value = "runHistory";
        form.elements["historyId"].value = id;
        form.submit();
        return false;
    }
    return false;
}
function show(id) {
    var obj = document.getElementById(id);
    if (obj) {
        obj.style.display = 'block';
        obj.myVis = true;
    }
}
function show2(id) {
    var obj = document.getElementById(id);
    var main = document.getElementById("historyList");
    var pan = document.getElementById("panel");
    if (main && obj && pan) {
        pan.innerHTML = obj.innerHTML;
        show("panel");
        pan.style.left = main.offsetLeft - pan.offsetWidth - 5;
        pan.style.top = main.offsetTop;
    }
}
function hide(id) {
    var obj = document.getElementById(id);
    if (obj) {
        obj.myVis = false;
        obj.style.display = 'none';
    }
}
function hideD(id) {
    var obj = document.getElementById(id);
    if (obj) {
        obj.myVis = false;
        setTimeout("hideMyVis('" + id + "')", 500);
    }
}
function hideMyVis(id) {
    var obj = document.getElementById(id);
    if (obj && obj.myVis != true) {
        obj.myVis = false;
        hide(id);
    }
}
function bgC(obj, color) {
    obj.style.backgroundColor = color;
}

var modelGroups = new Array();

function ModelGroup(id, name, manId, models) {
	this.id = id;
	this.name = name;
	this.manId = manId;
	this.models = models;
	return this;
}

function changeModel() {
    var objMod = document.getElementById("model");
    if (objMod) {
        var ik = 1;
        var isModelGroup = objMod[objMod.selectedIndex].isModelGroup;
        var form = document.getElementById("htmlSearchForm");
        if(form.elements['modelGroupId']) {
            if (isModelGroup && form.elements['modelGroupId'])
            {
                form.elements['modelGroupId'].value = objMod[objMod.selectedIndex].modelGroupId;
            }
            else
            {
                form.elements['modelGroupId'].value = 0;
            }
        }
    }

    clearGrade();

}

function clearGrade() {
    var grade = $("input[name='keywords']");
    if (grade) {
        grade.val(textMessages["gradeDefaultText"]);
    }
}

var models = new Array();
function Model(id, name, manId, bodyId) {
    this.id = id;
    this.name = name;
    this.manId = manId;
    this.bodyId = bodyId;
    return this;
}
function initLists(model, modelGroup) {
    var objMan = document.getElementById("manufacturer");
    var objMod = document.getElementById("model");
    if (objMan && objMod) {

        var grade = $("input[name='keywords']");
        var gradeVal;
        if (grade) {
            gradeVal = grade.val();
        }

        changeManufacturer();
        if (modelGroup > 0)
        {
        	GUI.setSelectedIndex(objMod, 'mg' + modelGroup);
        }
        else
        {
        	GUI.setSelectedIndex(objMod, model);
        }
        changeModel();

        if (grade && gradeVal) {
            grade.val(gradeVal);
        }
    }
}
function carResize(data) {
    try {
        for (var i1 = 0; i1 < data.length; i1++) {
            var maxHeight = 0;
            for (var i2 = 0; i2 < data[i1].length; i2++) {
                var table = document.getElementById("c" + data[i1][i2]);
                maxHeight = Math.max(maxHeight, table.clientHeight);
            }
            for (var i2 = 0; i2 < data[i1].length; i2++) {
                var table = document.getElementById("c" + data[i1][i2]);
                table.style.height = maxHeight;
            }
        }
    } catch (err) {
    }
}
function setPrefecture(prefId) {
    try {
        var obj = document.getElementById("prefecture");
        if (obj && obj.length) {
            for (var ik = 0; ik < obj.length; ik++) {
                if (prefId == obj[ik].value) {
                    obj[ik].selected = true;
                    break;
                }
            }
        }
    } catch (err) {
        alert(err.description);
    }
}

function sortCars(sortingType, sortingOrder, anchor) {
    $('#htmlSearchForm [name="sortForm.sortType"]').val(sortingType);
    $('#htmlSearchForm [name="sortForm.sortOrder"]').val(sortingOrder);
    $('#htmlSearchForm [name="pageForm.pageNum"]').val(0);
    $('#htmlSearchForm [name="defaultSort"]').val(0);
    var action = $('#htmlSearchForm').attr("action");
    var anchorPosition = action.lastIndexOf("#");
    if(anchorPosition != -1) {
        action = action.substring(0, anchorPosition);
    }
    $('#htmlSearchForm').attr("action", action += "#" + anchor);
    submitMainNew(1);
}

function checkDistanceFormValues(distanceForm, distanceFieldName, zip1FieldName, zip2FieldName) {
    //check zipcode/distance input fields
    var errorsUI = [];
    var distance = distanceForm.elements[distanceFieldName];
    var zipFirstPart = distanceForm.elements[zip1FieldName];
    var zipSecondPart = distanceForm.elements[zip2FieldName];

    if (distance && zipFirstPart && zipSecondPart)
    {
        var zipFirstPartLenght = zipFirstPart.value.length;
        var zipSecondPartLenght = zipSecondPart.value.length;
        var distanceSelected = distance.selectedIndex > 0;
        var zipFirstPartIsSet = zipFirstPartLenght == 3 && isDigit(zipFirstPart.value);
        var zipSecondPartIsSet = zipSecondPartLenght == 4 && isDigit(zipSecondPart.value);

        if (distanceSelected)
        {
            if (!zipFirstPartIsSet || !zipSecondPartIsSet)
            {
                errorsUI[errorsUI.length] = errors["zipDistanceOnlyDistanceSelected"];
            }
            else
            {
                $('#htmlSearchForm input[name=prefectures]').val('');
            }
        }
        else if (zipFirstPartLenght > 0 || zipSecondPartLenght > 0)
        {
            if (zipFirstPartIsSet && zipSecondPartIsSet)
            {
                errorsUI[errorsUI.length] = errors["zipDistanceOnlyZipSelected"];
            }
            else
            {
                errorsUI[errorsUI.length] = errors["zipDistanceZipPartlySelectedSelected"];
            }
        }
    }
    return errorsUI;
}

function checkInputValues() {

    var errorsUI = [];
    var frm = document.getElementById('htmlSearchForm');


    if (frm) {
        if (!checkSelect(frm, 'price', true)) {
            errorsUI[errorsUI.length] = errors["priceRange"];
        }

        if (!checkSelect(frm, 'mileage', true)) {
            errorsUI[errorsUI.length] = errors["mileageRange"];
        }

        if (!checkSelect(frm, 'year', false)) {
            errorsUI[errorsUI.length] = errors["yearRange"];
        }

        var distanceErrors = checkDistanceFormValues(frm, "dsForm.distance", "dsForm.zipFirstPart", "dsForm.zipSecondPart");
        if(distanceErrors.length) {
            for(var i = 0; i < distanceErrors.length; i++) {
                errorsUI[errorsUI.length] = distanceErrors[i];
            }
        }

        if (errorsUI.length > 0) {
            warningMessage.show(errorsUI);
            return false;
        }
        return true;
    }
    return false;
}

function checkSelect(frm, name, direction) {
    var elF = frm.elements[name + 'From'];
    var elT = frm.elements[name + 'To'];
    if (elF && elT && elF.selectedIndex > 0 && elT.selectedIndex > 0) {
        if (direction ? elF.selectedIndex > elT.selectedIndex : elF.selectedIndex < elT.selectedIndex) {
            return false;
        }
    }
    return true;
}

function redirectToSearchFormFromDealerPage(startSearch) {
	var form = document.getElementById("htmlSearchOldForm");
    form.elements["dealerId"].value = '';
    form.elements["pageForm.pageNum"].value = 0;
    form.elements['startSearch'].value = startSearch;
    form.elements["method"].value = "search";
    form.submit();
    return false;
}

function submitMainSL(startSearch) {
    var form = document.getElementById("htmlSearchForm");
    form.elements["pageForm.pageNum"].value = 0;
    return submitMainNew(startSearch);
}

function submitMainNew(startSearch) {
    var prefetures = new Array();
    var form = document.getElementById("htmlSearchForm");
    wbSearch.removeBlink();
    if (form && checkInputValues()) {
        form.elements['startSearch'].value = startSearch;
        form.elements["method"].value = "search";


        if ($("#all-areas").attr("checked")) {
             $("#htmlSearchForm input[name='prefectures']").val("");
        }
        var value = $("input[name='keywords']").val();
        if (value == textMessages["gradeDefaultText"]) {
            $("input[name='keywords']").val("");
        }
        if($.cookie("searchOnlyWelfareCars") == "true") {
            $("#searchOnlyWelfareCars").val("true");
        }
        else {
            $("#searchOnlyWelfareCars").val("false");
        }
        $("#htmlSearchForm").trigger("submit");
    }
    return false;
}


function switchLayout(oldLayout, pathString) {
    var form = document.getElementById('htmlSearchForm');
    if(oldLayout) {
        $.cookie("isOldLayout", "true",{ path: pathString, expires: 35000 });
        form.elements["oldLayoutParam"].value = "true";
    }
    else {
        $.cookie("isOldLayout", null, { path: pathString});
        form.elements["oldLayoutParam"].value = "false";
    }
    submitMainNew(1);
}

function initDefaultGradeText() {
    var value = $("input[name='keywords']").val();
    if(value == null || value == undefined || value == "") {
        $("input[name='keywords']").val(textMessages["gradeDefaultText"]);
    }
}

function checkDefaultGradeText(input, isInFocus) {
    if(isInFocus) {
        if(input.value == textMessages["gradeDefaultText"]) {
            input.value = "";
        }
    }
    else {
        if(input.value == "") {
            input.value = textMessages["gradeDefaultText"];
        }
    }
}

function findKeywordsSuggestions(inputBox, formId, cp) {
    inputBox.flushCache();
    if (inputBox.val().length > 0) {

        $.post(
                cp + "/ajax/keywordsSearchSuggestions.htm",
                $('#' + formId).serialize(),
                function(data) {
                    inputBox.autocomplete({
                        max: 20,
                        scrollHeight: 320
                    });
                    inputBox.setOptions({data: data.split("::::")});
                    inputBox.showSuggestionsBox();
                }

                );
    }
}

function checkSuggestionBox(inputBoxId, formId, cp) {
    var inputBox = $('#' + inputBoxId);
    if (inputBox.val().length > 0) {
        if (oldSuggestionBoxValue == undefined || inputBox.val() == textMessages["gradeDefaultText"]) {
            oldSuggestionBoxValue = inputBox.val();
            facetedCarsTable.toggleVisibility(true);
        } else if (oldSuggestionBoxValue != inputBox.val()) {
            oldSuggestionBoxValue = inputBox.val();
            findKeywordsSuggestions(inputBox, formId, cp);
            facetedCarsTable.toggleVisibility(false);
        }
    }
}

var carSelection = new Selection();

function storeCarSelection(){
    carSelection.storeInCookies("car");
}

function restoreCarSelection(){
    carSelection.restoreFromCookies("car");
    $.each(carSelection.getSelectionList(), function(index, value){
            var checkboxForCar = $("#checkboxForCar_" + value);
            var car = $("#car_" + value);
            if(!checkboxForCar.hasClass("checked")){
                checkboxForCar.addClass("checked");
            }
            if(!car.hasClass("selectedCar")){
                car.addClass("selectedCar");
            }
        });
}

function toogleCarSelection(car) {
    if($("#checkboxForCar_" + car).hasClass("checked")) {
        $("#checkboxForCar_" + car).removeClass("checked");
        $("#car_" + car).removeClass("selectedCar");
        carSelection.deleteFromSelection(car);
    }
    else {
        if(carSelection.addToSelection(car)) {
            $("#checkboxForCar_" + car).addClass("checked");
            $("#car_" + car).addClass("selectedCar");
        }
    }
    storeCarSelection();
}

function resetSelectedCars() {
    $("#searchResult .carCheckbox").removeClass("checked");
    $("#searchResult .car").removeClass("selectedCar");
    carSelection.resetSelection();
    storeCarSelection();
}

function submitSingleCar(carId) {
    if(carSelection.isEmpty()) {
        multipleSubmit.chooseCar(carId, false);
    }
    else {
        var carIds = carSelection.getSelectionList();
        carIds[carIds.length] = carId;
        multipleSubmit.chooseCars(carIds);
        resetSelectedCars();
    }
}

function submitSelectedCars() {
    if(carSelection.isEmpty()) {
        alert(messages["multipleSubmit_noCarsSelected"]);
        return;
    }
    multipleSubmit.chooseCars(carSelection.getSelectionList());
    resetSelectedCars();
}

var wbSearch = {
    searchWindowId: null,
    manWindowInitialized: false,
    modelWindowInitialized: false,
    prefectureWindowInitialized: false,
    priceModelYearMiliageWindowInitialized: false,
    modelWindowIsOpen: false, //used when user navigates from model window to manufacturer window
    multipleGradesWindowInitialized: false,
    manufacturerWindowId: "manufacturerWindow",
    modelWindowId: "modelWindow",
    prefectureWindowId: "prefectureWindow",
    multipleGradesWindowId: "multipleGradesWindow",


    initializeWindows : function(searchWindowId, manufacturerWindowId, modelWindowId, prefectureWindowId, multipleGradesWindowId) {
        if(searchWindowId) {
            this.searchWindowId = searchWindowId;
        }
        this.initializeManufacturerWindow(manufacturerWindowId);
        this.initializeModelWindow(modelWindowId);
        this.initializePrefectureWindow(prefectureWindowId);
        this.initializeMultipleGradesWindow(multipleGradesWindowId);
    },

    initializeManufacturerWindow: function(manufacturerWindowId) {
        if(manufacturerWindowId) {
            this.manufacturerWindowId = manufacturerWindowId;
        }
        var manufacturerWindow = this.getWindow(this.manufacturerWindowId);

		manufacturerWindow.dialog(
		{
			title: textMessages["manufacturerTitleText"],
			resizable: true,
			modal: true,
			width:  900,
			height: 'auto',
			autoOpen: false,
			closeOnEscape: true,
			position: 'top',
            open:  function(event, ui) { scrollTo(0,0); wbSearch.refreshWelfareCheckbox();},
            close: function(event, ui) { clickTaleCall("wbSearch.getWindow('" + this.manufacturerWindowId + "').dialog('close');");wbSearch.returnToCorrectPosition(); }
		});
        //inserting close link after dialog title text
        manufacturerWindow.parent("div")
                .find(".ui-dialog-title")
                .after("<a class=\"closeButton\" href=\"javascript:wbSearch.closeWindow('" + this.manufacturerWindowId + "')\"></a>" +
                       "<a class=\"welfareLink\"href=\"javascript:wbSearch.switchWelfareCheckbox()\">福祉車両</a><div class=\"welfareCheckbox\" onclick=\"wbSearch.switchWelfareCheckbox()\"></div>");
        manufacturerWindow.css("display", "block");
        this.manWindowInitialized = true;

    },

    initializeModelWindow: function(modelWindowId) {
        if(modelWindowId) {
            this.modelWindowId = modelWindowId;
        }
        var modelWindow = this.getWindow(this.modelWindowId);
        modelWindow.dialog(
        {
            title: textMessages["modelPopUpTitle"],
            resizable: false,
            modal: true,
            width: 1000,
            height: 'auto',
            autoOpen: false,
            closeOnEscape: true,
            position: 'top',
            open:  function(event, ui) { scrollTo(0,0); wbSearch.refreshWelfareCheckbox(); modelWindowUtil.refreshCheckboxes();},
            close: function(event, ui) { clickTaleCall("wbSearch.getWindow('" + this.modelWindowId + "').dialog('close');");wbSearch.returnToCorrectPosition();}
        });
        modelWindow.parent("div")
                .find(".ui-dialog-title")
                .after("<a class=\"closeButton\" href=\"javascript:wbSearch.closeWindow('" + this.modelWindowId + "')\"></a>"  +
                       "<a class=\"welfareLink\"href=\"javascript:wbSearch.switchWelfareCheckbox()\">福祉車両</a><div class=\"welfareCheckbox\" onclick=\"wbSearch.switchWelfareCheckbox()\"></div>");
        this.modelWindowInitialized = true;
    },

    initializePrefectureWindow: function(prefectureWindowId) {
        if(prefectureWindowId) {
            this.prefectureWindowId = prefectureWindowId;
        }
        var prefectureWindow = this.getWindow(this.prefectureWindowId);
        prefectureWindow.dialog(
        {
            title: textMessages["prefectureTitleText"],
            resizable: false,
            modal: true,
            width:  862,
            autoOpen: false,
            closeOnEscape: true,
            open:  function(event, ui) { prefectureSelector.refreshCheckboxes();},
            close: function(event, ui) { clickTaleCall("wbSearch.getWindow('" + this.prefectureWindowId + "').dialog('close');");wbSearch.returnToCorrectPosition();}
        });
        prefectureWindow.parent("div")
                .find(".ui-dialog-title")
                .after("<a class=\"closeButton\" href=\"javascript:wbSearch.closeWindow('" + this.prefectureWindowId + "')\"></a>" );
        prefectureWindow.css("display", "block");
        this.prefectureWindowInitialized = true;
    },

    initializeMultipleGradesWindow: function(multipleGradesWindowId) {
        if(multipleGradesWindowId) {
            this.multipleGradesWindowId = multipleGradesWindowId;
        }
        var multipleGradesWindow = this.getWindow(this.multipleGradesWindowId);
        multipleGradesWindow.dialog(
        {
            title: textMessages["selectMultipleGrades"],
            resizable: false,
            modal: true,
            width:  1000,
            height: 'auto',
            autoOpen: false,
            closeOnEscape: true,
            open:  function(event, ui) {multipleGradeSelector.refreshCheckboxes();},
            close: function(event, ui) {clickTaleCall("wbSearch.getWindow('" + this.multipleGradesWindowId + "').dialog('close');");wbSearch.returnToCorrectPosition();}
        });
        multipleGradesWindow.parent("div")
                .find(".ui-dialog-title")
                .after("<a class=\"closeButton\" href=\"javascript:wbSearch.closeWindow('" + this.multipleGradesWindowId + "')\"></a>" );
        multipleGradesWindow.css("display", "block");
        this.multipleGradesWindowInitialized = true;
    },

    ie6SelectboxFixup : function() {
//        var selector = ".ie6-dialog-zfix";
//        var manufacturerWindowOpen = ($("#" + this.manufacturerWindowId).length > 0) && ($("#" + this.manufacturerWindowId).parent().css("display") != "none");
//        var modelWindowOpen = ($("#" + this.modelWindowId).length > 0) && ($("#" + this.modelWindowId).parent().css("display") != "none");
//        var prefectureWindowOpen = ($("#" + this.prefectureWindowId).length > 0) && ($("#" + this.prefectureWindowId).parent().css("display") != "none");
//        var warningWindowOpen = ($("#warningWindow").length > 0) && ($("#warningWindow").parent().css("display") != "none");
//        if(manufacturerWindowOpen || modelWindowOpen|| prefectureWindowOpen || warningWindowOpen) {
//            $(selector).css("visibility", "hidden");
//        }
//        else {
//            $(selector).css("visibility", "visible");
//        }
    },

    refreshWelfareCheckbox : function() {
        if($("#searchOnlyWelfareCars").val() == "true" || $.cookie("searchOnlyWelfareCars") == "true") {
            $(".welfareCheckbox").addClass("checked");
            this.storeWelfareCheckboxInCookies("true");
        }
        else {
            $(".welfareCheckbox").removeClass("checked");
            this.storeWelfareCheckboxInCookies("false");
        }
    },

    switchWelfareCheckbox : function() {
        if($("#searchOnlyWelfareCars").val() == "true") {
            $(".welfareCheckbox").removeClass("checked");
            $("#searchOnlyWelfareCars").val("false");
            this.storeWelfareCheckboxInCookies("false");
        }
        else {
            $(".welfareCheckbox").addClass("checked");
            $("#searchOnlyWelfareCars").val("true");
            this.storeWelfareCheckboxInCookies("true");
        }
    },

    storeWelfareCheckboxInCookies : function(value) {
        $.cookie("searchOnlyWelfareCars", value, {expires: 36500, path: "/"});
    },

    returnToCorrectPosition : function () {
        var destination = 0;
        if (this.searchWindowId != null) {
            var searchWindowElement = $('#' + this.searchWindowId );
            destination = searchWindowElement.offset().top;
        }
        $("html:not(:animated),body:not(:animated)").animate({ scrollTop: destination}, 0 );
    },

    closeWindow: function(windowId) {
        var window = $("#" + windowId);;
        window.dialog("close");
    },

    getWindow: function(windowId) {
        return $("#" + windowId);
    },

    showSelectManufacturerWindow: function (modelWindowIsOpen) {
        clickTaleCall("wbSearch.showSelectManufacturerWindow(" + modelWindowIsOpen + ");");
        this.modelWindowIsOpen = modelWindowIsOpen;
        var manufacturerWindow = this.getWindow(this.manufacturerWindowId);
        manufacturerWindow.dialog('open');
        wbSearch.autoresizeSelectModalWindow();
        if($.browser.msie && $.browser.version < 7) {
        // bullshit for ie6, if someone can make it better - please do it
            manufacturerWindow.css("height", $(window).height() - 40 + "px");
            manufacturerWindow.css("overflow-y", "scroll");
            manufacturerWindow.dialog( "option", "position", 'top' );
        }
    },

    autoresizeSelectModalWindow: function () {
        var manufacturerWindow = this.getWindow(this.manufacturerWindowId);
        var modelWindow = this.getWindow(this.modelWindowId);

        if (manufacturerWindow.dialog("isOpen")) {
            manufacturerWindow.dialog( "option", "height", $(window).height() );
            manufacturerWindow.dialog( "option", "position", ['center','top']);
        }

        if (modelWindow.dialog("isOpen")) {
            modelWindow.dialog( "option", "height", $(window).height() );
            modelWindow.dialog( "option", "position", ['center','top']);
        }
    },

    selectManufacturer: function(manufacturerName, manufacturerId, manufacturerCarsCount) {
        $("#manufacturerSearchIdValue").val(manufacturerId);
        $("#manufacturerSearchId").val(manufacturerName);
        $("#disableSelectedModel").val('');
        $("#manufacturerCarsCount").val(manufacturerCarsCount);

        //clear previously selected model
        modelWindowUtil.reset();
        clearGrade();

        var isCountrySelected = (manufacturerId.substring(0,1) == 'c');

        if (isCountrySelected) { //no models to select
            $("#modelSearchId").val(manufacturerName + textMessages["allModels"]);
            if (this.modelWindowIsOpen) {
                this.getWindow(this.modelWindowId).dialog("close");
            }
            this.getWindow(this.manufacturerWindowId).dialog("close");
        } else {
            if (this.modelWindowIsOpen) {
                modelWindowUtil.fillInModelWindow(this.getWindow(this.modelWindowId), this.getWindow(this.manufacturerWindowId));

            } else {
                wbSearch.showSelectModelWindow();
            }
        }

        this.modelWindowIsOpen = false;
        this.blinkSearchButton();
    },

    showSelectModelWindow: function () {
        var manVal = $("#manufacturerSearchIdValue").val();
        if (manVal == null || manVal.length == 0) {
            warningMessage.show([textMessages["no_manufacturer_selected"]]);
            return false;
        }
        else if(manVal.substr(0,1) == "c")
        {
            warningMessage.show([textMessages["no_manufacturer_selected"]]);
            return false;
        }
        else {
            var manufacturers = $('.mfg a[href^=javascript:wbSearch.selectManufacturer]');
            var disalbeModelWindow = true;
            var manText = $("#manufacturerSearchId").val();
            for(var i = 0; i < manufacturers.length; i++) {
                var text = $(manufacturers[i]).text();
                if (text == manText) {
                    disalbeModelWindow = false;
                    break;
                }
            }
            if (disalbeModelWindow) {
                return false;
            }
            modelWindowUtil.fillInModelWindow(this.getWindow(this.modelWindowId), this.getWindow(this.manufacturerWindowId));
        }
    },

    selectModel: function() {
        var allModels = $("#modelWindow [id='all-models']");
        var modelGroupsField = $("#htmlSearchForm input[name='modelGroupId']");
        var modelIdsField = $("#modelSearchIdValue");
        var modelNamesField = $("#modelSearchId");
        var allModelsField = $("#allModelsChecked");

        if($(allModels).is(":checked")) {
            $(modelGroupsField).val("");
            $(modelIdsField).val("");
            $(modelNamesField).val($("#manufacturerSearchId").val() + textMessages["allModels"]);
            $(allModelsField).val("true");
        }
        else {
            $(allModelsField).val("false");
            var selectedGroups = $("#modelWindow [id^='mg-']:checked");

            var groupIds = new Array();
            var modelIds = new Array();
            var modelNames = "";
            selectedGroups.each(function(index, group){
                if(groupIds.length != 0) {
                    modelNames += "; ";
                }
                if($(group).attr("id") != "mg-0") {
                    groupIds[groupIds.length] = $(group).attr("id").replace("mg-", "");
                    modelNames += $(group).attr("value");
                }
            });

            var selectedModels = $("#modelWindow [id^='m-']:checked");

            for(var i in groupIds) { //filtering models which are already covered by model group selection
                selectedModels = $(selectedModels).not("[id*='-mg-" + groupIds[i]+ "']");
            }
            var groupIdIndex;
            selectedModels.each(function(index, model){
                if(modelNames != "") {
                    modelNames += "; ";
                }
                groupIdIndex = $(model).attr("id").indexOf("-mg-");
                modelIds[modelIds.length] = $(model).attr("id").substr(0, groupIdIndex).replace("m-", "");
                modelNames += $(model).attr("value");
            });
            $(modelGroupsField).val(groupIds.join(","));
            $(modelIdsField).val(modelIds.join(","));
            if(groupIds.length == 0 && modelIds.length == 0) {
                modelNames = $("#manufacturerSearchId").val() + textMessages["allModels"];
            }
            $(modelNamesField).val(modelNames);
        }
        clearGrade();
        //multipleGradeSelector.linkRefresh();
        this.closeWindow(this.modelWindowId);
        this.blinkSearchButton();
    },

    showSelectPrefectureWindow: function ()
    {

        prefectureSelector.initCarAmountForPrefectures();

        var buttonsAndGeomapRelationshipsMap = [];

        buttonsAndGeomapRelationshipsMap['b_tohoku'] = 'toh';
        buttonsAndGeomapRelationshipsMap['b_kanto'] = 'kant';
        buttonsAndGeomapRelationshipsMap['b_tokai'] = 'tok';
        buttonsAndGeomapRelationshipsMap['b_kansai'] = 'kans';
        buttonsAndGeomapRelationshipsMap['b_koshinetsu-hokuriku'] = 'kosh';
        buttonsAndGeomapRelationshipsMap['b_shikoku'] = 'shik';
        buttonsAndGeomapRelationshipsMap['b_kyushu'] = 'kyus';
        buttonsAndGeomapRelationshipsMap['b_chugoku'] = 'chug';

        var obj;

        clickTaleCall('wbSearch.showSelectPrefectureWindow();');
        this.getWindow(this.prefectureWindowId).dialog('open');

        if($.browser.msie && $.browser.version < 9)
        {
            $('#b_kanagawa').css("font-size", "8px");
            $('#b_kanagawa').children('span').css("font-size", "8px");

            $('.b-map-prefectures li').mouseenter(function(){
                $('.b-map-buttons #b_' + $(this).attr('id')).addClass('active');
            });

            $('.b-map-prefectures li').mouseleave(function(){

                if(!$('.b-map-buttons #b_' + $(this).attr('id')).children('input:checkbox').is(':checked'))
                {
                    $('.b-map-buttons #b_' + $(this).attr('id')).removeClass('active');
                }
            });

            $('.b-map-buttons label').mouseenter(function()
            {
                $(this).addClass('active');

                if(buttonsAndGeomapRelationshipsMap[$(this).attr('id')] != null)
                {
                    $('.' + buttonsAndGeomapRelationshipsMap[$(this).attr('id')]).addClass('active');
                }
                else
                {
                    obj = $(this).attr('id').replace('b_','');
                    $('.b-map-prefectures #' + obj).children().addClass('active');
                }
            });

            $('.b-map-buttons label').mouseleave(function()
            {
                if(!$(this).children('input:checkbox').is(':checked'))
                {
                    $(this).removeClass('active');
                    if(buttonsAndGeomapRelationshipsMap[$(this).attr('id')] != null)
                    {
                        $('.' + buttonsAndGeomapRelationshipsMap[$(this).attr('id')]).removeClass('active');
                    }
                    else
                    {
                        $('.b-map-prefectures #' + obj).children().removeClass('active');
                    }
                }
            });
        }
        else
        {
            $('.b-map-prefectures li').hover(function(){
                $('.b-map-buttons #b_' + $(this).attr('id')).addClass('hover');
            },

                    function()
                    {
                        $('.b-map-buttons #b_' + $(this).attr('id')).removeClass('hover');
                    });

            $('.b-map-buttons label').hover(
                    function()
                    {
                        if(buttonsAndGeomapRelationshipsMap[$(this).attr('id')] != null)
                        {
                            $('.' + buttonsAndGeomapRelationshipsMap[$(this).attr('id')]).addClass('hover');
                        }
                        else
                        {
                            obj = $(this).attr('id').replace('b_','');
                            $('.b-map-prefectures #' + obj ).children().addClass('hover');
                        }
                    },

                    function()
                    {
                        if(buttonsAndGeomapRelationshipsMap[$(this).attr('id')] != null)
                        {
                            $('.' + buttonsAndGeomapRelationshipsMap[$(this).attr('id')]).removeClass('hover');
                        }
                        else
                        {
                            $('.b-map-prefectures #' + obj ).children().removeClass('hover');
                        }
                    });

            $('#b_kanagawa').css("font-size", "10px !important");
            $('#b_kanagawa').children('span').css("font-size", "10px !important");
        }

        $('.b-map-buttons label').click(
                function()
                {
                    if($(this).children('input:checkbox').is(':checked'))
                    {
                        $(this).addClass('active');

                        if(buttonsAndGeomapRelationshipsMap[$(this).attr('id')] != null)
                        {
                            $('.' + buttonsAndGeomapRelationshipsMap[$(this).attr('id')]).addClass('active');
                        }
                        else
                        {
                            obj = $(this).attr('id').replace('b_','');
                            $('.b-map-prefectures #' + obj ).children().addClass('active');
                        }
                    }
                    else
                    {
                        $(this).removeClass('active');

                        if(buttonsAndGeomapRelationshipsMap[$(this).attr('id')] != null)
                        {
                            $('.' + buttonsAndGeomapRelationshipsMap[$(this).attr('id')]).removeClass('active');
                        }
                        else
                        {
                            obj = $(this).attr('id').replace('b_','');
                            $('.b-map-prefectures #' + obj ).children().removeClass('active');
                        }
                    }
                    return $(this).children('input:checkbox').not(':checked');
                });

        $('.b-map-prefectures li').click(function()
        {
            $('.b-map-buttons #b_' + $(this).attr('id')).children('input').click();

            $(this).children('a').toggleClass('active');
        });

        var allPrefectures = $("#prefectureWindow input[type='checkbox'][id^='p-']:checked");
        for (var i = 0; i < allPrefectures.length; i++)
        {
            var cb = $('#' + allPrefectures[i].id);
            var parentLabel = $(cb).parent('label');

            $(parentLabel).addClass('active');

            obj = $(parentLabel).attr('id').replace('b_','');

            $('.b-map-prefectures #' + obj ).children().addClass('active');
        }

        $("#prefectureWindow input[type='checkbox'][id^='a-']:checked").each(function()
        {
            $(this).parent('label').addClass('active');
        });

        $("#prefectureWindow input[type='checkbox'][id^='p-']").each(function()
        {
            var amount = prefecturesCarAmount[$(this).attr('value')];

            $(this).parent('label').children('span').html(' (' + thousandSeparator(amount) + ')');
        });

        $(".b-map-buttons label input:checkbox[id^='a-']").each(function()
        {
            $(this).parent('label').css("text-align", "center");

            var count = 0;

            $(".b-map-buttons label input:checkbox[id$='-" + $(this).attr('id') + "']").each(function()
            {
                count = count + parseInt(prefecturesCarAmount[$(this).attr('value')]);
            });

            $(this).parent('label').children('span').html(' (' + thousandSeparator(count) + ')');
        });


        $('#all-areas-span').html(' (' + thousandSeparator(prefecturesCarAmount['999']) + ')');

        var kaganawaHack = $('#b_kanagawa').children('span').html().replace(' ', '');
        $('#b_kanagawa').children('span').html(kaganawaHack);
//        $('#b_kanagawa').children('input:checkbox').css('width', '1em');
    },

    selectPrefecture: function() {
        prefectureSelector.fillSelectedPrefectures();
        this.getWindow(this.prefectureWindowId).dialog('close');
        this.blinkSearchButton();
        if($('#all-areas').is(':checked'))
        {
            $('#excludeCarsForTheCountry').attr('checked', '');
            this.refreshCheckboxes();

        }
    },

    showSelectMultipleGradesWindow: function() {
        clickTaleCall('wbSearch.showSelectMultipleGradesWindow();');
        multipleGradeSelector.fillInGradeWindow();
    },

    blinkSearchButton: function() {
        $("#portalSearchTable .searchButton, .b-index-search-form .searchButton").addClass("searchButtonChangeIndex");
        $("#searchForm .footer .buttons .searchButton").addClass("searchButtonChange");
        setTimeout(this.removeBlink, 2000);
    },

    removeBlink: function() {
        $("#searchForm .footer .buttons .searchButton").removeClass("searchButtonChange");
        $("#portalSearchTable .searchButton, .b-index-search-form .searchButton").removeClass("searchButtonChangeIndex");
    },

    refreshCheckboxes: function() {
        $(".filters input").each(function(){
            if($(this).is(":checked")) {
                $("label[for='"+ $(this).attr("id") +"']").css("color", "red");
            }
            else {
                $("label[for='"+ $(this).attr("id") +"']").css("color", "black");
            }
        });
    }
}


var prefectureSelector = {
    checkboxList: null,
    contextPath: null,

    setContextPath: function(contextPath) {
//        alert("setContextPath");
        this.contextPath = contextPath;
        if(this.contextPath == null || this.contextPath == "null" || this.contextPath == "/") {
            this.contextPath = "";
        }

    },

    initCarAmountForPrefectures: function()
    {
        if(prefecturesCarAmount.length == 0)
        {
//            alert("initCarAmountForPrefectures");
            $.ajax({
                type: "get",
                url: this.contextPath + "/ajax/getPrefecturesCarAmount.htm",
                async: false,
                success: function(data)
                {
                    prefecturesCarAmount = eval('(' + data + ')');
                }
            });
        }

        if(prefecturesDealersAmount.length == 0)
        {
            $.ajax({
                type: "get",
                url: this.contextPath + "/ajax/getPrefecturesDealersAmount.htm",
                async: false,
                success: function(data)
                {
                    prefecturesDealersAmount = eval('(' + data + ')');
                }
            });
        }

        if(prefecturesNames.length == 0)
        {
            $.ajax({
                type: "get",
                url: this.contextPath + "/ajax/getPrefecturesNames.htm",
                async: false,
                success: function(data)
                {
                    prefecturesNames = eval('(' + data + ')');
                }
            });
        }

        if(areasNames.length == 0)
        {
            $.ajax({
                type: "get",
                url: this.contextPath + "/ajax/getAreasNames.htm",
                async: false,
                success: function(data)
                {
                    areasNames = eval('(' + data + ')');
                }
            });
        }

        if(areasAliases.length == 0)
        {
            $.ajax({
                type: "get",
                url: this.contextPath + "/ajax/getAreasAliases.htm",
                async: false,
                success: function(data)
                {
                    areasAliases = eval('(' + data + ')');
                }
            });
        }

        if(areasPrefectures.length == 0)
        {
            $.ajax({
                type: "get",
                url: this.contextPath + "/ajax/getAreasPrefectures.htm",
                async: false,
                success: function(data)
                {
                    areasPrefectures = eval('(' + data + ')');
                }
            });
        }

        if(areasCarsAmount.length == 0)
        {
            for(key in areasPrefectures)
            {
                var count = 0;
                for(key2 in areasPrefectures[key])
                {
                    count = count + Number(prefecturesCarAmount[areasPrefectures[key][key2]]);
                }

                areasCarsAmount[key] = count;
            }
        }

        if(areasDealersAmount.length == 0)
        {
            for(key in areasPrefectures)
            {
                var count = 0;
                for(key2 in areasPrefectures[key])
                {
                    count = count + Number(prefecturesDealersAmount[areasPrefectures[key][key2]]);
                }

                areasDealersAmount[key] = count;
            }
        }

        if(prefAliases.length == 0)
        {
            $.ajax({
                type: "get",
                url: this.contextPath + "/ajax/getPrefecturesAliases.htm",
                async: false,
                success: function(data)
                {
                    prefAliases = eval('(' + data + ')');
                }
            });
        }
    },

    getAreasCarsAmount: function()
    {
        if(areasCarsAmount.length == 0)
        {
            this.initCarAmountForPrefectures();
        }

        return areasCarsAmount;
    },

    getAreasDealersAmount: function()
    {
        if(areasDealersAmount.length == 0)
        {
            this.initCarAmountForPrefectures();
        }

        return areasDealersAmount;
    },

    getPrefecturesCarAmount: function()
    {
        if(prefecturesCarAmount.length == 0)
        {
            this.initCarAmountForPrefectures();
        }

        return prefecturesCarAmount;
    },

    getPrefecturesDealersAmount: function()
    {
        if(prefecturesDealersAmount.length == 0)
        {
            this.initCarAmountForPrefectures();
        }

        return prefecturesDealersAmount;
    },

    getPrefecturesNames: function()
    {
        if(prefecturesNames.length == 0)
        {
            this.initCarAmountForPrefectures();
        }

        return prefecturesNames;
    },

    getAreasNames: function()
    {
        if(areasNames.length == 0)
        {
            this.initCarAmountForPrefectures();
        }

        return areasNames;
    },

    getAreasAliases: function()
    {
        if(areasAliases.length == 0)
        {
            this.initCarAmountForPrefectures();
        }

        return areasAliases;
    },

    getAreasPrefectures: function()
    {
        if(areasPrefectures.length == 0)
        {
            this.initCarAmountForPrefectures();
        }

        return areasPrefectures;
    },

    getPrefAliases: function()
    {
        if(prefAliases.length == 0)
        {
            this.initCarAmountForPrefectures();
        }

        return prefAliases;
    },

    initialize: function(rootNodeId, rootCheckboxId, blockCheckboxIdPrefix, contextPath) {
        this.setContextPath(contextPath);
        this.checkboxList = new CheckboxList();
        this.checkboxList.initialize(rootNodeId, rootCheckboxId, blockCheckboxIdPrefix, true);
    },

    checkAll: function(element)
    {
        this.checkboxList.checkAll(element);

        var checked = $(element).is(":checked");

        var allPrefectures = new Array();
        var allAreas = new Array();

        allPrefectures = $("#prefectureWindow input[type='checkbox'][id^='p-']");
        allAreas = $("#prefectureWindow input[type='checkbox'][id^='a-']");

        var allCheckboxes = $.merge(allPrefectures, allAreas);

        for (var i = 0; i < allCheckboxes.length; i++)
        {
            var cb = $('#' + allCheckboxes[i].id);
            var parentLabel = $(cb).parent('label');
            var obj = $(parentLabel).attr('id').replace('b_','');

            if(checked)
            {
                $('.b-map-prefectures #' + obj ).children().addClass('active');
                $(parentLabel).addClass('active');
            }
            else
            {
                $('.b-map-prefectures #' + obj ).children().removeClass('active');
                $(parentLabel).removeClass('active');
            }
        }

        //ticket #2652
        //begin
        this.refreshExcludeCarsForTheCountry();
        //end
    },

    checkBlock: function(element)
    {
        $(".b-map-buttons label input:checkbox[id$='-" + element.id + "']").each(
                function()
                {
                    if($('#' + element.id).is(':checked'))
                    {
                        $(this).parent('label').addClass('active');
                    }
                    else
                    {
                        $(this).parent('label').removeClass('active');
                    }
                });

        this.checkboxList.checkBlock(element);

        //ticket #2652
        //begin
        this.refreshExcludeCarsForTheCountry();
        //end
    },

    checkSingleCheckbox: function(element) {
        this.checkboxList.checkSingleCheckbox(element);

        $(".b-map-buttons label input:checkbox").each(function()
        {
            if(!$(this).is(':checked'))
            {
                $(this).parent('label').removeClass('active');
            }
            else
            {
                $(this).parent('label').addClass('active');
            }
        });

        //ticket #2652
        //begin
        this.refreshExcludeCarsForTheCountry();
        //end
    },

    refreshExcludeCarsForTheCountry : function()
    {
        var exlCarsForTheCountry = false;

        var allPrefectures = $("#prefectureWindow input[type='checkbox'][id^='p-']");
        for (var i = 0; i < allPrefectures.length; i++)
        {
            if(allPrefectures[i].checked)
            {
                exlCarsForTheCountry = true;
                break;
            }
        }

        if (!exlCarsForTheCountry) { //could skip if regions selected

            //zip code check
            var dist = $("select[name='dsForm.distance']").val();
            var zFirstPart = $("input[name='dsForm.zipFirstPart']").val();
            var zSecPart = $("input[name='dsForm.zipSecondPart']").val();
            if (dist.length > 0 && zFirstPart.length == 3 && zSecPart.length == 4) {
                exlCarsForTheCountry = true;
            }
        }

        $('#excludeCarsForTheCountry').attr('checked', exlCarsForTheCountry);
        wbSearch.refreshCheckboxes();

    },

    reset: function() {
        this.checkboxList.reset();
        $("#htmlSearchForm input[name='prefectures']").val("");
        $("#prefectureSearchId").html("<div class=\"option\">" + textMessages["defaultPrefecturers"] + "</div>");

        var allPrefectures = new Array();
        var allAreas = new Array();

        allPrefectures = $("#prefectureWindow input[type='checkbox'][id^='p-']");
        allAreas = $("#prefectureWindow input[type='checkbox'][id^='a-']");

        var allCheckboxes = $.merge(allPrefectures, allAreas);

        for (var i = 0; i < allCheckboxes.length; i++)
        {
            var cb = $('#' + allCheckboxes[i].id);
            var parentLabel = $(cb).parent('label');
            $(parentLabel).removeClass('active');
            var obj = $(parentLabel).attr('id').replace('b_','');
            $('.b-map-prefectures #' + obj ).children().removeClass('active');
        }

        this.refreshExcludeCarsForTheCountry();
    },
    
    fillSelectedPrefectures: function() {
        var prefectures = $("#htmlSearchForm input[name='prefectures']");
        var prefecturesUI = $("#prefectureSearchId");

        var prefetures = Array();
        var prefeturesUIVal = "";
        var isAllChecked = $("#all-areas").is(":checked");

        var allPrefectures = $("#prefectureWindow input[type='checkbox'][id^='p-']:checked");
        for (var i = 0; i < allPrefectures.length; i++) {
            prefetures[i] = allPrefectures[i].value;
            if (!isAllChecked) {
                prefeturesUIVal += "<div class=\"option\">" + allPrefectures[i].alt + "</div>";
            }
        }
        prefectures.val(prefetures);
        if (!isAllChecked && prefeturesUIVal.length > 0) {
            prefecturesUI.html(prefeturesUIVal);
        } else {
            prefecturesUI.html("<div class=\"option\">" + textMessages["defaultPrefecturers"] + "</div>");
        }
    },

    refreshCheckboxes: function() {
        var prefectures = $("#htmlSearchForm input[name='prefectures']");
        var selectedPrefsArrayTemp = prefectures.val().split(",");
        var selectedPrefsArray = Array();
        for (var i = 0; i < selectedPrefsArrayTemp.length; i++) {
            selectedPrefsArray[selectedPrefsArrayTemp[i]] = selectedPrefsArrayTemp[i];
        }

        var allPrefectures = $("#prefectureWindow input[type='checkbox'][id^='p-']");
        for (var i = 0; i < allPrefectures.length; i++) {

            var id = allPrefectures[i].id.substring(2,allPrefectures[i].id.indexOf("-a-"));
            if (selectedPrefsArray[id] != undefined) {
                this.checkboxList.setChecked(allPrefectures[i])
            } else {
                this.checkboxList.setUnchecked(allPrefectures[i])
            }
        }

        var allAreas = $("#prefectureWindow input[type='checkbox'][id^='a-']");
        for (var i = 0; i < allAreas.length; i++) {
            this.checkboxList.refreshBlockCheckBox(allAreas[i].id);
        }

        this.checkboxList.refreshAllCheckBox();
    }
}

var requestedGrades = [];

var multipleGradeSelector = {
    checkboxList: null,
    otherGrades: [],
    lastUsedPrefecturesIds: "",


    initialize: function(rootNodeId, rootCheckboxId, blockCheckboxIdPrefix) {
        this.checkboxList = new CheckboxList();
        this.checkboxList.initialize(rootNodeId, rootCheckboxId, blockCheckboxIdPrefix, true);
    },

    reset: function() {
        $("#multipleGradesWindow input[type='checkbox']").removeAttr("checked");

    },

    fillInGradeWindow: function() {
        var objModel = $("#modelSearchId");
        var gradesWindow = $("#multipleGradesWindow");
        var elementsPerRow = 3;

        var modelGroupId =  $("input[name='modelGroupId']").val();

        var modelSearchIdValue = $("#modelSearchIdValue");
        var modelId = modelSearchIdValue.val();
        var message = textMessages["commonGradeMessage"];

        var prefectures = $("#htmlSearchForm input[name='prefectures']");
        var prefecturesIds = prefectures.val();
        var reloadGrades = false;

        if(prefecturesIds != this.lastUsedPrefecturesIds) {
            reloadGrades = true;
            this.lastUsedPrefecturesIds = prefecturesIds;
        }
                

        if (gradesWindow) {
            var modelIdUI = objModel.val();

            if (modelGroupId.length != 0 || modelIdUI.length == 0 || modelId.length == 0 || modelId.indexOf(',') > -1) {
                warningMessage.show([message]);
            } else {

                var content = ["<table cellspacing='0' cellpadding='0' class=\"wideTable\"><tr><td  class='title' colspan='" + elementsPerRow + "'>" +
                               textMessages["selectMultipleGrades"] + "</td></tr>"];
                content[content.length] = "<tr><td  colspan='" + elementsPerRow + "'>" +
                               "<a href=\"javascript:multipleGradeSelector.updateSelectedGrades();\" class=\"okButton\"></a>" + 
                                "<a href=\"javascript:multipleGradeSelector.reset();\" class=\"resetButton\"  ></a></td></tr>";

                var dataArray = requestedGrades[modelId];
                if (dataArray != null && ! reloadGrades) {
                    if (dataArray != null && $.isArray(dataArray) && dataArray.length > 0) {
                         multipleGradeSelector.formatGradeNames(content, dataArray, elementsPerRow);
                         multipleGradeSelector.openGradesDialog(gradesWindow, content);
                    } else {
                         warningMessage.show([textMessages["noGradesForCar"]]);
                    }
                } else {
                    $.ajax({
                        type: "get",
                        url: cp + "/ajax/gradesByModel.htm",
                        data: { modelId: modelId, prefectureIds: prefecturesIds},
                        success: function(data) {
                            if (data.length > 0) {
                                dataArray = data.split("::::");
                            } else {
                                dataArray = null;
                            }
                            requestedGrades[modelId] = dataArray;
                            if (dataArray != null && $.isArray(dataArray) && dataArray.length > 0) {
                                multipleGradeSelector.formatGradeNames(content, dataArray, elementsPerRow);
                                multipleGradeSelector.openGradesDialog(gradesWindow, content);
                            } else {
                                warningMessage.show([textMessages["noGradesForCar"]]);
                            }


                        }
                    });
                }
            }

        }
    },

    formatGradeNames: function(content, dataArray, elementsPerRow) {

    	var elementsCount = dataArray.length;
        var additionalClass;

        for (var i = 0; i < elementsCount; ) {
            var gradeWithCount = dataArray[i].split("||||");
        	var grade = gradeWithCount[0];
        	var count = gradeWithCount[1];
            if (count == null) {
                count = 0;
            }
        	if (i == 0 || i % elementsPerRow == 0) {
                content[content.length] = "<tr>";
                additionalClass = "noBorder";
            }
            else {
                additionalClass = "";
            }        	
        	
            content[content.length] = "<td><div class=\"checkboxItem ellipsis " + additionalClass + "\" ><input type=\"checkbox\" onchange=\"multipleGradeSelector.checkSelectedGradesSize(this)\" id='" + grade + "'/><label for='" + grade + "'>" + grade + "</label></div><span class=\"countGrade\" > (" + count + ")</span></td>";
            i++;

            if (i == elementsCount || (i % elementsPerRow == 0)) {
                content[content.length] = "</tr>";
            }
        	
        }

        content[content.length] = "</table><br /><a href=\"javascript:multipleGradeSelector.updateSelectedGrades();\" class=\"okButton\" id=\"multGradeButtonOk\"></a>";
        content[content.length] = "<a href=\"javascript:multipleGradeSelector.reset();\" class=\"resetButton\" id=\"multGradeButtonReset\" ></a><br/><br/><br/>";

    },


    openGradesDialog: function(gradesWindow, content) {
        gradesWindow.html(content.join(""));
        wbSearch.getWindow(wbSearch.multipleGradesWindowId).dialog('open');
        if($.browser.msie && $.browser.version < 7) {
            $("#multipleGradesWindow").css("height", $(window).height() + "px");
            $("#multipleGradesWindow").css("overflow-y", "scroll");
            gradesWindow.dialog( "option", "position", 'top' );
        }
    },

    refreshCheckboxes: function() {
        var gradeSelected = $("#htmlSearchForm input[name='keywords']");
        var gradeSelectedArray = gradeSelected.val().split(";");

        var gradeTemp = $("#multipleGradesWindow input[type='checkbox']");
        var gradeArray = [];
        for (var i = 0; i < gradeTemp.length; i++) {
            gradeArray[gradeTemp[i].id] = gradeTemp[i];
        }

        this.otherGrades = [];

        var gradeName, grade;
        for (var i = 0; i < gradeSelectedArray.length; i++) {
            gradeName = gradeSelectedArray[i];
            if (gradeName != textMessages["gradeDefaultText"] && gradeName != '') {
                grade = gradeArray[gradeName];

                if (grade != undefined) {
                    grade.checked = "checked";
                } else {
                    this.otherGrades[this.otherGrades.length] = gradeName;
                }
            }
        }
    },

    updateSelectedGrades: function() {
        var gradeNames = $("#htmlSearchForm input[name='keywords']");
        var gradesSelected = $("#multipleGradesWindow input[type='checkbox']").filter(":checked");

        var gradesValue = [];

        for (var i = 0; i < this.otherGrades.length; i++) {
             gradesValue[gradesValue.length] = this.otherGrades[i];
        }

        for (var i = 0; i < gradesSelected.length; i++) {
            gradesValue[gradesValue.length] = gradesSelected[i].id;
        }

        var newGradesVal = gradesValue.join(";");

        if (newGradesVal == '') {
           newGradesVal = textMessages["gradeDefaultText"];
        }
        gradeNames.val(newGradesVal);
        oldSuggestionBoxValue = newGradesVal;
        wbSearch.closeWindow("multipleGradesWindow");
        wbSearch.blinkSearchButton();
    },

    checkSelectedGradesSize: function(checkbox) {
        if (checkbox.checked) {
            var gradesSelected = $("#multipleGradesWindow input[type='checkbox']").filter(":checked");
            if (gradesSelected.length + this.otherGrades.length > 10) {
                 checkbox.checked = "";
                 warningMessage.show([textMessages["onlyTenGradesAllowed"]]);
            }
        }
    }

}

var requestedModels = [];

var modelWindowUtil = {
    checkboxList: null,

    initialize: function(rootNodeId, rootCheckboxId, blockCheckboxIdPrefix) {
        this.checkboxList = new CheckboxList();
        this.checkboxList.initialize(rootNodeId, rootCheckboxId, blockCheckboxIdPrefix, false);
    },

    reset: function() {
        $("#modelSearchId").val(textMessages["defaultModels"]);
        $("#modelSearchIdValue").val("");
        $("#htmlSearchForm input[name='modelGroupId']").val("");
        this.checkboxList.reset();
    },

    fillInModelWindow: function(modelWindow, prefectureWindow) {
        var objMan = $("#manufacturerSearchIdValue");
        var objManName = $("#manufacturerSearchId");
        var objManCarCount = $("#manufacturerCarsCount");
        var carsCount = 0;

        if (objMan && modelWindow) {
            var content = ["<table cellspacing='0' cellpadding='0' class=\"wideTable\"><tr><td colspan='{elementsPerRow}' class='title'>"+ objManName.val()+"&nbsp;&nbsp;"+
                textMessages["changeManufacturerText"]+"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a class=\"changeManufacturer\"href=\"javascript:wbSearch.showSelectManufacturerWindow(true);\">"+textMessages["changeManufacturerLinkText"]+
                "</a></td></tr><tr><td colspan='{elementsPerRow}'>" +
                "<input type=\"checkbox\" id=\"all-models\" onclick=\"javascript:modelWindowUtil.checkboxList.checkAll(this)\" />" +
                "<label class=\"checkAllModels\" for=\"all-models\">" + objManName.val() + textMessages["allModels"] + "</label>"+
                "<span> ({manufacturerCarsCount}" + formatNumber(objManCarCount.val()) + ")</span>" +
                "<div class=\"buttons topButtons\"><a class=\"okButton\" href=\"javascript:wbSearch.selectModel();\" ></a><a class=\"submitButton\" onclick=\"wbSearch.selectModel(); return submitMainNew('1');\" href=\"#\"></a><a class=\"resetButton\" href=\"javascript:modelWindowUtil.checkboxList.reset();\" ></a></div>" +
                "</td></tr>"];

            var manId = objMan.val();
            if (objManCarCount.val() != "") {
                content[0] = content[0].replace(/{manufacturerCarsCount}/g,"");
            }

            if (manId != undefined && manId.length > 0) {
                var manType = manId.substring(0, 1);
                if (manType == 'm') {
                    var manufacturerId = manId.substring(1, manId.length);
                    var dataArray = requestedModels[manufacturerId];
                    if (dataArray != null) {
                        if (dataArray != null && $.isArray(dataArray) && dataArray.length > 1) {
                            if (dataArray[0] == "group_grouped") {
                                content[0] = content[0].replace(/{elementsPerRow}/g,"4");
                                modelWindowUtil.fillSearchPopUpModelsGroupedByModelGroup(content, dataArray, 4);
                            } else {
                                content[0] = content[0].replace(/{elementsPerRow}/g,"5");
                                modelWindowUtil.fillSearchPopUpModelsGroupedByInitialLetter(content, dataArray, 4);
                            }
                        }
                        modelWindowUtil.openModelDialog(modelWindow, prefectureWindow, content);
                    } else {
                        $.ajax({
                            type: "get",
                            url: cp + "/ajax/modelsForManufacturer.htm",
                            data: { manId: manId.substring(1, manId.length)},
                            success: function(data) {

                                dataArray = eval(data);
                                if (dataArray != null && $.isArray(dataArray) && dataArray.length > 1) {
                                    if (dataArray[0] == "group_grouped") {
                                        content[0] = content[0].replace(/{elementsPerRow}/g,"4");
                                        modelWindowUtil.fillSearchPopUpModelsGroupedByModelGroup(content, dataArray, 4);
                                    } else {
                                        content[0] = content[0].replace(/{elementsPerRow}/g,"5");
                                        modelWindowUtil.fillSearchPopUpModelsGroupedByInitialLetter(content, dataArray, 4);
                                    }
                                }
                                requestedModels[manufacturerId] = dataArray;

                                if (objManCarCount.val() == "") {
                                    for (var i = 1; i < dataArray.length; i++) {
                                        var valueData = dataArray[i]['value'];
                                        for (var j = 0; valueData && j < valueData.length; j++) {
                                            carsCount += valueData[j]["count"];
                                        }
                                    }
                                    content[0] = content[0].replace(/{manufacturerCarsCount}/g,formatNumber(carsCount));
                                    objManCarCount.val(carsCount);
                                }

                                modelWindowUtil.openModelDialog(modelWindow, prefectureWindow, content);
                            }
                        });
                    }
                } else {
                    content[content.length] = "<br /></table>"
                    modelWindowUtil.openModelDialog(modelWindow, prefectureWindow, content);

                }
            } else {
                content[content.length] = "<br /></table>";
                modelWindowUtil.openModelDialog(modelWindow, prefectureWindow, content);
            }
        }
        if($.browser.msie && $.browser.version < 7) {
        // bullshit for ie6, if someone can make it better - please do it
            modelWindow.css("height", $(window).height() - 40 + "px");
            modelWindow.css("overflow-y", "scroll");
            modelWindow.dialog( "option", "position", 'top' );
        }
    },

    fillSearchPopUpModelsGroupedByModelGroup: function(content, dataArray, elementsPerRow) {

        for (var i = 1; i < dataArray.length; i++) {//first el is identifier - not a data
            var key = dataArray[i]['key'];
            var value = dataArray[i]['value'];
            var count = dataArray[i]['count'];
            var additionalClass = "topGrayBorder";
            var groupTitleClass;
            var buttonsClass;
            var groupRowIndex;
            if (key != undefined && key != null) { //models with model Group
                if(value.length == 0) {
                    continue; //skip empty groups
                }

                groupTitleClass = "groupTitle";
                buttonsClass = "buttons";
                groupRowIndex = content.length;
            }
            else {
                //add fake group for ungroupped models
                key = {value: 0, key: 0};
                groupTitleClass = "hidden";
                buttonsClass = "buttons";
                groupRowIndex = -1;
            }
            content[content.length] = "<tr><td colspan='" + elementsPerRow + "' class='" + additionalClass + "'>" +
                                      "<div class=\"" + groupTitleClass + "\"><span class=\"title\">" + key['value'] + "&nbsp;&nbsp;&nbsp;</span>" +
                                      "<input type=\"checkbox\" value=\"" + key['value'] + "\" id=\"mg-" + key['key'] + "\" onclick=\"javascript:modelWindowUtil.checkboxList.checkBlock(this)\" /><label class=\"group\" for=\"mg-" + key['key'] + "\">" + key['value'] + " " + textMessages["modelsForGroup"] + "<span>({carsCount})</span></label></div>" +
                                      "</td></tr>";
            var carsCount = 0;
            for (var j = 0; value && j < value.length;) {

                if (j == 0 || j % elementsPerRow == 0) {
                    content[content.length] = "<tr>";
                    additionalClass = "noBorder";
                }
                else {
                    additionalClass = "";
                }

                content[content.length] = "<td><div class=\"checkboxItem " + additionalClass + "\"><input type=\"checkbox\" value=\"" + value[j]['value'] + "\" id=\"m-"+ value[j]["key"]+"-mg-" + key['key'] + "\"" + additionalClass + " onclick=\"javascript:modelWindowUtil.checkboxList.checkSingleCheckbox(this)\" /><label for=\"m-"+ value[j]["key"]+"-mg-" + key['key'] + "\">" + value[j]["value"] +  "<span>(" + formatNumber(value[j]["count"]) +")</span></label></div></td>";
                carsCount += value[j]["count"];
                j++;

                if (j == value.length || (j % elementsPerRow == 0)) {
                    content[content.length] = "</tr>";
                }
            }
            if(groupRowIndex != -1) {
                content[groupRowIndex] = content[groupRowIndex].replace("{carsCount}", formatNumber(carsCount)); 
            }
        }
        content[content.length] = "<tr><td colspan='4' class='topGrayBorder'>" +
                                      "<div class=\"buttons\"><a class=\"okButton\" href=\"javascript:wbSearch.selectModel();\" ></a><a class=\"submitButton\" onclick=\"wbSearch.selectModel(); return submitMainNew('1');\" href=\"#\"></a><a class=\"resetButton\" href=\"javascript:modelWindowUtil.checkboxList.reset();\" ></a></div>" +
                                      "</td></tr>";
        content[content.length] = "</table><br />";
    },

    fillSearchPopUpModelsGroupedByInitialLetter: function(content, dataArray, elementsPerRow) {
        content[content.length] = "<tr class=\"hidden\"><td>" +
                  "<input type=\"checkbox\" id=\"mg-0\" /><label for=\"mg-0\"></label>" +
                  "</td></tr>";
        for (var i = 1; i < dataArray.length; i++) {//first el is identifier - not a data
            var key = dataArray[i]['key'];
            var value = dataArray[i]['value'];
            var count = dataArray[i]['count'];
            if(value.length == 0) continue;
            content[content.length] = "<tr><td class=\"topGrayBorder\">&nbsp;</td><td class=\"topGrayBorder\" valign=\"top\" colspan=\"" + (elementsPerRow)+ "\">&nbsp;" +
                                      "</td></tr>";
            content[content.length] = "<tr><td valign=\"top\" style=\"width:6%;\">" + key + "</td>";

            var modelName;
            var additionalClass;

            for (var j = 0; value && j < value.length;) {
                modelName = value[j]["value"];

                if (j != 0 && j % elementsPerRow == 0) {
                    content[content.length] = "<tr><td>&nbsp;</td>";
                }

                additionalClass = (j == 0 || j % elementsPerRow == 0) ? "noBorder" : "";

                var colspan = null;
                if ((j + 1) == value.length) {
                    colspan = elementsPerRow - (j % elementsPerRow) - 1;
                }

                content[content.length] = "<td style=\"width:23%;\" ><div class=\"checkboxItem " + additionalClass + "\"><input type=\"checkbox\" value=\"" + modelName + "\" id=\"m-" + value[j]["key"] + "-mg-0\" onclick=\"javascript:modelWindowUtil.checkboxList.checkSingleCheckbox(this)\" /><label for=\"m-" + value[j]["key"] + "-mg-0\">" + modelName + "<span>(" + formatNumber(value[j]["count"]) + ")</span></label></div></td>";
                j++;

                if (colspan !== null) {
                    content[content.length] = "<td colspan=\"" + colspan + "\" style=\"width:" + colspan * 23 + "%;\" >&nbsp;</td>";
                }

                if (j == value.length || (j % elementsPerRow == 0)) {
                    content[content.length] = "</tr>";
                }
            }
        }
        content[content.length] = "<tr><td colspan='5' class='topGrayBorder'>" +
                                      "<div class=\"buttons\"><a class=\"okButton\" href=\"javascript:wbSearch.selectModel();\" ></a><a class=\"submitButton\" onclick=\"wbSearch.selectModel(); return submitMainNew('1');\" href=\"#\"></a><a class=\"resetButton\" href=\"javascript:modelWindowUtil.checkboxList.reset();\" ></a></div>" +
                                      "</td></tr>";
        content[content.length] = "</table><br />";
    },

    openModelDialog: function(modelWindow, prefectureWindow, content) {
        clickTaleCall("modelWindowUtil.openModelDialog(" +
                      modelWindow + ", " +
                      prefectureWindow + ", " +
                      content + ");");
        modelWindow.html(content.join(""));

        if (prefectureWindow != null) {
            prefectureWindow.dialog("close");
        }
        modelWindow.css("display", "block");
        modelWindow.dialog('open');
        wbSearch.autoresizeSelectModalWindow();
        if($.browser.msie && $.browser.version < 7) {
        // bullshit for ie6, if someone can make it better - please do it
            $("#modelWindow").css("height", $(window).height() + "px");
            $("#modelWindow").css("overflow-y", "scroll");
            modelWindow.dialog( "option", "position", 'top' );
        }
    },

    checkAll: function(element) {
        var allModels = $("#all-models");
        if($(allModels).is(":checked")) {
            $(allModels).removeAttr("checked");
        }
        else {
            $(allModels).attr("checked", "checked");
        }
        this.checkboxList.checkAll(element);
        wbSearch.selectModel();
    },

    refreshCheckboxes: function() {
        var modelGroupsField = $("#htmlSearchForm input[name='modelGroupId']");
        var modelIdsField = $("#modelSearchIdValue");
        var modelNamesField = $("#modelSearchId");
        var allModelsField = $("#allModelsChecked");

        if($(allModelsField).val() == "true") {
            $("#modelWindow input[type='checkbox']").attr("checked", "checked");
            return;            
        }

        if($(modelGroupsField).val() != "") {
            var groups = $(modelGroupsField).val().split(",");
            for(var i in groups) {
                $("#modelWindow [id$='mg-" + groups[i] + "']").attr("checked", "checked");
            }
        }
        if($(modelIdsField).val() != "") {
            var models = $(modelIdsField).val().split(",");
            for(var i in models) {
                $("#modelWindow [id^='m-" + models[i] + "']").attr("checked", "checked");
            }
        }
    }
}



var warningMessage = {

    warningWindowInitialized: false,
    show: function(errorsArray) {
        clickTaleCall("warningMessage.show(" + errorsArray + ");");
        var warningWindow = $("#warningWindow");
        if(!this.warningWindowInitialized) {
        	warningWindow.dialog(
            {
                title: textMessages["warning"],
                resizable: false,
                width:  450,
                autoOpen: false,
                modal: true,
                closeOnEscape: true,
                close: function(event, ui) { clickTaleCall("wbSearch.closeWindow('warningWindow').dialog('close');") }
             });
            this.warningWindowInitialized = true;
            warningWindow.parent("div")
            .find(".ui-dialog-title")
            .after("<a class=\"closeButton\" href=\"javascript:wbSearch.closeWindow('warningWindow')\"></a>");
        }

        var warningContent = [];
        for (var i = 0; i < errorsArray.length; i++) {
            warningContent[warningContent.length] = "<div>" + errorsArray[i] + "</div><br/>";
        }

        warningContent[warningContent.length] = "<div class=\"okButtonWrapper\"><a href=\"javascript:wbSearch.closeWindow('warningWindow')\" class=\"okButton\"></a></div>";

        $("#warningWindowContent").html(warningContent.join(""));


        warningWindow.css("display", "block");
        warningWindow.dialog('open');
    }
}

function formatNumber(value) {
    value = value + "";
    var digitIndex = 3;
    var result="";
    for(var i = (value.length - 1); i >= 0; i--) {
        result = value.charAt(i) + result;
        digitIndex --;
        if(digitIndex == 0 && i != 0) {
            digitIndex = 3;
            result = "," + result;
        }
    }

    return result;
}

function isDigit(value) {
   var digit = value.replace(/[^\d]/g, "");
   return digit == value;
}

function clickTaleCall(parameter) 
{
    if(typeof ClickTaleExec=='function')
        ClickTaleExec(parameter);
}

var facetedCarsTable = {

    uiElementNames: [],
    uiElementsVals: [],
    isInited: false,
    isAvailable: true,

    toggleVisibility: function(isAvailableParam) {
        if (this.isAvailable != isAvailableParam) {

            if (isAvailableParam) {
                $('div.round-panel').show();
            } else {
                this.hide();
                $('div.round-panel').hide();

            }

            this.isAvailable = isAvailableParam;
        }
    },
    init: function() {
        if (!this.isInited) {
            var form = $('#htmlSearchForm');
            var bodyIdTemp = $("#bodyIdTemp").val();
            if (bodyIdTemp.length > 0) {
                form = form.clone();
                form.find("input[name='bodies']").val(bodyIdTemp);
            }
            
            $.post(
                cp + "/ajax/facetedCarsTable.htm",
                form.serialize(),
                function(data) {
                    this.uiElementNames = [];
                    this.uiElementsVals = [];

                    var dataArray = eval('(' + data + ')');
                    var yearPrice = dataArray['yearPrice'];
                    var priceMileage = dataArray['priceMileage'];
                    var yearMileage = dataArray['yearMileage'];
                    facetedCarsTable.fillSubTable(yearPrice, 'yearPrice', 1);
                    facetedCarsTable.fillSubTable(priceMileage, 'priceMileage', 2);
                    facetedCarsTable.fillSubTable(yearMileage, 'yearMileage', 3);
                    facetedCarsTable.isInited = true;
                }
            );
        }
    },

    hide: function() {
        $('div.show-hide-panel').hide();
    },

    show: function() {
        facetedCarsTable.init();
        $('div.show-hide-panel').show()
    },

    fillSubTable: function(data, subTableName, index) {
        var tableParent = $('#' + subTableName + 'Table');

        var tableContent = ['<div class="table"><table cellpadding="0" cellspacing="0" border="0">' +
                            '<thead><th colspan="2" class="f">中古車情報の相場</th>'];

        //table header
        var horisontalLabels = data['horisontalLabels'];
        var length =  horisontalLabels.length;
        var th;
        var secondColumnClass = "class=\"s\"";
        for (var i = 0; i < length; i++) {
            if (i == length -1) {
                th = '<th class="l">';
            } else {
                th = '<th ' + secondColumnClass + '>';
                secondColumnClass = "";
            }
            tableContent[tableContent.length] = th + horisontalLabels[i] + '</th>';
        }
        tableContent[tableContent.length] = '</thead><tbody>';

        //table body




        var carsDistr = data['carsDistribution'];
        var verticalLabels = data['verticalLabels'];

        var vElementNames = data['vCorrFields'];
        var vElementValues = data['vCorrFieldsValues'];
        var vElementNamesTag = 'v' + index;
        var vElementValuesTag = 'v' + index;
        this.uiElementNames[vElementNamesTag] = vElementNames;
        this.uiElementsVals[vElementValuesTag] = vElementValues;

        var hElementNames = data['hCorrFields'];
        var hElementValues = data['hCorrFieldsValues'];
        var hElementNamesTag = 'h' + index;
        var hElementValuesTag = 'h' + index;
        this.uiElementNames[hElementNamesTag] = hElementNames;
        this.uiElementsVals[hElementValuesTag] = hElementValues;

        var column, carsCount, tdClass;
        length = carsDistr.length;
        for (var i = 0; i < length; i++) {
            if (i == length - 1) {
                tableContent[tableContent.length] = '<tr class="last-tr">';
            } else {
                tableContent[tableContent.length] = '<tr>';
            }
            column = carsDistr[i];
            for (var j = 0; j < column.length; j ++) {

                if (j == column.length - 1) {
                    tdClass = 'l';
                } else {
                    tdClass = '';
                }


                if (i == 0 && j == 0) {
                    tableContent[tableContent.length] = '<td class="f1" colspan="2" style="text-align:right;">合計 <span class="red">' +
                                                        $('#carsCountVal').html() +
                                                        '</span>台&nbsp;&nbsp;</td>';
                } else if (j == 0) {
                    tableContent[tableContent.length] = '<td class="f2">' + verticalLabels[i - 1] + '</td><td class="f3">';
                    if (carsDistr[i][0] > 0) {
                        tableContent[tableContent.length] = '<a href="#" onclick="'+ prepareFSApplyScriptString(vElementNamesTag, vElementValuesTag, i - 1, '','','') + '">';
                        tableContent[tableContent.length] = carsDistr[i][0] + '台</a>';
                    } else {
                        tableContent[tableContent.length] = '&nbsp;';
                    }
                    tableContent[tableContent.length] = '</td>';
                } else if (i == 0) {
                    carsCount = carsDistr[i][j];
                    if (carsCount < 1) {
                        tableContent[tableContent.length] = '<td class="' + tdClass + '">&nbsp;</td>';
                    } else {
                        tableContent[tableContent.length] = '<td class="' + tdClass + '">' +
                                                            '<a href="#" onclick="'+ prepareFSApplyScriptString('', '', '', hElementNamesTag,hElementValuesTag,j - 1) + '">'
                                + carsCount + '台</td></a>';
                    }
                } else {
                    carsCount = carsDistr[i][j];
                    if (carsCount < 1) {
                        tableContent[tableContent.length] = '<td class="' + tdClass + '">&nbsp;</td>';
                    } else {
                        var a = '<a href="#" onclick="'+ prepareFSApplyScriptString(vElementNamesTag, vElementValuesTag, i - 1, hElementNamesTag,hElementValuesTag,j - 1) + '">';
                        if (carsCount < 20) {
                            tableContent[tableContent.length] = '<td class="low ' + tdClass + '">' + a + carsCount + '台</a></td>';
                        } else if (carsCount < 50) {
                            tableContent[tableContent.length] = '<td class="prelow ' + tdClass + '">' + a  + carsCount + '台</a></td>';
                        } else if (carsCount < 90) {
                            tableContent[tableContent.length] = '<td class="mid ' + tdClass + '">' + a  + carsCount + '台</a></td>';
                        } else if (carsCount < 150) {
                            tableContent[tableContent.length] = '<td class="prehigh ' + tdClass + '">' + a  + carsCount + '台</a></td>';
                        } else {
                            tableContent[tableContent.length] = '<td class="high ' + tdClass + '">' + a  + carsCount + '台</a></td>';
                        }
                    }

                }
            }

            tableContent[tableContent.length] = '</tr>';
        }

        tableContent[tableContent.length] = '</tbody></table></div>';


        tableParent.html(tableContent.join(''));

    }


}


function prepareFSApplyScriptString(vElementNamesTag, vElementValuesTag, vPos, hElementNamesTag, hElementValuesTag, hPos) {
    return 'return fsApplyVal(\'' + vElementNamesTag + '\',\'' + vElementValuesTag + '\',\'' + vPos + '\',\'' +
           hElementNamesTag + '\',\'' + hElementValuesTag + '\',\'' + hPos + '\')';
}

function fsApplyVal(vElementNamesTag, vElementValuesTag, vPos, hElementNamesTag, hElementValuesTag, hPos) {

    var form = document.getElementById("htmlSearchForm");

    if (vElementNamesTag != '' && vElementValuesTag != '' && vPos != '') {
        var elementNames = facetedCarsTable.uiElementNames[vElementNamesTag];
        var elementVals = facetedCarsTable.uiElementsVals[vElementValuesTag][vPos];
        for (var i = 0; i < elementNames.length; i++) {
            form.elements[elementNames[i]].value = elementVals[i];
        }
    }

    if (hElementNamesTag != '' && hElementValuesTag != '' && hPos != '') {
        var elementNames = facetedCarsTable.uiElementNames[hElementNamesTag];
        var elementVals = facetedCarsTable.uiElementsVals[hElementValuesTag][hPos];
        for (var i = 0; i < elementNames.length; i++) {
            form.elements[elementNames[i]].value = elementVals[i];
        }
    }

    submitMainSL('1');
    return false;
}

function thousandSeparator(n,sep)
{
    var sRegExp = new RegExp('(-?[0-9]+)([0-9]{3})'), sValue=n+'';
    if (sep === undefined)
    {
        sep=',';
    }

    while(sRegExp.test(sValue))
    {
        sValue = sValue.replace(sRegExp, '$1'+sep+'$2');
    }

    return sValue;
}

