$(document).ready(function(){
    $('.places-list > .tree-branch').hover(function(){
        $(this).addClass('place-name-hover');
        $(this).find('ul.level-1').show();
    }, function(){
        $(this).removeClass('place-name-hover');
        $(this).find('ul.level-1').hide();
    })
    
    $('.places-list li.level-1').hover(function(){
        $(this).find('ul.level-2').show();
        $(this).addClass('level-1-hover').css({
            'backgroundPosition': 'left -'+($(this).position().top-6)+'px'
        });
    }, function(){
        $(this).removeClass('level-1-hover');
        $(this).find('ul.level-2').hide();
    })
    
    $('.places-list li.level-2').hover(function(){
        $(this).addClass('level-2-hover').css({
            'backgroundPosition': 'left -'+($(this).position().top-6)+'px'
        });
    }, function(){
        $(this).removeClass('level-2-hover');        
    })
    
    $('.places-menu .switch').click(function(){
        
        $(this).toggleClass('minus').toggleClass('plus');
        $(this).parent().toggleClass('closed');
    })
    
    $('a.other_cities_title').click(function(){
        $('.other-cities').toggleClass('o-show').toggleClass('o-hide');
    })
    
        
    $('a.other_countries_title').click(function(){
        $('.other-countries').toggleClass('o-show').toggleClass('o-hide');
    })
    
    
    
    swaps = [];
    $(".ob_swap_url").each(function(i){
        swaps[i] = $(this).val();
        if ($.trim($(this).val()) == "" ) {
                $(this).val($(this).attr("def"));
                $(this).toggleClass("swap_grayed");
        }
        // Получение фокуса полем
        $(this).focusin(function(){
            if ($(this).val() == $(this).attr("def") || $(this).val() =='') {
                $(this).toggleClass("swap_grayed");
                $(this).val("");
            }
        // Потеря фокуса полем
        }).focusout(function(){
            if ($.trim($(this).val()) == "" || $(this).val() == $(this).attr("def")) {
                $(this).val($(this).attr("def"));
                $(this).toggleClass("swap_grayed");
            }
        });
    }); 
    
    
    checkObjDropdown();
    
})

function  checkObjDropdown(){
    var obj=$("select#select_object");
    var opt =obj.find(" > option"); 
    
    if (opt.length > 1){
        $("tr#div_object").show();
        $('#tr_object').show();
    }else{
        $("tr#div_object").hide();
        $('#tr_object').hide();
    }
}

function  checkPlaceDropdown(){
    var obj=$("select#select_place");
    var opt =obj.find(" > option"); 
   
    if (opt.length > 1){
        $("#tr_plcobject").show();
    }else{
        $("#tr_plcobject").hide();
    }
}


var map;
var form_state = false;

function sendRegistrationForm()
{
    if (form_state) return;
    form_state = true;
	
    JsHttpRequest.query('/clients/register/validate/',
    {
        'form' : $('#register_form')[0]
        },
    function(result, errors){
        form_state = false;
        if (result && result.res == 0){				
            $.dqValidate('#register_form', result);
        } else if (result && result.res == 1){
            window.location.assign('/register/confirm/');
        } else {
            console.log(errors);
        }
    }, true
    );
}

function sendConfirmForm()
{
    if (form_state) return;
    form_state = true;

    JsHttpRequest.query('/clients/confirm/validate/',
    {
        'form' : $('#register_form')[0]
        },
    function(result, errors){
        form_state = false;
        if (result && result.res == 0){
            $.dqValidate('#register_form', result);
        } else if(result && result.res == 1){
            $('#confirm-block').html(result.text);
            window.setTimeout("linkTo();", 3000);
        } else {
            console.log(result, errors);
        }
    }, true
    );
}

function linkTo()
{
    var link_user = $('#link_user').val();
    window.location.assign(link_user);
}

function sendLoginForm()
{
    if (form_state) return;
    form_state = true;
	
    JsHttpRequest.query('/clients/validateLogin/',
    {
        'form' : $('#login_form')[0]
        },
    function(result, errors){
        form_state = false;
        if (result && result.res == 0){				
            $.dqValidate('#login_form', result);
        } else if (result && result.res == 1){
            window.location.assign(result.path);
        } else {
            console.log(errors);
        }
    }, true
    );
}

function sendRemindForm()
{
    if (form_state) return;
    form_state = true;

    JsHttpRequest.query('/clients/remind/validate/',
    {
        'form' : $('#remind_form')[0]
        },
    function(result, errors){
        form_state = false;
        if (result && result.res == 0){
            $.dqValidate('#remind_form', result);
        } else if(result && result.res == 1){
            window.location.assign('/clients/remind/sent/');
        } else {
            console.log(errors);
        }
    }, true
    );
}

function sendNewPasswForm()
{
    if (form_state) return;
    form_state = true;

    JsHttpRequest.query('/clients/remind/validatePassword/',
    {
        'form' : $('#newpassw_form')[0]
        },
    function(result, errors){
        form_state = false;
        if (result && result.res == 0){
            $.dqValidate('#newpassw_form', result);
        } else if(result && result.res == 1){
            $('#remind_new_block').hide();
            $('#remind_new_success_block').show();
        } else {
            console.log(errors);
        }
    }, true
    );
}

/**
 * Фильтр по типу объявлений
 * компании/частные
 */
function filterCompanyType(type, obj)
{
    $('.country-head .country-status a').removeClass('active');
    $(obj).addClass('active');
    $('#company_type').val(type);
	
    filterCountry(type);
}

/**
 * Фильтр по городам
 */
function filterCity(id)
{
    var city_id = $('#city_id').val();
    if (id == 'all') {
        filterCountry(false, id);
    } else {
        filterCountry(false, city_id+','+id);
    }
}

function filterTypeSell(id)
{
    $('#type-sell li').removeClass('active');
    $('#type-sell #type-sell-'+id).addClass('active');
    $('#type-sell-value').val(id);
    filterCountry(false, false, id);
}

function getNewBuild()
{
    var newbuild = $('#new-build #check-1').attr("checked") === true ? 1 : 0;
    var oldbuild = $('#new-build #check-2').attr("checked") === true ? 1 : 0;

    var type = 0;
    if (newbuild == 1 && oldbuild == 1) {
        type = 3;
    } else if (newbuild == 0 && oldbuild == 0) {
        type = 3;		
    } else if (newbuild == 1) {
        type = 2;
    } else if (oldbuild == 1) {
        type = 1;
    }	
	
    return type;
}

function filterNewBuild()
{
    var type = getNewBuild();
    filterCountry(false, false, false, type);
}

function filterTypeId(id)
{
    var type_id = $('#type_id').val();
    if (id != 'all') {
        id = type_id+','+id
    }	
    filterCountry(false, false, false, false, id);
}

function filterPrice(id)
{
    var price_id = $('#price_id').val();
    if (id != 'all') {
        id = price_id+','+id
    }	
    filterCountry(false, false, false, false, false, id);
}

function filterPage(page)
{
    filterCountry(false, false, false, false, false, false, page);
}

function filterShow(item, page)
{
    if (form_state) return;
    form_state = true;
    //$('.loader_icon').show();
    //$('#page-block').html('');
    $.scrollTo('#objects-list');
	
    JsHttpRequest.query('/objects/showPage/',
    {
        'item' : item, 
        'page' : page
    },
    function(result, errors){
        form_state = false;
        if(result && result.res == 1){				
            $('#page-block').html(result.list);
            //$('.loader_icon').hide();				
        } else {
            console.log(errors);
            return false;
        }
    }, true
    );	
}

function filterCountry(company_type, city_id, type_sell, new_build, type_id, place_id, price_id, page )
{
    if (form_state) return;
    form_state = true;
	
    $('.loader_icon').show();
    //$('#objects-list').html('');	
	
    var country_id = $('#country_id').val();
	
    if (!company_type || company_type < 1 )
    {
        company_type = $('#company_type').val();
    }
    company_type--;
	
    if (!city_id || city_id < 1) {
        city_id = $('#city_id').val();
    }
    
    if (!place_id || place_id < 1) {
        place_id = $('#place_id').val();
    }
	
    if (!type_sell || type_sell < 1) {
        type_sell = $('#type-sell-value').val();
    }

    if (!new_build || new_build < 1) {
        new_build = getNewBuild();
    }

    if (!type_id || type_id < 1) {
        type_id = $('#type_id').val();
    }

    if (!price_id || price_id < 1) {
        price_id = $('#price_id').val();
    }else{
        var id = $('#price_id').val();
        if (price_id != 'all') {
            price_id = id+','+price_id;
        }	
    }
    if (!page || page < 1) {
        page = 1;		
    } else {
        $.scrollTo('#objects-list');
    }

    JsHttpRequest.query('/objects/items/filter/',
    {
        'country_id' : country_id,
        'company_type' : company_type,
        'city_id' : city_id,
        'place_id': place_id,
        'type_sell' : type_sell,
        'new_build' : new_build,
        'type_id' : type_id,
        'price_id' : price_id,
        'page' : page
    },
    function(result, errors){
        form_state = false;
        if(result && result.res == 1){
            $('#country-filters').html(result.filter);
            //$('#objects-list').html(result.items);
            /*
//-----------------------------------------
// Отображение KML		
// Инициализируем карту
		var myLatlng = new google.maps.LatLng(map_latitude, map_longitude);
		var myOptions = {
			zoom: zoom,
			center: myLatlng,
            scrollwheel: false,
			mapTypeId: google.maps.MapTypeId.ROADMAP
		}
		        
		var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
		var yourKML = new google.maps.KmlLayer(map_url+result.filter_link);        
		yourKML.setMap(map);
        
//----------------------------------
                */
            map.showMarkers(result.map);
            $('.loader_icon').hide();
        } else {
            console.log(errors);
            return false;
        }
    }, true
    );	
}

function mapTypeId(id)
{
    var type_id = $('#type_id').val();
    if (id != 'all') {
        id = type_id+','+id
    }	
    filterMap(id);
}

function mapNewBuild()
{
    var type = getNewBuild();
    filterMap(false, type);
}

function setUserObjFilter()
{	
    filterMap(false, false);
}

function filterMap(type_id, new_build)
{
    if (form_state) return;
    form_state = true;
    $('.loader_icon').show();
	
    var tr_id = $('#tr_id').val();
    if (!type_id || type_id < 1) {
        type_id = $('#type_id').val();
    }

    if (!new_build || new_build < 1) {
        new_build = getNewBuild();
    }
	
    var userbuild = $('#user-obj').attr("checked") === true ? 1 : 0;

    var country_id = $('#country_id').val();
	
    JsHttpRequest.query('/objects/map/filter/',
    {
        'country_id' : country_id,
        'tr_id' : tr_id,
        'type_id' : type_id,
        'new_build' : new_build,
        'userbuild' : userbuild
    },
    function(result, errors){
        form_state = false;
        if(result && result.res == 1){
            $('#map-filters').html(result.filter);

            /*
//-----------------------------------------
// Отображение KML		
// Инициализируем карту
		var myLatlng = new google.maps.LatLng(map_latitude, map_longitude);
		var myOptions = {
			zoom: zoom,
			center: myLatlng,
            scrollwheel: false,
			mapTypeId: google.maps.MapTypeId.ROADMAP
		}
		        
		var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
		var yourKML = new google.maps.KmlLayer(map_url+result.filter_link);        
		yourKML.setMap(map);        
//----------------------------------
*/              
            map.showMarkers(result.map);
            $('.loader_icon').hide();
        } else {
            console.log(errors);
            return false;
        }
    }, true
    );	
}

function setCurrency(obj)
{	
    if (form_state) return;
    form_state = true;

    var cur = $(obj).val();
	
    JsHttpRequest.query('/exchange/setCur/',
    {
        'cur' : cur
    },
    function(result, errors){
        form_state = false;
        if(result && result.res == 1){
            window.location.reload();				
        } else {
            console.log(errors);
        }
    }, true
    );
		
}

//обратная связь
function sendFeedback()
{
    if (form_state) return false;
    form_state = true;

    JsHttpRequest.query('/feedback/validate/',
    {
        'form' : $('#feedback_form')[0]
        },
    function(result, errors){
        form_state = false;
        if (result && result.res == 0){
            $.dqValidate('#feedback_form', result);
        } else if (result && result.res == 1){
            $('#feedback_form').html(result.text);
        } else {
            console.log(errors);
        }
    }, true
    );
}

function setNewsCountry(obj)
{
    var path = $(obj).val();
    window.location.assign(path);
}

function fsGetPrice(obj){
    var typeSell = $(':selected',obj).val();
    JsHttpRequest.query('/objects/getPriceSearch/',
    {
        'type' : typeSell
        },
    function(result, errors){
            if (result && result.res == 1){
                $('[name=price_from]').html(result.first_price);
                $('[name=price_to]').html(result.two_price);
            } else {
                console.log(errors);
            }
        }, true
    );
    
}
