﻿var searchFormMode = 'list';

var txtText_OnFocus = function(textId) {
    var txtText = $("#" + textId);
    if (txtText.val() == "например, маз, man") {
        txtText.css("color", "black");
        txtText.css("font-style", "normal");
        txtText.val("");
    }
}

var getOfferType = function() {
    var offerType = parseInt($("input[@name='rbOfferType']:radio:checked").val());
    return offerType;
}
var rbOfferType_Select = function() {
    var offerType = getOfferType();
    if (searchFormMode == 'main') {
        FillFilterPrices(offerType);
        if (offerType == 2)
            $("#priceLabel").html('Цена в месяц, <span class="weight_n">руб.</span>');
        else
            $("#priceLabel").html('Цена, <span class="weight_n">руб.</span>');
    }
    else {
        if (offerType == 1) {
            $("#otherSearchFormParams").show();
            $("#ddlOfferPricePeriod").hide();
            FillSearchFilterPrices(offerType, null);
        }
        else {
            $("#otherSearchFormParams").hide();
            $("#ddlOfferPricePeriod").show();
            FillSearchFilterPrices(offerType, null);
        }
    }
    var r = $('#ddlRubrics');
    $.jmsajax({
        url: '/webservices/Search.asmx/GetParentRubricsForSearch',
        data: { offerType: offerType },
        success: function(d) {
            h = new Array();
            h.push(getDefaultItem());
            for (var i = 0; i < d.length; i++) {
                h.push('<option value="' + d[i].Alias + '">' + d[i].Name + '</option>');
            }
            r.html(h.join(''));
        }
    });
    $("#ddlRubrics option:first").attr("selected", "selected");
    OnRubricChange('ddlRubrics', 'ddlSubRubrics');
    $($("#conditionBlock li span")[0]).click();
}

var FillFilterPrices = function(offerType) {
    var h = new Array();
    var pr = $('#ddlPrices');
    if (offerType == 1) {
        pr.html('<option value="">любая</option>' +
                 '<option value="inf;500000">до 500 тыс. руб.</option>' +
                 '<option value="500000;1000000">500 тыс. - 1 млн.</option>' +
                 '<option value="1000000;2000000">1 млн. - 2 млн.</option>' +
                 '<option value="3000000;5000000">3 млн. - 5 млн.</option>' +
                 '<option value="5000000;inf">свыше 5 млн.</option>');
    }
    if (offerType == 2) {
        pr.html('<option value="">любая</option>' +
                 '<option value="inf;50000">до 50 тыс. руб.</option>' +
                 '<option value="100000;150000">100 тыс. - 150 тыс.</option>' +
                 '<option value="150000;200000">150 тыс. - 200 тыс.</option>' +
                 '<option value="200000;250000">200 тыс. - 250 тыс.</option>' +
                 '<option value="250000;inf">свыше 250 тыс.</option>');
    }
}
var FillSearchFilterPrices = function(offerType, offerPricePeriod) {
    var pr = $("#priceBlock");
    if (offerType == 1) {
        pr.html('<li><span value="" onclick="priceSelect(this);" class="red">'
                    + 'любая</span></li>'
                    + '<li><span value="inf;500000" onclick="priceSelect(this);">до 500 тыс.</span></li>'
                    + '<li><span value="500000;1000000" onclick="priceSelect(this);">500 тыс. - 1 млн.</span></li>'
                    + '<li><span value="1000000;2000000" onclick="priceSelect(this);">1 млн. - 2 млн.</span></li>'
                    + '<li><span value="3000000;5000000" onclick="priceSelect(this);">3 млн. - 5 млн.</span></li>'
                    + '<li><span value="5000000;inf" onclick="priceSelect(this);">свыше 5 млн.</span></li>');
    }
    else if (offerType == 2) {
        
        if (offerPricePeriod == 0) {
            pr.html('');
            $("#priceValuesBlock").hide();
        }
        if (offerPricePeriod == 1) {
            $("#priceValuesBlock").show();
            pr.html('<li><span value="" onclick="priceSelect(this);" class="red">'
                    + 'любая</span></li>'
                    + '<li><span value="inf;50000" onclick="priceSelect(this);">до 50 тыс.</span></li>'
                    + '<li><span value="100000;150000" onclick="priceSelect(this);">100 тыс. - 150 тыс.</span></li>'
                    + '<li><span value="150000;200000" onclick="priceSelect(this);">150 тыс. - 200 тыс.</span></li>'
                    + '<li><span value="200000;250000" onclick="priceSelect(this);">200 тыс. - 250 тыс.</span></li>'
                    + '<li><span value="250000;inf" onclick="priceSelect(this);">свыше 250 тыс.</span></li>');
        }
        else if (offerPricePeriod == 2) {
            $("#priceValuesBlock").show();
            pr.html('<li><span value="" onclick="priceSelect(this);" class="red">'
                    + 'любая</span></li>'
                    + '<li><span value="inf;1500" onclick="priceSelect(this);">до 1500</span></li>'
                    + '<li><span value="1500;3500" onclick="priceSelect(this);">1500 - 3500</span></li>'
                    + '<li><span value="3500;6000" onclick="priceSelect(this);">3500 - 6000</span></li>'
                    + '<li><span value="6000;15000" onclick="priceSelect(this);">6000 - 15000</span></li>'
                    + '<li><span value="15000;inf" onclick="priceSelect(this);">свыше 15000</span></li>');
        }
    } 
    $("#txtPriceFrom").val('');
    $("#txtPriceTo").val('');
}

var ddlPricePeriodChanged = function() {
    var offerPricePeriod = parseInt($("#ddlOfferPricePeriod").val());
    FillSearchFilterPrices(2, offerPricePeriod);
}
var txtText_OnBlur = function(textId) {
    var txtText = $("#" + textId);
    if (txtText.val() == '') {
        txtText.css("color", "#8f8f8f");
        txtText.css("font-style", "normal");
        txtText.val("например, маз, man");
    }
}
var Search = function(offerTypeId, rubricsId, subRubricsId, brandsId, modelsId, textId, pricesId, conditionId) {
    var text = $("#" + textId).val();
    var rubric = $("#" + rubricsId + " option:selected").val();
    var subrubric = $("#" + subRubricsId + " option:selected").val();
    var condition = $("#" + conditionId).val();
    var offerType = getOfferType();
    var region = $("#ddlRegions").val();
    var offerPricePeriod = parseInt($("ddlOfferPricePeriod").val());
    if (searchFormMode == 'main') {
        offerPricePeriod = "0";
    }
    else {
        offerPricePeriod = parseInt($("#ddlOfferPricePeriod").val());
    }
    var brand = '';
    var model = '';
    if (brandsId != null)
        brand = $("#" + brandsId + " option:selected").val();
    if (modelsId != null)
        model = $("#" + modelsId + " option:selected").val();
    var price = '';
    var priceFrom = '';
    var priceTo = '';
    if (searchFormMode == 'list') {
        $.query.REMOVE("pf");
        $.query.REMOVE("pt");
        priceFrom = $("#txtPriceFrom").val();
        if (priceFrom <= 0) priceFrom = '';
        priceTo = $("#txtPriceTo").val();
        if (priceTo <= 0) priceTo = '';
        if ($("#photoonly").attr("checked"))
            $.query.SET("photoonly", "true");
        else
            $.query.REMOVE("photoonly");
    }
    else {
        price = $("#" + pricesId + " option:selected").val();
        if (price != '') {
            var prices = price.split(";");
            if (prices[0] != 'inf')
                priceFrom = prices[0];
            else {
                priceFrom = '';
                $.query.REMOVE("pf");
            }
            if (prices[1] != 'inf')
                priceTo = prices[1];
            else {
                priceTo = '';
                $.query.REMOVE("pt");
            }
        }
    }
    var loc = "";
    if (offerType == 2)
        loc = "/rent/";
    else
        loc = "/offers/";

    if (searchFormMode == 'main')
        region = $("#globalRegion").val();
    if (region != null && region != '') {
        loc = "/" + region + loc;
    }
    else {
        $.cookie("Trucks_RegionAlias", null,
    {
        expires: 365,
        path: "/",
        secure: false
    });
    }


    if (rubric != '') {
        loc = loc + rubric + "/";
    }
    if (rubric != '' && subrubric != '') {
        loc = loc + subrubric + "/";
    }
    if (brand != null && brand != '' && subrubric != '')
        loc = loc + brand + "/";
    if (model != null && model != '' && brand != '')
        loc = loc + model + "/";
    if (text != null && text != '' && text != 'например, маз, man') {
        $.query.SET("text", encodeURIComponent(text));
    }
    else {
        $.query.REMOVE("text");
    }

    var vpAdded = false;

    if (condition != '' && condition != null) {
        var condAlias = '';
        switch (condition) {
            case '72':
                condAlias = 'new';
                break;
            case '73':
                condAlias = 'best';
                break;
            case '74':
                condAlias = 'good'
                break;
            case '75':
                condAlias = 'satisfactory';
                break;
            case '76':
                condAlias = 'beaten';
                break;
            case '77':
                condAlias = 'forparts';
                break;
        }
        if (condAlias != '') {
            if (vpAdded == true) {
                loc = loc + "-" + condAlias;
            } else {
                loc = loc + "vp-" + condAlias;
                vpAdded = true;
            }
        }
    }
    if (vpAdded == true) {
        loc = loc + "/";
    }

    if (offerType == 1) {
        clearRentParameters();
        if (priceFrom != '') {
            $.query.SET("pf", priceFrom);
        }
        if (priceTo != '') {
            $.query.SET("pt", priceTo);
        }
    }
    else if (offerType == 2) {
        clearOfferParamters();
        if (offerPricePeriod == 1) {//monthly
            if (priceFrom != '')
                $.query.SET("mpf", priceFrom);
            else {
                $.query.REMOVE("mpf");
            }
            if (priceTo != '')
                $.query.SET("mpt", priceTo);
            else
                $.query.REMOVE("mpt");

            $.query.REMOVE("dpf");
            $.query.REMOVE("dpt");
        }
        else if (offerPricePeriod == 2) {//daily
            if (priceFrom != '')
                $.query.SET("dpf", priceFrom);
            else
                $.query.REMOVE("dpf")
            if (priceTo != '')
                $.query.SET("dpt", priceTo);
            else
                $.query.REMOVE("dpt");
            $.query.REMOVE("mpf");
            $.query.REMOVE("mpt");
            if (priceFrom != '' || priceTo != '')
                $.query.SET("ppt", 2);
        } else {
            $.query.REMOVE("mpf");
            $.query.REMOVE("mpt");
            $.query.REMOVE("dpf");
            $.query.REMOVE("dpt");
            $.query.REMOVE("ppt");
        }
        if (offerPricePeriod == 1 || offerPricePeriod == 2)
            $.query.SET("ppt", offerPricePeriod);
    }

    $.query.REMOVE("p");
    document.location.href = loc + $.query.toString();
}
var clearRentParameters = function() {
    $.query.REMOVE("mpf");
    $.query.REMOVE("mpt");
    $.query.REMOVE("dpf");
    $.query.REMOVE("dpt");
    $.query.REMOVE("ppt");
}

var clearOfferParamters = function() {
    $.query.REMOVE("pt");
    $.query.REMOVE("pf");
}
var OnRubricChange = function(idRubrics, idSubrubrics) {
    var rs = $('#' + idRubrics + ' option:selected').val();
    var sr = $('#' + idSubrubrics);
    var offerType = getOfferType();
    if (rs != '') {
        $.jmsajax({
            url: '/webservices/Search.asmx/GetRubricsForSearchByRubricAlias',
            data: { offerType: offerType, rubricAlias: rs },
            cache: true,
            success: function(d) {
                h = new Array();
                h.push(getDefaultItem());
                for (var i = 0; i < d.length; i++) {
                    h.push('<option value="' + d[i].Alias + '">' + d[i].Name + '</option>');
                }
                sr.html(h.join(''));
            }
        });
    }
    else {
        sr.html(getDefaultItem());
    }
    if (getOfferType() == 1)
        UpdateBrands(idSubrubrics);
    if (searchFormMode == 'main') {
        UpdateBrands(idSubrubrics);
    }
    UpdateRegions("ddlSubRubrics", "ddlBrands", "ddlModels");
}

var InitSearchForm = function() {

    var rs = $("#ddlRubrics option:selected").val();
    var sr = $("#ddlSubRubrics option:selected").val();
    var brand = $("#ddlBrands option:selected").val();
    var model = $("#ddlModels option:selected").val();
    //    if (model == '' || model == null) {
    //        if (brand != '' && brand != null) {
    //            UpdateModels("rbOfferType", "ddlSubRubrics", "ddlBrands");
    //        }
    //        else if (brand == '' || brand == null) {
    //            UpdateBrands("rbOfferType", "ddlSubRubrics");
    //        }
    //    }
}
var UpdateBrands = function(idSubrubrics) {
    var sr = $("#" + idSubrubrics + " option:selected").val();
    if (sr == undefined)
        sr = '';
    var brands = $("#ddlBrands");
    var offerType = getOfferType();
    if (sr != '' && brands.length > 0) {
        $.jmsajax({
            url: '/webservices/Search.asmx/GetBrandForSearchByRubricAlias',
            data: { offerType: offerType, alias: sr },
            success: function(d) {
                h = new Array();
                h.push(getDefaultItem());
                for (var i = 0; i < d.length; i++) {
                    h.push('<option value="' + d[i].Alias + '">' + d[i].Name + '</option>');
                }
                brands.html(h.join(''));
            }
        });
    }
    else {
        brands.html('');
        brands.html(getDefaultItem());
    }
    UpdateModels(idSubrubrics, "ddlBrands");
}

var UpdateModels = function(idSubrubrics, brandId) {
    var sr = $("#" + idSubrubrics + " option:selected").val();
    if (sr == undefined)
        sr = '';
    var brand = $("#" + brandId + " option:selected").val();
    if (brand == undefined)
        brand = '';
    var models = $("#ddlModels");
    var offerType = getOfferType();
    if (models.length > 0) {
        if (sr != '' && brand != '') {
            $.jmsajax({
                url: '/webservices/Search.asmx/GetModelsForSearchByRubricAndBrandAlias',
                data: { offerType: offerType, rubricAlias: sr, brandAlias: brand },
                success: function(d) {
                    h = new Array();
                    h.push(getDefaultItem());
                    for (var i = 0; i < d.length; i++) {
                        h.push('<option value="' + d[i].Alias + '">' + d[i].Name + '</option>');
                    }
                    models.html(h.join(''));
                }
            });
        }
        else {
            models.html(getDefaultItem());
        }
        UpdateRegions(idSubrubrics, brandId, "ddlModels");
    }
}

var UpdateRegions = function(idSubrubrics, brandId, modelId) {
    return;
    var rs = $("#ddlRubrics option:selected").val();
    if (rs == undefined)
        rs = '';
    var sr = $("#" + idSubrubrics + " option:selected").val();
    if (sr == undefined)
        sr = '';
    var brand = $("#" + brandId + " option:selected").val();
    if (brand == undefined)
        brand = '';
    var model = $("#" + modelId + " option:selected").val();
    if (model == null)
        model = '';
    var regions = $("#ddlRegions");
    var offerType = getOfferType();
    if (regions.length > 0) {
        $.jmsajax({
            url: '/webservices/Search.asmx/GetActiveRegions',
            data: { offerType: offerType, rubricAlias: rs, subRubricAlias: sr, brandAlias: brand, modelAlias: model },
            success: function(d) {
                h = new Array();
                h.push('<option value="">Россия</option>');
                for (var i = 0; i < d.length; i++) {
                    h.push('<option value="' + d[i].Alias + '">' + d[i].Name + '</option>');
                }
                regions.html(h.join(''));
                var globalRegion = $("#globalRegion").val();
                if (globalRegion != 'undefined' && globalRegion != '') {
                    $("#ddlRegions [value='" + globalRegion + "']").attr("selected", "selected");
                }
            }
        });
    }
}
var toggleprice = function() {
    $("#priceSpan").toggleClass('current_extra_header');

    $("#pricePredefinedBlock").toggle();
}
var togglecondition = function() {
    $("#conditionSpan").toggleClass('current_extra_header');
    $("#conditionBlock").toggle();
}
var conditionSelect = function(itm) {
    $("#conditionBlock li span").removeAttr("selected");
    $("#conditionBlock li span").removeClass("red");
    $(itm).attr("selected", "true");
    $(itm).addClass("red");
    $("#txtCondition").val($("#conditionBlock li span[selected='true']").attr("value"));
}
var priceSelect = function(itm) {
    $("#pricePredefinedBlock ul li span").removeAttr("selected");
    $("#pricePredefinedBlock ul li span").removeClass("red");
    $(itm).attr("selected", "true");
    $(itm).addClass("red");

    price = $("#pricePredefinedBlock ul li span[selected='true']").attr("value");
    var priceFrom = '';
    var priceTo = '';
    if (price != '') {
        var prices = price.split(";");
        if (prices[0] != 'inf')
            $("#txtPriceFrom").val(prices[0]);
        else
            $("#txtPriceFrom").val('');
        if (prices[1] != 'inf')
            $("#txtPriceTo").val(prices[1]);
        else
            $("#txtPriceTo").val('');
    }
    else {
        $("#txtPriceFrom").val('');
        $("#txtPriceTo").val('');
    }
}
function getDefaultItem() {
    return '<option value="">любая</option>';
}
function checkSearchEnter(e, id) {
    if (!e) e = window.event;
    if (e.keyCode == 13 && id) {
        Search('ddlRubrics', 'ddlSubRubrics', 'ddlBrands', 'ddlModels', 'txtText', 'ddlPrices', 'txtCondition');
        return false;
    }
    else {
        return true;
    }
}
var SearchCargo = function() {
    var cf = $("#hdncountryfrom").val();
    var rf = $("#hdnfrom").val();
    var prf = $("#hdnpfrom").val();
    var ct = $("#hdncountryto").val();
    var rt = $("#hdnto").val();
    var prt = $("#hdnpto").val();
    var rft = $("#txtfrom").val();
    var rtt = $("#txtto").val();
    var transType = $('#cargotransporttype option:selected').val();
    var ot = $('#ddlOfferType option:selected').val();
    var loc = ot;
    if (rft != '') {
        if (rf != undefined && rf != '')
            $.query.SET("rf", rf);
        else $.query.REMOVE("rf");
        if (prf != undefined && prf != '')
            $.query.SET("prf", prf);
        else $.query.REMOVE("prf");
        if (cf != undefined && cf != '')
            $.query.SET("cf", cf);
        else {
            $.query.REMOVE("cf");
            $.query.REMOVE("rf");
        }
    }
    else {
        $.query.REMOVE("rf");
        $.query.REMOVE("prf");
        $.query.REMOVE("cf");
    }
    if (rtt != '') {
        if (rt != undefined && rt != '')
            $.query.SET("rt", rt);
        else $.query.REMOVE("rt");
        if (prt != undefined && prt != '')
            $.query.SET("prt", prt);
        else $.query.REMOVE("prt");
        if (ct != undefined && ct != '')
            $.query.SET("ct", ct);
        else {
            $.query.REMOVE("ct");
            $.query.REMOVE("rt");
        }
    }
    else {
        $.query.REMOVE("rt", rt);
        $.query.REMOVE("prt", prt);
        $.query.REMOVE("ct");
    }

    if (transType != undefined && transType != '')
        $.query.SET("tt", transType);
    else $.query.REMOVE("tt");

    var parameters = getParameters();

    var pars = getParametersString(parameters);
    if (pars != '')
        $.query.SET("pars", pars);
    else
        $.query.REMOVE("pars");
    document.location.href = loc + $.query.toString();
}
function getParameters() {
    var parameters = [];
    var parcontrols = $("[id^='par_']")
    parcontrols.each(function(a, b) {
        var val = $('option:selected', b).val();
        var par = $(b).attr("id").replace('par_', '');
        if (par != '' && val != '')
            parameters.push(
        {
            id: par,
            val: val
        });
    });
    return parameters;
}
var getParametersString = function(parameters) {
    var strings = [];
    for (var i = 0; i < parameters.length; i++) {
        strings.push(parameters[i].id + '|' + parameters[i].val);
    }
    return strings.join(",");
}

function setSearchSort(sort) {
    $.query.REMOVE("p");
    $.query.SET("sort", sort);
    
    var sortType = $('#ddlOfferType option:selected').val();

    document.location.href = sortType + $.query.toString();
}
var ChangeOfferType = function(type) {
    var val = $('#ddlOfferType option:selected').val();
    document.location.href = val;
}
