﻿var searchActiveTab = ""; // ИД активного таба
var query = "";

$(document).ready(function () {

});

(function ($) {
    $(function () {
        $('ul.qstabs').delegate('li:not(.current)', 'click', function () {
            getQSTab(this.id); // в случае клика по списку табов
        })
    })
})(jQuery)

function getQSTab(id) {
    // отображение контента DIV согласно выбранному пункту в закладках
    $('.li-' + id).addClass('current').siblings().removeClass('current')
			    .parents('div.qssection').find('div.qsbox').hide().eq($('.li-' + id).index()).fadeIn(0);

    searchActiveTab = id; // получить ИД активного таба

    if (typeof $("#ChouseAreaList_" + id).val() != "undefined") {// элемент присутствует на форме?
        if ($("#ChouseAreaList_" + id).attr("className") != "multiSelect") { // элемент инициализирован?
            $("#ChouseAreaList_" + id).multiSelect({ selectAllText: '(Все районы)', noneSelected: '(Все районы)', oneOrMoreSelected: '*', listHeight: '290' }, function (el) {
                if (getML) { getML(1); }
            });
        }
    }

    if (typeof $("#ChouseBuildingType_" + id).val() != "undefined") { // элемент присутствует на форме?
        if ($("#ChouseBuildingType_" + id).attr("className") != "multiSelect") { // элемент инициализирован?
            $("#ChouseBuildingType_" + id).multiSelect({ selectAllText: '(Любой тип)', noneSelected: '(Любой тип)', oneOrMoreSelected: '*', listHeight: '290' }, function (el) {
                if (getML) { getML(1); }
            });
        }
    }

    if (typeof $("#ChouseEstateType_" + id).val() != "undefined") { // элемент присутствует на форме?
        if ($("#ChouseEstateType_" + id).attr("className") != "multiSelect") { // элемент инициализирован?
            $("#ChouseEstateType_" + id).multiSelect({ selectAllText: '(Любой тип)', noneSelected: '(Любой тип)', oneOrMoreSelected: '*', listHeight: '290' }, function (el) {
                if (getML) { getML(1); }
            });
        }
    }

    if (typeof $("#ChouseCountry_" + id).val() != "undefined") { // элемент присутствует на форме?
        if ($("#ChouseCountry_" + id).attr("className") != "multiSelect") {  // элемент инициализирован?
            $("#ChouseCountry_" + id).multiSelect({ selectAllText: '(Любая страна)', noneSelected: '(Любая страна)', oneOrMoreSelected: '*', listHeight: '290' }, function (el) {
                if (getML) { getML(1); }
            });
        }
    }

    syncElementValues(id);

    // получить количество объектов
    if (getML) { getML(1); }

    // цвет формы быстропоиска
    if (id == '10') document.getElementById('ctl00_QuickSearch_ctl00_CountObjects').style.backgroundColor = '#03abed';
    if (id == '20') document.getElementById('ctl00_QuickSearch_ctl00_CountObjects').style.backgroundColor = '#ff6600';
    if (id == '21') document.getElementById('ctl00_QuickSearch_ctl00_CountObjects').style.backgroundColor = '#ec7a1a';
    if (id == '60') document.getElementById('ctl00_QuickSearch_ctl00_CountObjects').style.backgroundColor = '#125bc2';
    if (id == '40') document.getElementById('ctl00_QuickSearch_ctl00_CountObjects').style.backgroundColor = '#2e771d';
    if (id == '41') document.getElementById('ctl00_QuickSearch_ctl00_CountObjects').style.backgroundColor = '#20a600';
    if (id == '70') document.getElementById('ctl00_QuickSearch_ctl00_CountObjects').style.backgroundColor = '#efb313';

    curr_attr = '';
    $('.multiSelect').hover(
        function () {
            var offset = $(this).offset();
            curr_attr = $(this).attr('title');
            $(this).removeAttr('title');
            if (curr_attr == '') return false;
        }, function () {
            $(this).attr('title', curr_attr);
        }
    );
}   

function onclick_send(hf) {
    document.getElementById(hf).value = query; // GenerateQuery();
}

function CheckBuildingType(TypeId) {
    if (document.getElementById("ChouseBuildingType_" + TypeId)) {
        var name = "#ChouseBuildingType_" + TypeId;
        if ( readCookie(name) != "" ) eraseCookie(name);
        if ($('#divChouseBuildingType_' + TypeId + ' .selectAll :input').attr('checked') == false) {
            var PreBuildingType = $(name).attr('title');
            createCookie(name, $(name).attr('title'), "1");
            return PreBuildingType;
        }
    } 
    
    return "";
}

function CheckEstateType(TypeId) {
    if (document.getElementById("ChouseEstateType_" + TypeId)) {
        var name = "#ChouseEstateType_" + TypeId;
        if ( readCookie(name) != "" ) eraseCookie(name);
        if ( $('#divChouseEstateType_' + TypeId + ' .selectAll :input').attr('checked') == false) {
            var PreEstateType = $(name).attr('title');
            createCookie(name, $(name).attr('title'), "1");
            return PreEstateType;
        }
    } 

    return "";
}

function CheckOperation(TypeId) {
    var PreOperation;
    if (document.getElementById("ChouseOperationSale_" + TypeId)) {
        var cookienamesale = "#ChouseOperationSale_" + TypeId;
        var cookienamerent = "#ChouseOperationRent_" + TypeId;

        if (document.getElementById("ChouseOperationSale_" + TypeId).checked) {
            if (readCookie(cookienamesale) != "") eraseCookie(cookienamesale);
            PreOperation = "Operation:10;";
            createCookie(cookienamesale, "10", "1");

            eraseCookie(cookienamerent);
        } else {
            if (readCookie(cookienamerent) != "") eraseCookie(cookienamerent);
            PreOperation = "Operation:20;";
            createCookie(cookienamerent, "20", "1");

            eraseCookie(cookienamesale);
        }
    } else {
        PreOperation = "";
    }
    return PreOperation;
}

function CheckPrice(TypeId) {
    var PrePrice = "";
    if (document.getElementById("ChousePriceMin_" + TypeId)) {
        var cookienamemin = "#ChousePriceMin_" + TypeId;
        var cookienamemax = "#ChousePriceMax_" + TypeId;

        if (readCookie(cookienamemin) != "") eraseCookie(cookienamemin);
        if (readCookie(cookienamemax) != "") eraseCookie(cookienamemax);

        if ($(cookienamemin).attr('value')) {
            PrePrice += "PriceMin:" + $(cookienamemin).attr('value') + ";";
            createCookie(cookienamemin, $(cookienamemin).attr('value'), "1");
        }
        if ($(cookienamemax).attr('value')) {
            PrePrice += "PriceMax:" + $(cookienamemax).attr('value') + ";";
            createCookie(cookienamemax, $(cookienamemax).attr('value'), "1");
        }
    }
    return PrePrice;
}

function CheckRegion(TypeId) {
    if (document.getElementById("ChouseAreaList_" + TypeId)) {
        var name = "#ChouseAreaList_" + TypeId;
        if (readCookie(name) != "") eraseCookie(name);
        var PreDistrict = $(name).attr('title');
        if ($('#divChouseAreaList_' + TypeId + ' .selectAll :input').attr('checked') == false) {
            createCookie(name, $(name).attr('title'), "1");
        }
        return PreDistrict;
    }
    else if (document.getElementById("ChouseCountry_" + TypeId)) {
        var name = "#ChouseCountry_" + TypeId;
        if (readCookie(name) != "") eraseCookie(name);
        var PreDistrict = $(name).attr('title');
        if ($('#divChouseCountry_' + TypeId + ' .selectAll :input').attr('checked') == false) {
            createCookie(name, $(name).attr('title'), "1");
        }
        return PreDistrict;
    } 
    return "";
}

function ChouseRegionChange(obj) {
    var name = "#ChouseAreaList_" + searchActiveTab;
    if (typeof $(name).val() != "undefined") {
        if (readCookie(name) != "") eraseCookie(name);
        //$(name).attr('title', "");
    }
}

function GQ_getAllDistricts(TypeId) {
    var count = document.getElementById("ChouseAreaList_" + TypeId).GetItemCount();
    var Districts = [];
    for (var i = 1; i < count; i++) {
        var item = document.getElementById("ChouseAreaList_" + TypeId).GetItem(i);
        Districts.push(item.value);
    }
    return Districts.join(",");
}
function OnRegionChanged(ChouseRegion) {
    document.getElementById("ChouseAreaList_" + searchActiveTab).PerformCallback(ChouseRegion.GetValue().toString());
}

function CheckRooms(TypeId) {
    var PreRooms = [];
    if (document.getElementById("ChouseRooms1_" + TypeId)) {
        if (readCookie("#ChouseRooms1_" + TypeId) != "") eraseCookie("#ChouseRooms1_" + TypeId);
        if (readCookie("#ChouseRooms2_" + TypeId) != "") eraseCookie("#ChouseRooms2_" + TypeId);
        if (readCookie("#ChouseRooms3_" + TypeId) != "") eraseCookie("#ChouseRooms3_" + TypeId);
        if (readCookie("#ChouseRooms4_" + TypeId) != "") eraseCookie("#ChouseRooms4_" + TypeId);
        if (readCookie("#ChouseRooms5_" + TypeId) != "") eraseCookie("#ChouseRooms5_" + TypeId);
        if (readCookie("#ChouseRooms6_" + TypeId) != "") eraseCookie("#ChouseRooms6_" + TypeId);
        
        if (document.getElementById("ChouseRooms1_" + TypeId).checked) {
            PreRooms.push("1");
            createCookie("#ChouseRooms1_" + TypeId, "1", "1");
        }
        if (document.getElementById("ChouseRooms2_" + TypeId).checked) {
            PreRooms.push("2");
            createCookie("#ChouseRooms2_" + TypeId, "2", "1");
        }
        if (document.getElementById("ChouseRooms6_" + TypeId)) {
            if (document.getElementById("ChouseRooms6_" + TypeId).checked) {
                PreRooms.push("6");
                createCookie("#ChouseRooms6_" + TypeId, "6", "1");
            }
        } else {
            if (document.getElementById("ChouseRooms3_" + TypeId).checked) {
                PreRooms.push("3");
                createCookie("#ChouseRooms3_" + TypeId, "3", "1");
            }
            if (document.getElementById("ChouseRooms4_" + TypeId).checked) {
                PreRooms.push("4");
                createCookie("#ChouseRooms4_" + TypeId, "4", "1");
            }
            if (document.getElementById("ChouseRooms5_" + TypeId).checked) {
                PreRooms.push("5");
                createCookie("#ChouseRooms5_" + TypeId, "5", "1");
            }
        }  
    }
    PreRooms = PreRooms.join(",");
    if (PreRooms != "")
        PreRooms = "Rooms:" + PreRooms + ";";
    return PreRooms;
}

function CheckSAll(TypeId) {
    var PrePrice = "";
    var cookienamemin = "";
    var cookienamemax = "";
    if (document.getElementById("ChouseSAllMin_" + TypeId)) {
        cookienamemin = "#ChouseSAllMin_" + TypeId;
        cookienamemax = "#ChouseSAllMax_" + TypeId;

        if (readCookie(cookienamemin) != "") eraseCookie(cookienamemin);
        if (readCookie(cookienamemax) != "") eraseCookie(cookienamemax);

        if ($(cookienamemin).attr('value')) {
            PrePrice += "SAllMin:" + $(cookienamemin).attr('value') + ";";
            createCookie(cookienamemin, $(cookienamemin).attr('value'), "1");
        }
        if ($(cookienamemax).attr('value')) {
            PrePrice += "SAllMax:" + $(cookienamemax).attr('value') + ";";
            createCookie(cookienamemax, $(cookienamemax).attr('value'), "1");
        }
    }
    if (document.getElementById("ChouseSAreaMin_" + TypeId)) {
        cookienamemin = "#ChouseSAreaMin_" + TypeId;
        cookienamemax = "#ChouseSAreaMax_" + TypeId;

        if (readCookie(cookienamemin) != "") eraseCookie(cookienamemin);
        if (readCookie(cookienamemax) != "") eraseCookie(cookienamemax);

        if ($(cookienamemin).attr('value')) {
            PrePrice += "SAreaMin:" + $(cookienamemin).attr('value') + ";";
            createCookie(cookienamemin, $(cookienamemin).attr('value'), "1");
        }
        if ($(cookienamemax).attr('value')) {
            PrePrice += "SAreaMax:" + $(cookienamemax).attr('value') + ";";
            createCookie(cookienamemax, $(cookienamemax).attr('value'), "1");
        }
    }
    if (document.getElementById("ChouseSLivingMin_" + TypeId)) {
        cookienamemin = "#ChouseSLivingMin_" + TypeId;
        cookienamemax = "#ChouseSLivingMax_" + TypeId;

        if (readCookie(cookienamemin) != "") eraseCookie(cookienamemin);
        if (readCookie(cookienamemax) != "") eraseCookie(cookienamemax);

        if ($(cookienamemin).attr('value')) {
            PrePrice += "SLivingMin:" + $(cookienamemin).attr('value') + ";";
            createCookie(cookienamemin, $(cookienamemin).attr('value'), "1");
        }
        if ($(cookienamemax).attr('value')) {
            PrePrice += "SLivingMax:" + $(cookienamemax).attr('value') + ";";
            createCookie(cookienamemax, $(cookienamemax).attr('value'), "1");
        }
    }
    return PrePrice;
}

//дропдаун-мультиселекты
var textSeparator = ";";
function OnListBoxSelectionChanged(listBox, args, dropdownBox) {
    if (args.index == 0) {
        listBox.UnselectAll();
        listBox.SelectIndices([0]);
    } else {
        listBox.UnselectIndices([0]);
    }
    if (listBox.GetSelectedItems() == "")
        listBox.SelectIndices([0]);
    UpdateText(listBox, dropdownBox);
}
function UpdateText(listBox, dropdownBox) {
    var selectedItems = listBox.GetSelectedItems();
    if (document.getElementById(dropdownBox)) {
        document.getElementById(dropdownBox).SetText(GetSelectedItemsText(selectedItems));
    }
}
function GetSelectedItemsText(items) {
    var texts = [];
    for (var i = 0; i < items.length; i++)
        texts.push(items[i].text);
    return texts.join(textSeparator);
}

//готовим данные для отправки на сервер
var TypeLoaded = [];
var tmt;

function GenerateQuery() {
    var TypeId = searchActiveTab;

    //window['SQButton_' + TypeId].Enabled = false;

    var PreQuery = "Type:" + TypeId + ";";
    //вид операпции
    if (typeof CheckOperation == 'function') {
        var PreOperation = CheckOperation(TypeId);
        if (PreOperation != "") PreQuery += PreOperation;
    }
    //цена,площадь
    if (typeof CheckPrice == 'function') {
        var PrePrice = CheckPrice(TypeId);
        if (PrePrice != "") PreQuery += PrePrice;
    }
    if (typeof CheckSAll == 'function') {
        var PreSAll = CheckSAll(TypeId);
        if (PreSAll != "") PreQuery += PreSAll;
    }
    //комнатность
    if (typeof CheckRooms == 'function') {
        var PreRooms = CheckRooms(TypeId);
        if (PreRooms != "") PreQuery += PreRooms;
    }
    //районы
    if (typeof CheckRegion == 'function') {
        var PreDistrict = CheckRegion(TypeId);
        PreQuery += "Districts:" + PreDistrict + ";";
    }
    //тип постройки
    if (typeof CheckBuildingType == 'function') {
        var PreBuildingType = CheckBuildingType(TypeId);
        if (PreBuildingType != "") PreQuery += "BuildingType:" + PreBuildingType + ";";
    }
    //тип недвижимости
    if (typeof CheckEstateType == 'function') {
        var PreEstateType = CheckEstateType(TypeId);
        if (PreEstateType != "") PreQuery += "EstateType:" + PreEstateType + ";";
    }
    //alert(PreQuery);
    return PreQuery;
}


function GetObjectCount(Condition) {
    document.getElementById("object_count_label").innerHTML = "???";
    GetObjectCountService.Service1.GetObjectsCount(Condition, SucceedCallback);
}
function SucceedCallback(result) {
    //alert(result);
    document.getElementById("object_count_label").innerHTML = result;
}

function getML(i) {
    query = GenerateQuery();
    GetObjectCount(GenerateQuery());
}
