﻿var lastCall = 0;
var searchButtonLeft = 0;
var timerOn = false;
var counting = 0;
var submiting = 0;

if ($.Params.Values['tab'] == '3') { $('.search-list-options-params').css('display', 'none'); }
else { $('.search-list-options-params').css('display', 'block'); }

function PrintOffers() {
    var selectedIds = GetChecked();
    if (selectedIds != '') {
        var address = 'PrintOffers.aspx?selectedOffers=' + selectedIds;
        window.open(address, '', 'width=890,height=800,scrollbars=yes');
    }
    else { alert('Proszę zaznaczyć oferty do drukowania.'); }
}

function GetQueryString() {
    return document.URL.substring(document.URL.indexOf('?'));
}

$(window).scroll(function () {
    ShowHideSearchButton();
});

$(window).resize(function () {
    PositionSearchButton();
    ShowHideSearchButton();
});

function ShowHideSearchButton() {
    var position1 = $(btnShowFiltersClientID).position();
    var top1 = position1.top;
    var trigger1 = ($(window).scrollTop() + $(window).height()) - top1 - 24;
    $('#fixedSearchButton').toggle(trigger1 <= 0);
}

function PositionSearchButton() {
    var position = $(btnShowFiltersClientID).offset();
    searchButtonLeft = position.left;
    $('#fixedSearchButton').css('left', searchButtonLeft - 40);
}

function SkyscrapperLoad() {
    timerOn = true;
    setTimeout(Timer, 500);
}

function Timer() {
    var skay = document.getElementById('skyscrapper');
    var width = skay.offsetWidth;

    if (width > 0 && timerOn) {
        var position = $(btnShowFiltersClientID).offset();
        searchButtonLeft = position.left;
        $('#fixedSearchButton').css('left', searchButtonLeft - 42);
        var panel = document.getElementById('panel-search-container');
        if (panel == undefined) {
            panel = document.getElementById('search-list-left');
        }
        if (panel != undefined) {
            skay.style.marginTop = panel.offsetTop + 'px';
            var page = document.getElementById('page');
            page.style.width = '1120px';
        }
        timerOn = false;
    }
    if (timerOn) { setTimeout(Timer, 100); }
    setTimeout(function () { timerOn = false; }, 1000);
}

function OnSucceededGetFilters(result) {
    ShowHideFilters();
    $('#filterBox').html(result);
    PositionSearchButton();
    ShowHideSearchButton();
}

function ShowHideFilters() {
    //    $(searchBoxClientID).toggle($(ddlEstateTypeClientID).val() > 0);
    //    $(btnShowClientID).toggle($(ddlEstateTypeClientID).val() <= 0);
}

function SetEstateTypeText() { $(txtEstateTypeClientID).val($(ddlEstateTypeClientID + ' :selected').text()); }
function SetOfferTypeText() { $(txtOfferTypeClientID).val($(ddlOfferTypeClientID + ' :selected').text()); }
function SetCurrencyText() { $(txtCurrencyClientID).val($(ddlCurrencyClientID + ' :selected').text()); }
function SetSortText() { $(txtSortClientID).val($(ddlSortClientID + ' :selected').text()); }

$(document).ready(function () {
    $(".search-list-container").mouseenter(function () {
        $(this).children(".cookieControls").css("display", "block");
    }).mouseleave(function () {
        $(this).children(".cookieControls").css("display", "none");
    });
    PositionSearchButton();

    $(ddlCurrencyClientID).change(function () {
        SetCurrencyText();
    });
    $(ddlSortClientID).change(function () {
        SetSortText();
    });
    $(ddlOfferTypeClientID).change(function () {
        SetOfferTypeText();
        CountOffers();
    });

    $(ddlEstateTypeClientID).change(function () {
        SetEstateTypeText();
        WebServices.WS_Search.GetFilters($(ddlEstateTypeClientID).val(), OnSucceededGetFilters);
        CountOffers();
    });

    $(cbxPhotoClientID).change(function () { CountOffers(); });
    $(cbxRNSClientID).change(function () { CountOffers(); });

    $('.search-box-left-title-location').click(function (event) {
        if ($(this).hasClass('link') == false)
            return;

        $('#search-list-left-shortcuts').hide('slow');
        $('#search-list-left-location').show('slow');

        $('.search-box-left-title-shortcuts').addClass('link');
        $('.search-box-left-title-location').removeClass('link');
    });
    $('.search-box-left-title-shortcuts').click(function (event) {
        if ($(this).hasClass('link') == false)
            return;

        $('#search-list-left-location').hide('slow');
        $('#search-list-left-shortcuts').show('slow');

        $('.search-box-left-title-location').addClass('link');
        $('.search-box-left-title-shortcuts').removeClass('link');
    });

    $(txtPriceFromClientID).numeric("");
    $(txtPriceToClientID).numeric("");
    $(txtPricePerMeterFromClientID).numeric("");
    $(txtPricePerMeterToClientID).numeric("");
    $(txtSquareFromClientID).numeric("");
    $(txtSquareToClientID).numeric("");

    $(txtPriceFromClientID).keyup(function () { CountOffers(); });
    $(txtPriceToClientID).keyup(function () { CountOffers(); });
    $(txtPricePerMeterFromClientID).keyup(function () { CountOffers(); });
    $(txtPricePerMeterToClientID).keyup(function () { CountOffers(); });
    $(txtSquareFromClientID).keyup(function () { CountOffers(); });
    $(txtSquareToClientID).keyup(function () { CountOffers(); });

    $(txtPriceFromClientID).focusin(function () { if ($(txtPriceFromClientID).val() == "od") $(txtPriceFromClientID).val(""); });
    $(txtPriceFromClientID).focusout(function () { if ($(txtPriceFromClientID).val() == "") $(txtPriceFromClientID).val("od"); });
    $(txtPriceToClientID).focusin(function () { if ($(txtPriceToClientID).val() == "do") $(txtPriceToClientID).val(""); });
    $(txtPriceToClientID).focusout(function () { if ($(txtPriceToClientID).val() == "") $(txtPriceToClientID).val("do"); });
    $(txtPricePerMeterFromClientID).focusin(function () { if ($(txtPricePerMeterFromClientID).val() == "od") $(txtPricePerMeterFromClientID).val(""); });
    $(txtPricePerMeterFromClientID).focusout(function () { if ($(txtPricePerMeterFromClientID).val() == "") $(txtPricePerMeterFromClientID).val("od"); });
    $(txtPricePerMeterToClientID).focusin(function () { if ($(txtPricePerMeterToClientID).val() == "do") $(txtPricePerMeterToClientID).val(""); });
    $(txtPricePerMeterToClientID).focusout(function () { if ($(txtPricePerMeterToClientID).val() == "") $(txtPricePerMeterToClientID).val("do"); });
    $(txtSquareFromClientID).focusin(function () { if ($(txtSquareFromClientID).val() == "od") $(txtSquareFromClientID).val(""); });
    $(txtSquareFromClientID).focusout(function () { if ($(txtSquareFromClientID).val() == "") $(txtSquareFromClientID).val("od"); });
    $(txtSquareToClientID).focusin(function () { if ($(txtSquareToClientID).val() == "do") $(txtSquareToClientID).val(""); });
    $(txtSquareToClientID).focusout(function () { if ($(txtSquareToClientID).val() == "") $(txtSquareToClientID).val("do"); });

    SetOfferTypeText();
    SetEstateTypeText();
    SetCurrencyText();
    SetSortText();

    ShowHideFilters();
    ShowHideSearchButton();
    //GenerateLocationCodes();
});


function GetQSIntValue(value) {
    if (value.length == 0) { return -2; }
    else { return value; }
}

function getOfferType() { return $(ddlOfferTypeClientID).val(); }

function getPriceFrom() {
    var p = $(txtPriceFromClientID).val();
    if (p != "od" && p != "") { return p; }
    else { return null; }
}

function getPriceTo() {
    var p = $(txtPriceToClientID).val();
    if (p != "do" && p != "") { return p; }
    else { return null; }
}

function getPricePerMeterFrom() {
    var p = $(txtPricePerMeterFromClientID).val();
    if (p != "od" && p != "") { return p; }
    else { return null; }
}

function getPricePerMeterTo() {
    var p = $(txtPricePerMeterToClientID).val();
    if (p != "do" && p != "") { return p; }
    else { return null; }
}

function getSquareFrom() {
    var p = $(txtSquareFromClientID).val();
    if (p != "od" && p != "") { return p; }
    else { return null; }
}

function getSquareTo() {
    var p = $(txtSquareToClientID).val();
    if (p != "do" && p != "") { return p; }
    else { return null; }
}

function GetCurrencyId() {
    var item = $(hfCurrencyIdClientID).val();
    if (parseInt(item) != "NaN" && item != "") { return item; }
    else { return null; }
}

function GetInvestmentId() {
    var item = $(hfInvestmentIdClientID).val();
    if (parseInt(item) != "NaN" && item != "") { return item; }
    else { return null; }
}

function GetAgencyId() {
    var item = $(hfAgencyIdClientID).val();
    if (parseInt(item) != "NaN" && item != "") { return item; }
    else { return null; }
}

function GetEstateId() { return $(ddlEstateTypeClientID).val(); }

function getDDLValue(ddlId) {
    if ($(ddlId).attr('disabled') == 'disabled' || $(ddlId).text().trim() == 'wczytywanie danych') {
        return -2;
    }
    var value = $(ddlId).val();
    if (value == "" || value == null) {
        return -2;
    }
    else {
        return value;
    }
}

function getDDLValueSingleArray(ddlId) {
    var arr = new Array();
    if ($(ddlId).attr('disabled') == 'disabled' || $(ddlId).text().trim() == 'wczytywanie danych') {

        return arr;
    }
    var value = $(ddlId).val();
    if (value == "" || value == null) {

        return arr;
    }
    else {
        if (value > 0) {
            arr.push(value);
        }
        return arr;
    }
}

function addSelectedToMyOffers(group) {
	var selectedIds = GetChecked();
	if (selectedIds != '' && selectedIds != 'on') {
        var count = parseInt($.cookie('countSlides'));
        var ids = selectedIds.split('|');
        for (var i = 0; ids[i] != undefined; i++)
            if (!isInArray(ids[i], 1) && ids[i] != 'on') {
                addToMyOffers(ids[i]);
                var elId = $('#AddOfferButton_' + ids[i]);
                $(elId).attr('Src', 'images/ikonka-dodaj-red.png');
                $(elId).attr('Title', 'Usuń z moich ofert');
            }
        if (panelOpened && mode == 1)
            getContent(1, '');
        count++;
        $.cookie('countSlides', count, { expires: 7 });
        getAllOfferCount();
    }
    else {
    	if (group) alert('Proszę zaznaczyć oferty dla grupowego zapytania.');
    	else alert('Proszę zaznaczyć oferty do dodania.');
    	return false;
    }
    dockSliding();
    return true;
}

function addSelectedToCompareOffers() {
    var selectedIds = GetChecked();
    if (selectedIds != '') {
        var count = parseInt($.cookie('countSlides'));
        var ids = selectedIds.split('|');
        for (var i = 0; ids[i] != undefined; i++)
            if (!isInArray(ids[i], 3)) {
                addToCompareOffers(ids[i]);
                var elId = $('#CompareOfferButton_' + ids[i]);
                $(elId).attr('Src', 'images/ikonka-porownaj-red.png');
                $(elId).attr('Title', 'Usuń z porównania');
            }
        if (panelOpened && mode == 3)
            getContent(3, '');
        count++;
        $.cookie('countSlides', count, { expires: 7 });
        getAllOfferCount();
    }
    else {
        alert('Proszę zaznaczyć oferty do dodania.');
    }
    dockSliding();
}

function removeSelectedToMyOffers() {
    var selectedIds = GetChecked();
    if (selectedIds != '') {
        var ids = selectedIds.split('|');
        for (var i = 0; ids[i] != undefined; i++) {
            if (isInMyOffers(ids[i]))
                removeFromMyOffers(ids[i]);
            $('#search-list-center div input[value=' + ids[i] + ']').parent().hide('fast').remove();
        }
        $('#docklist_myoffers_cnt').text(getMyOffersCount());
    }
    else {
        alert('Proszę zaznaczyć oferty do usunięcia z Moich Ofert.');
    }
}

function GetChecked() {
    var selectedIds = '';
    var items = $('div#search-list-center input:checked');
    items.each(function (i) {
        if (i > 0)
            selectedIds += '|';
        selectedIds += $(this).val();
    });
    return selectedIds;
}

function GetCheckBoxListValue(sender) {
    var obj = sender;
    var arr = new Array;
    if (obj != null) {

        for (i = 0; i < obj.length; i++) {
            if (obj.item(i).checked == true) {
                arr.push(obj.item(i).value);
            }
        }
    }
    return arr;
}

function ClearCheckBoxListValue(sender, nameBox, text) {
    var obj = sender;
    obj.innerHTML = '';
    nameBox = nameBox + '_ddlText';

    document.getElementById(nameBox).value = text;
}

function GetCurrentSelections() {
    return {
        estateId: GetEstateId(),
        //provinceId: GetProvinceId(),
        offerTypeId: getOfferType(),
        priceFrom: getPriceFrom(),
        priceTo: getPriceTo(),
        squareMeterFrom: getSquareFrom(),
        squareMeterTo: getSquareTo(),
        pricePerMeterFrom: getPricePerMeterFrom(),
        pricePerMeterTo: getPricePerMeterTo(),
        photo: $(cbxPhotoClientID + ':checked').val(),
        rns: $(cbxRNSClientID + ':checked').val(),
        agencyId: GetAgencyId(),
        queryString: GetQueryString(),
        currencyId: GetCurrencyId(),
        investmentId: GetInvestmentId(),
        location: $(txtLocationCodesClientID).val(),
        submitDate: GetSubmitDate()
    };
}

function GetSubmitDate() {
    if ($(hfSubmitDateClientId).val() != undefined) {
        return $(hfSubmitDateClientId).val();
    }
    return null;
}

function CountOffers() {
    counting = 1;
    btnSearchDisable();
    btnSearchText("Szukam...");
    var x = GetCurrentSelections();
    var filters = GetCheckBoxListValue(document.getElementsByName('chkFilters'));
    if (x.estateId != null) { filters.push("EstateId$" + x.estateId); }
    //if (x.provinceId != null) { filters.push("ProvinceId$" + x.provinceId); }
    if (x.offerTypeId != null) { filters.push("OfferTypeId$" + x.offerTypeId); }
    if (x.priceFrom != null) { filters.push("PrFrom$" + x.priceFrom); }
    if (x.priceTo != null) { filters.push("PrTo$" + x.priceTo); }
    if (x.pricePerMeterFrom != null) { filters.push("ppmFrom$" + x.pricePerMeterFrom); }
    if (x.pricePerMeterTo != null) { filters.push("ppmTo$" + x.pricePerMeterTo); }
    if (x.squareMeterFrom != null) { filters.push("SqMForm$" + x.squareMeterFrom); }
    if (x.squareMeterTo != null) { filters.push("SqMTo$" + x.squareMeterTo); }
    if (x.agencyId != null) { filters.push("_AgencyId$" + x.agencyId); }
    if (x.investmentId != null) { filters.push("_InvestmentId$" + x.investmentId); }
    if (x.photo != null) { filters.push("Photo$1"); }
    if (x.currencyId != null) { filters.push("Currency$" + x.currencyId); }
    if (x.rns != null) { filters.push("_RNS$1"); }
    if (x.location != null && x.location != "") { filters.push("Location$" + x.location); }
    if (x.submitDate != null && x.submitDate != "") {
        filters.push("_SubmitDate$" + x.submitDate);
    }
    lastCall++;
    WebServices.WS_Search.Search(x.estateId, lastCall, filters, OnSucceededCount);
}

function btnSearchFocus() {
    $(btnShowClientID).focus();
}

function btnSearchEnable() {
    $(btnShowClientID).removeAttr('disabled');
    $(btnShowFiltersClientID).removeAttr('disabled');
    $(btnShowFiltersFixedClientID).removeAttr('disabled');
}

function btnSearchDisable() {
    $(btnShowClientID).attr('disabled', 'disabled');
    $(btnShowFiltersClientID).attr('disabled', 'disabled');
    $(btnShowFiltersFixedClientID).attr('disabled', 'disabled');
}

function btnSearchText(text) {
    $(btnShowClientID).val(text);
    $(btnShowFiltersClientID).val(text);
    $(btnShowFiltersFixedClientID).val(text);
}

function OnSucceededCount(result) {
    counting = 0;
    if (result.LastCall == lastCall) {
        if (result.Count < 1) {
            btnSearchDisable();
            btnSearchText("Pokaż wyniki: " + result.Count);
            submiting = 0;
        }
        else {
            btnSearchEnable();
            btnSearchText("Pokaż wyniki: " + result.Count);
            if (submiting == 1) {
                $(btnShowClientID).click();
            }
        }
    }
}

function increaseClicksPerOffer(offerId) {
    WebServices.WS_Offers.increaseClicksPerOffer(offerId, onBsClickSuccess);
}

function onBsClickSuccess(result) {

}
