var count_foto = 0;
$(document).ready(function(admin_mode) {
        
    /* выбор марки авто  */
    $("#model").change(function() {
        $("#model").removeClass('error');   
    })          
    $("#mark").change(function() {
        $("#mark").removeClass('error');
        $("#model").attr('disabled','disabled');
        
        if($('#mark option:selected').val()==0)
        {
            $("#model").attr('disabled','disabled');
        }
        else
        {
            $('#mark option[value=0]').remove();
            $("#model").attr('disabled',false);
            $("#model").addClass('secelc_loading');

            $.ajax({
                url: '/ajax.php?&p=2&mark='+$('#mark option:selected').val(),
                dataType : "html",  
                cache    : false,                   
                success: function (data, textStatus) {
                    $('#model option[@value<>0]').remove();
                    $("#model").removeClass('secelc_loading');
                    $("#model").append(data);
                    
                    $('#model_input').remove();   
                    $('#model_container').remove();   
                    //$('#model').selectbox({debug: true});   
                }
                });   
        }
    })
    
    var s_status = 0;
    /* global search */
    $("#global_search").click(function global_search(page)
    {
        if(s_status==0)
        {
            s_status = 1;
            if($('div.search_div2:eq(0)').css('display')!='none')
            {
                $('div.search_div2:eq(0)').slideToggle('slow');
            }   
            
            var p = "&p="+page;
            
            
            
            $('div.search_div:eq(0)').slideToggle('slow');   
            $.ajax({
                    url: '/ajax.php?&search='+encodeURIComponent($("input[name=s-text]").val()) + '&type=' + $("#select-s-type").val() + p,
                    dataType : "html",
                    async : true,
                    cache    : false,                   
                    success: function (data, textStatus) {
                        
                        $('div.search_div2:eq(0) div').html(data);
                        
                        $('div.search_div2:eq(0) div.paginator a').click(function() {
                            global_search($(this).attr('title'));
                            return false;
                        })
                        
                        window.setTimeout("$('div.search_div:eq(0)').slideToggle('slow');",1000);
                        window.setTimeout("$('div.search_div2:eq(0)').slideToggle('slow');",1700);
                        window.setTimeout(nulles_status,2000);
                    }
                    });
        }
    });
    
       
    
    /* avto search */
    var s_status2 = 0;
    $("#global_avto_search").click(function global_search_avto_form(page)
    {
        var p = "&p="+page;
        
        if(s_status2==0)
        {
            s_status2 = 1;
            if($('div.search_div2:eq(1)').css('display')!='none')
            {
                $('div.search_div2:eq(1)').slideToggle('slow');
            }   
            
            var form  = $("#global_avto_search_form").serialize();
            
            $('div.search_div:eq(1)').slideToggle('slow');   
            $.ajax({
                    url: '/ajax.php?&main_search=avto&'+form + p,
                    dataType : "html",                     
                    cache    : false,                   
                    success: function (data, textStatus) {
                        
                        $('div.search_div2:eq(1) div').html(data);
                        
                        
                        $('div.search_div2:eq(1) div.paginator a').click(function() {
                            global_search_avto_form($(this).attr('title'));
                            return false;
                        })
                        
                        
                        window.setTimeout("$('div.search_div:eq(1)').slideToggle('slow');",1000);
                        window.setTimeout("$('div.search_div2:eq(1)').slideToggle('slow');",1700);
                        window.setTimeout(nulles_status2,2000);
                    }
                    });
        }
    });
    
    
    
    
    function change_by_paginator(el)
    {
        
        if(s_status2==0)
        {
            s_status2 = 1;
            
            $("div.paginator").empty();
            $("div.paginator").addClass('pagin_search');
            var form  = $("#global_avto_search_form").serialize()
            
            $.ajax({
                    url: '/ajax.php?&main_search=avto&'+form + '&p=' + $(el).attr('title'),
                    dataType : "html",                     
                    cache    : false,                   
                    success: function (data, textStatus) {
                        
                        
                        $('div.search_div2:eq(1) div').height('auto');
                        $('div.search_div2:eq(1) div').html(data);
                        
                        $('div.search_div2:eq(1) div').height('auto');
                        
                        $("div.paginator a").each(function(el) {
                            $(this).click( function() {
                                change_by_paginator(this) ;
                                return false;
                            });
                            
                        });
                        
                        
                        
                        window.setTimeout(nulles_status2,2000);
                    }
                    });
        }
        return false;
    }
    
    function nulles_status2()
    {
        s_status2=0;
    }
    function nulles_status()
    {
        s_status=0;
    }
    
    
    
    /* выбор страны */
    $("#country").change(function() {
        if(s_status==0 && s_status2==0)
        {
            $("#region").attr('disabled','disabled');
            $("#city").attr('disabled','disabled');
            
            $('#region_input').remove();   
            $('#region_container').remove();   
            $('#region').show(); 
            
            $('#city_input').remove();   
            $('#city_container').remove();   
            $('#city').show();
            
            if($('#country option:selected').val()==0)
            {
                
                
                $("#region").attr('disabled','disabled');
                $("#city").attr('disabled','disabled');
            }
            else
            {
                $("#region").attr('disabled',false);
                $("#region").addClass('secelc_loading');
                $('#region option[@value<>0]').remove();
                     
                if($("#country").hasClass("add_razbor"))
                    $('#country option[@value=0]').remove();    
                    
                
                
                $.ajax({
                    url: '/ajax.php?&p=2&country='+$('select[@name=country] option:selected').val(),
                    dataType : "html",                     
                    cache    : false,                   
                    success: function (data, textStatus) {
                        $('#region option[@value<>0]').remove();
                        $("#region").removeClass('secelc_loading');
                        $("#region").append(data);
                        
                        if($("#country").hasClass("add_razbor"))
                            $('#region option[@value=0]').remove();
                        
                        $('#region_input').remove();   
                        $('#region_container').remove();   
                        //$('#region').selectbox({debug: true});   
                    }
                    });   
            }
        }
    })
    
    /* выбор региона */
    $("#region").change(function() {
        if(s_status==0 && s_status2==0)
        {
            var act_reg = $('#region option:selected').val();
            
            if(act_reg==0)
            {
                $("#city").attr('disabled','disabled');       
            }   
            else
            {
                $("#city").attr('disabled',false);
                $("#city").addClass('secelc_loading');
                $('#city option[@value<>0]').remove();
                
                $.ajax({
                        url: '/ajax.php?&p=2&region='+act_reg,
                        dataType : "html",                     
                        success: function (data, textStatus) {
                            $('#city option[@value<>0]').remove();
                            $("#city").removeClass('secelc_loading');
                            $("#city").append(data);
                            
                            if($("#country").hasClass("add_razbor"))
                                $('#city option[@value=0]').remove();
                            
                            $('#city_input').remove();   
                            $('#city_container').remove();   
                            //$('#city').selectbox({debug: true});
                        }
                        });
            }
        }
    })
    
    // search
    $("input[name=s-text]").focus(function() {
        this.value='';
    });
    $("input[name=s-text]").blur(function() {
        if(this.value=='' || this.value==' ') {
            this.value='Введите ключевое слово';
        }
    });
    
    //$("input[name=s-text]").keypress(function(event) {
//        if(event.keyCode==13)
//        {
//            
//        }
//    });

    // login
    $("#login_form input[name=mail_m]").focus(function() {
        if(this.value=='mail')
            this.value='';
    });
    $("#login_form input[name=mail_m]").blur(function() {
        if(this.value=='' || this.value==' ') {
            this.value='mail';
        }
    });
    $("#login_form input[name=pass_m]").focus(function() {
        if(this.value=='pass')
            this.value='';
    });
    $("#login_form input[name=pass]").blur(function() {
        if(this.value=='' || this.value==' ') {
            this.value='pass';
        }
    });
    
    $("a.submit").click(function() {
        $("#login_form").submit();
    })
    
    /*  hidden fle input */
    if(admin_mode!=1)
    $("input[type=file]").change(function() {
        var name = $("input[type=file]").attr('name');
        
        $("#"+name+'_span').html($("input[type=file]").val());
    })
    
    /* registration */ 
    $("#submit_registr").click(
    function prov_login()
    {
        if($("#pass").val()!=$("#pass2").val())
        {
            $("#pass").addClass("error");       
            $("#pass2").addClass("error");       
        }
        
        if($("#pass").val().length<3)
        {                              
            $("#pass").addClass("error");       
            $("#pass2").addClass("error");       
        }
        
        $.ajax({
                url: '/ajax.php?login='+$('#login').val(),
                dataType : "html",                     
                success: function (data, textStatus) {
                    if(data!="0")
                    {
                        if($('#login').val()!='')
                            $("#error1").html("Уже занят");
                        else
                            $("#error1").html("Уже занят");
                            
                        $("#error1").show();
                        $('#login').addClass("error");
                    }
                    if(data=='invalid')
                    {
                        $("#error1").html("Запрещённые символы");
                        $("#error1").show();
                        $('#login').addClass("error");
                    }
                    if(data=='len' || data=='')
                    {
                        $("#error1").html("Несоответствует длинна");
                        $("#error1").show();
                        $('#login').addClass("error");
                    }
                }
                });   
                
        $.ajax({
                url: '/ajax.php?&mail=' + $('#mail').val(),
                dataType : "html",                     
                success: function (data, textStatus) {
                    if(data!="0")
                    {
                        if($('#mail').val()==' ' || $('#mail').val()=='')
                            $("#error2").html("Укажите ваш почтовый ящик");
                        else
                            $("#error2").html("Уже занят");
                        
                        $("#error2").show();
                        $('#mail').addClass("error");
                    }
                    if(data=='invalid')
                    {
                        $("#error2").html("Неверно написан");
                        $("#error2").show();
                        $('#mail').addClass("error");
                    }
                }
                }); 
        if($("input.error").size()==0)
        {
            $("#reg_form").submit();
        }   
    });
    
    $("input").focus(function() {
        $(this).removeClass("error");
    })
    
    // --- Автозаполнение2 ---
    //$("#city").autocomplete("/ajax.php", {
//        delay:10,
//        minChars:2,
//        matchSubset:1,
//        autoFill:true,
//        matchContains:1,
//        cacheLength:10,
//        selectFirst:true,
//        formatItem:liFormat,
//        maxItemsToShow:10,
//        onItemSelect:selectItem
//    });
//    
//    function liFormat (row, i, num) {
//        
//        var result = row[0] + '<p class=qnt>' + row[1]  + '</p>';
//        return result;
//    }
//    function selectItem(li) {
//        if( li == null ) var sValue = 'А ничего не выбрано!';
//        if( !!li.extra ) var sValue = li.extra[2];
//        else var sValue = li.selectValue;
//    }
    
    
    /* добавляем автомобиль */
    $("#add_avto_form input[type=button]").click(function() {
        var error = 0;
        if($("#mark").val()==0)
        {
            $($("#mark").addClass('error'));
            error = 1;
        }
        if($("#model").val()==0)
        {
            $($("#model").addClass('error'));
            error = 1;
        }
            
        if(error == 0)
            $("#add_avto_form").submit();
    })
    
    /* добавляем комментарий  */
    $("#add_comment_form input[type=button]").click(function() {
        var error = 0;
        if($("#mail").val()==0)
        {
            $($("#mail").addClass('error'));
            error = 1;
        }
        if($("#comment").val()==0)
        {
            $($("#comment").addClass('error'));
            error = 1;
        }
            
        if(error == 0)
            $("#add_comment_form").submit();
    })
    
    
    
    /* селекторы */
    //$('#mark').selectbox({debug: true});
//    $('#country').selectbox({debug: true});
//    $('.year').selectbox({debug: true});
//    $('#select-s-type').selectbox({debug: true});
    
    /* add-site */
    $("#add-site").click(function() {
        var country = $('select[@name=country] option:selected').val();
        var region = $('#region option:selected').val();
        var city = $('select[@name=city] option:selected').val();
        
        var str  ='';
        
        if($("#region").attr('disabled')==false)
        {
            str = $('select[@name=country] option:selected').html() + ', ' + $('#region option:selected').html(); 
        }
        if($("#city").attr('disabled')==false)
        {
            str +=', ' + $('select[@name=city] option:selected').html(); 
        }
        
        if($("#region").attr('disabled')==false) 
        {
            $(".add-city").append("<p>"+ str + '</p>');
            $("#add-city").val($("#add-city").val() + '|' + country + '-' + region + '-' + city );
        }
        
        
        $("#region").attr('disabled','disabled');
        $("#city").attr('disabled','disabled');
        $("#country option[@value=0]").attr('selected','selected');
    })
    
    
    count_foto = $("div.foto_item").size();
        
    function chanfe_file_new_avto(el) {
        count_foto++;
        if($(".new_avto input.type_file[@value='']").size()<=1)
        if(count_foto<6)
        $(".more_foto").append('<label for="foto">'+
                                    '<input class="type_file" title="avt_span'+count_foto+'" type="file" name="avt'+count_foto+'" id="avt'+count_foto+'" />'+
                                    '<span class="hide_file" id="avt_span'+count_foto+'"></span><br />'+
                                '</label>');
        
        if(admin_mode!=1)
            $("#" + $(el).attr('title')).html($(el).val());
        
        
        $(".new_avto input[@type=file]").change(function() {
            chanfe_file_new_avto(this);   
        })
        
        if(admin_mode==1)
        $(".ed_avto input[@type=file]").change(function() {
            chanfe_file_new_avto(this);   
        })
    }
    
    $(".new_avto input[@type=file]").change(function() {
        chanfe_file_new_avto();   
    })
    
    if(admin_mode==1) 
    $(".ed_avto input[@type=file]").change(function() {
        chanfe_file_new_avto();   
    })
    
    if(admin_mode!=1)
    $("a.galery").fancybox();
})
