function validate()
{
    var validator = $('#register').validate({
        rules: {
            login: {
                required:   true,
                minlength:  4,
                email:      true,
                remote:     '/ajax.php?act=check_login&value=login'
            },
            passwd: {
                required:   true,
                minlength:  4
            },
            repasswd: {
                required:   true,
                minlength:  4,
                equalTo:    "#passwd"
            }
        },
        messages: {
            login: {
                remote: "Этот логин уже занят!"
            }
        },
        submitHandler: function(form) 
        {
            /**
             * Дополнительная валидация
             * 
             */
            if(parseInt($('#selregion').val()) < 1)
            {
                validator.showErrors({'data[region]': 'Выберете город'});
                return false;
            }
            
            var sdialog = $('#submit-dialog');
            sdialog.dialog({modal: true});

            $.post(location.href.replace('#', '')+'?ajax=true', $(form).serialize(), function(data, textStatus) {
                if(data == undefined) return false;
                
                if(data == 'true')
                {
                    sdialog.dialog('destroy');
                    sdialog.dialog({
                        'title': 'Регистрация завершена',
                        close: function(event, ui) { location.href = '/' },
                        buttons: { "Ok": function() { $(this).dialog("close"); } }
                    });
                    sdialog.html("<p>Регистрация завершена успешно.</p>");
                    sdialog.dialog('open');
                }
                else
                {
                    sdialog.dialog('destroy');
                    sdialog.dialog({
                        'title': 'Неудачная попытка',
                        close: function(event, ui) { location.href = '/' },
                        buttons: { "Ok": function() { $(this).dialog("close"); } }
                    });
                    sdialog.html("<p>Регистрация завершилась ошибкой. Пожалуйста повторите позже.</p>");
                    sdialog.dialog('open');
                }
                
                return false;
            });
        },
        errorPlacement: function(error, element) {
            $("<div />").html(error).insertAfter(element);
            element.parent().addClass("errorValidate");
        },
        success: function(label) {
            label.parent().parent().removeClass("errorValidate");
        }
    });
}

function validate_profile()
{
    var validator = $('#register_edit').validate({
        
        submitHandler: function(form)
        {
            /**
             * Дополнительная валидация
             */
            if(parseInt($('#selregion').val()) < 1)
            {
                validator.showErrors({'data[region]': 'Выберете город'});
                return false;
            }

            var sdialog = $('#submit-dialog');
            sdialog.dialog({modal: true});

            $.post(location.href.replace('#', '')+'?ajax=true', $(form).serialize(), function(data, textStatus)
            {
                if(data == undefined) return false;

                if(data == 'true')
                {
                    sdialog.dialog('destroy');
                    sdialog.dialog({
                        'title': 'Готово!',
                        close: function(event, ui) { location.href = location.href },
                        buttons: { "Ok": function() { $(this).dialog("close"); } }
                    });
                    sdialog.html("<p>Ваши данные изменены.</p>");
                    sdialog.dialog('open');
                }
                else
                {
                    sdialog.dialog('destroy');
                    sdialog.dialog({
                        'title': 'Неудачная попытка',
                        close: function(event, ui) { location.href = location.href },
                        buttons: { "Ok": function() { $(this).dialog("close"); } }
                    });
                    sdialog.html("<p>Изменение данных закончилось ошибкой.</p>");
                    sdialog.dialog('open');
                }

                return false;
            });
        },
        errorPlacement: function(error, element) {
            $("<div />").html(error).insertAfter(element);
            element.parent().addClass("errorValidate");
        },
        success: function(label) {
            label.parent().parent().removeClass("errorValidate");
        }
    });
}

function validate_advanced_data()
{
    var validator = $('#edit_advanset_data').validate({

        submitHandler: function(form)
        {
            var sdialog = $('#submit-dialog');
            sdialog.dialog({modal: true});

            $.post(location.href.replace('#', '')+'?ajax=true', $(form).serialize(), function(data, textStatus)
            {
                if(data == undefined) return false;

                if(data == 'true')
                {
                    sdialog.dialog('destroy');
                    sdialog.dialog({
                        'title': 'Готово!',
                        close: function(event, ui) { location.href = location.href },
                        buttons: { "Ok": function() { $(this).dialog("close"); } }
                    });
                    sdialog.html("<p>Ваши данные изменены.</p>");
                    sdialog.dialog('open');
                }
                else
                {
                    sdialog.dialog('destroy');
                    sdialog.dialog({
                        'title': 'Неудачная попытка',
                        close: function(event, ui) { location.href = location.href },
                        buttons: { "Ok": function() { $(this).dialog("close"); } }
                    });
                    sdialog.html("<p>Изменение данных закончилось ошибкой.</p>");
                    sdialog.dialog('open');
                }

                return false;
            });
        },
        errorPlacement: function(error, element) {
            $("<div />").html(error).insertAfter(element);
            element.parent().addClass("errorValidate");
        },
        success: function(label) {
            label.parent().parent().removeClass("errorValidate");
        }
    });
}

function validate_password()
{
    var validator = $('#edit_password').validate({

        rules: {
            new_password: {
                required:   true,
                minlength:  4
            },
            renew_password: {
                required:   true,
                minlength:  4,
                equalTo:    "#passwd"
            }
        },
        submitHandler: function(form)
        {
            var sdialog = $('#submit-dialog');
            sdialog.dialog({modal: true});

            $.post(location.href.replace('#', '')+'?ajax=true', $(form).serialize(), function(data, textStatus)
            {
                if(data == undefined) return false;

                if(data == 'true')
                {
                    sdialog.dialog('destroy');
                    sdialog.dialog({
                        'title': 'Пароль',
                        close: function(event, ui) { location.href = location.href },
                        buttons: { "Ok": function() { $(this).dialog("close"); } }
                    });
                    sdialog.html("<p>Пароль успешно изменён.</p>");
                    sdialog.dialog('open');
                }
                else
                {
                    sdialog.dialog('destroy');
                    sdialog.dialog({
                        'title': 'Неудачная попытка',
                        close: function(event, ui) { location.href = location.href },
                        buttons: { "Ok": function() { $(this).dialog("close"); } }
                    });
                    sdialog.html("<p>"+data+"</p>");
                    sdialog.dialog('open');
                }

                return false;
            });
        },
        errorPlacement: function(error, element) {
            $("<div />").html(error).insertAfter(element);
            element.parent().addClass("errorValidate");
        },
        success: function(label) {
            label.parent().parent().removeClass("errorValidate");
        }
    });
}

function add_event_upload()
{
    var sdialog = $('#submit-dialog');
    var ajaxUrl = location.href.replace('#', '')+'?ajax=true&logo=1';
    $('#logo').each(function(){
        new Ajax_upload(this, {
            action: ajaxUrl,
            responseType: 'json',
            onSubmit: function(file, ext) {
                sdialog.dialog({modal: true});

                button=this._button;
                $(button).html('Загрузка...');
                interval = window.setInterval(function(){
                    var text = $(button).html();
                    if (text.length < 11){
                        $(button).html(text + '.');
                    } else {
                        $(button).html('Загрузка...');
                    }
                }, 200);
            },
            onComplete: function(file, response) {
                button=this._button;
                $ul=$(button).next();
                console.log(file);
                console.log(response);
                window.clearInterval(interval);
                $(button).html('Загрузить файл');
                sdialog.dialog('destroy');
                sdialog.dialog({
                    'title': response.error ? 'Ошибка загрузки' : 'Загрузка',
                    close: function(event, ui) { location.href = location.href },
                    buttons: { "Ok": function() { $(this).dialog("close"); } }
                });
                sdialog.html(response.error ? ("<p>" + response.error + "</p>") : ("<p>" + response.message + "</p>"));
                sdialog.dialog('open');
            }
        });
    });
}

function editTournament(id)
{
    var tdialog = $('#tournir-dialog');
    var sdialog = $('#submit-dialog');
    
    $.getJSON('/ajax.php', {'act': 'get_tournament', 'id': id}, function(data) {
        if(data != 'false')
        {
            for(var key in data) {
                tdialog.find(':input[name="data['+key+']"]').val(data[key]);
            }
        }
    });

    $.getJSON('/ajax.php', {'act': 'get_tournament_types'}, function(data) {
        if(data != false)
        {
            $('#formats').html();
            for(var key in data) {
                $('#formats').append("<option value='"+key+"'>"+data[key]+"</option>");
            }
        }
    });

    tdialog.dialog({
        'modal': true,
        'width': '500px',
        'title': 'Редактировать турнир',
        open: function(event, ui) {
           $('#frules,#finfo').tinymce({
              script_url : '/admin/mods/editor/tiny_mce.js',
              theme : "advanced",
              plugins: 'table',
              theme_advanced_buttons1 : "mybutton,bold,italic,underline,separator,strikethrough,justifyleft,justifycenter,justifyright,justifyfull,bullist,numlist,undo,redo,link,unlink",
              theme_advanced_buttons2 : "tablecontrols",
              theme_advanced_buttons3 : "",
              theme_advanced_toolbar_location : "top",
              theme_advanced_toolbar_align : "left",
              theme_advanced_statusbar_location : "bottom"
           });
        },
        close: function(event, ui) {
            $('#frules').tinymce().setContent('');
            $('#finfo').tinymce().setContent('');
            $('#frules').tinymce().remove();
            $('#finfo').tinymce().remove();
            $(this).dialog("destroy");
        },
        buttons: {
            "Сохранить": function()
            {
                var request = {};
                request['id'] = id;
                request['save']  = true;
                request['ajax'] = true;
                $('#tournir-form').find("input, textarea, select").each(function()
                    {
                        if(this.name == 'data[rules]')
                            request[this.name] = $('#frules').tinymce().getContent();
                        else
                            if(this.name == 'data[info]')
                                request[this.name] = $('#finfo').tinymce().getContent();
                            else
                                request[this.name] = this.value;
                    }
                );

                $.post('/profile/tournament/', request, function(data)
                {
                    sdialog.dialog({modal: true});
                    sdialog.dialog('destroy');
                    sdialog.dialog({
                        'title': 'Редактирование турнира',
                        close: function(event, ui) {
                            $(this).dialog("destroy");
                        },
                        buttons: {
                            "Ok": function() {
                                $(this).dialog("close");
                                tdialog.dialog("close");
                                var href = document.location.href;
                                document.location.href = href.replace("#", "") + "#tab-tournament";
                            }
                        }
                    });
                    
                    if('true' == data)
                    {
                        sdialog.html("<p>Редактирование турнира завершено успешно!</p>");
                        sdialog.dialog('open');
                    }
                    else
                    {
                        sdialog.html("<p>Произошла ошибка!</p>");
                        sdialog.dialog('open');
                    }
                });
            },
            "Отмена": function()
            {
                $(this).dialog("destroy");
            }
        }
    });
    return false;
}

function deleteTournament(id)
{
    if(confirm('Удалить турнир?'))
    {
        $.post('/profile/tournament/', {'ajax': true, 'delete': true, 'id': id});
        $('#tour_' + id).remove();
    }
    return false;
}

function addTournament()
{
    var tdialog = $('#tournir-dialog');
    var sdialog = $('#submit-dialog');

    $.getJSON('/ajax.php', {'act': 'get_tournament_types'}, function(data) {
        if(data != false)
        {
            $('#formats').html();
            for(var key in data) {
                $('#formats').append("<option value='"+key+"'>"+data[key]+"</option>");
            }
        }
    });

    $('#tournir-form').find("input, textarea, select").each(function() {
        this.value = '';
    });

    tdialog.dialog({
        'modal': true,
        'width': '500px',
        'title': 'Создать турнир',
        open: function(event, ui) {
            $('#frules,#finfo').tinymce({
                script_url : '/admin/mods/editor/tiny_mce.js',
                theme : "advanced",
                plugins: 'table',
                theme_advanced_buttons1 : "mybutton,bold,italic,underline,separator,strikethrough,justifyleft,justifycenter,justifyright,justifyfull,bullist,numlist,undo,redo,link,unlink",
                theme_advanced_buttons2 : "tablecontrols",
                theme_advanced_buttons3 : "",
                theme_advanced_toolbar_location : "top",
                theme_advanced_toolbar_align : "left",
                theme_advanced_statusbar_location : "bottom"
            });
        },
        close: function(event, ui) {
            $('#frules').tinymce().setContent('');
            $('#finfo').tinymce().setContent('');
            $('#frules').tinymce().remove();
            $('#finfo').tinymce().remove();
            $(this).dialog("destroy");
        },
        buttons: {
            "Сохранить": function()
            {
                var request = {};
                request['add']  = true;
                request['ajax'] = true;
                $('#tournir-form').find("input, textarea, select").each(function()
                    {
                        if(this.name == 'data[rules]')
                            request[this.name] = $('#frules').tinymce().getContent();
                        else
                            if(this.name == 'data[info]')
                                request[this.name] = $('#finfo').tinymce().getContent();
                            else
                                request[this.name] = this.value;
                    }
                );

                $.post('/profile/tournament/', request,
                function(data)
                {
                    sdialog.dialog({modal: true});
                    sdialog.dialog('destroy');
                    sdialog.dialog({
                        'title': 'Создание турнира',
                        close: function(event, ui) {
                            $(this).dialog("destroy");
                        },
                        buttons: {
                            "Ok": function() {
                                $(this).dialog("close");
                                tdialog.dialog("close");
                                var href = document.location.href;
                                document.location.href = href.replace("#", "") + "#tab-tournament";
                            }
                        }
                    });

                    if('true' == data)
                    {
                        sdialog.html("<p>Создание турнира завершено успешно!</p>");
                        sdialog.dialog('open');
                    }
                    else
                    {
                        sdialog.html("<p>Произошла ошибка!</p>");
                        sdialog.dialog('open');
                    }
                });
            },
            "Отмена": function()
            {
                $(this).dialog("destroy");
            }
        }
    });
    return false;
}

function add_cuisine_menu()
{
    var lastel = $('#club_menu_cuisine').find('tr:last');
    var index  = lastel.attr('index');
    index = parseInt(index);
    lastel.attr('index', index + 1);
    lastel.remove();
    
    var select = lastel.find('td:index(0)').html();

    var html = $('<tr></tr>').append(
        $('<td></td>').append(
            select
        )
    ).append(
        $('<td></td>').append(
            $('<input/>').attr({type: 'text', name: 'title[]'}).css({width: '150px'})
        )
    ).append(
        $('<td></td>').append(
            $('<input/>').attr({type: 'text', name: 'price[]'}).css({width: '150px'})
        ).append(' руб.')
    ).append(
        $('<td></td>').append(
            $('<a/>').attr({'href': '#'}).html('Удалить').click(function()
            {
                var index = $(this).parent().parent().attr('index');
                index = parseInt(index);
                $('#club_menu_cuisine').find('tr[index='+index+']').remove();

                return false;
            })
        )
    ).attr({'index': index}).appendTo($('#club_menu_cuisine').find('tbody:index(0)'));
    lastel.appendTo($('#club_menu_cuisine').find('tbody:index(0)'));
}

$(document).ready(function() {
    $.extend($.validator, {
        messages: {
            required: "Это поле обязательно для заполнения.",
            remote: "Please fix this field.",
            email: "Введите правильный email адресс",
            url: "Введите правильную url ссылку",
            date: "Введите правильную дату",
            dateISO: "Введите дату в формате ISO",
            number: "Введите число.",
            digits: "Please enter only digits",
            equalTo: "Введённые значения не совпадают",
            accept: "Please enter a value with a valid extension.",
            maxlength: $.validator.format("Значение не должно превышать {0} символов."),
            minlength: $.validator.format("Значение не должно быть меньше {0} символов."),
            rangelength: $.validator.format("Введите значение длиной от {0} до {1} символов."),
            range: $.validator.format("Введите значение от {0} до {1}."),
            max: $.validator.format("Значение не должно превышать {0}."),
            min: $.validator.format("Значение не должно быть меньше {0}.")
        }
    });
    $.datepicker.regional.ru =
    {
        closeText:"Закрыть",
        prevText:"&#x3c;Пред",
        nextText:"След&#x3e;",
        currentText:"Сегодня",
        monthNames:["Январь","Февраль","Март","Апрель","Май","Июнь","Июль","Август","Сентябрь","Октябрь","Ноябрь","Декабрь"],
        monthNamesShort:["Янв","Фев","Мар","Апр","Май","Июн","Июл","Авг","Сен","Окт","Ноя","Дек"],
        dayNames:["воскресенье","понедельник","вторник","среда","четверг","пятница","суббота"],
        dayNamesShort:["вск","пнд","втр","срд","чтв","птн","сбт"],
        dayNamesMin:["Вс","Пн","Вт","Ср","Чт","Пт","Сб"],
        dateFormat:"dd.mm.yy",
        firstDay:1,
        isRTL:false
    };
    
    validate();
    validate_profile();
    validate_password();
    validate_advanced_data();
    add_event_upload();
    $('input[type=radio]').attr("class", "radio");
    $.datepicker.setDefaults($.extend({showMonthAfterYear: false}, $.datepicker.regional['ru']));
    $('#date_open').datepicker({
        dateFormat: 'yy.mm.dd'
    });
    $('#dt_start').datepicker({
        dateFormat: 'yy.mm.dd'
    });

    //Подгружаем районы
    $('#selregion').change(function() {
        $('#selarea').html('');
        $.getJSON('/ajax.php?act=select_area&ajax=true', {id: this.value}, function(data, textStatus) {
            var select = $('#selarea');

            if(data == false)
            {
                select.parent().parent().css("display", "none");
                return;
            }

            select.parent().parent().css("display", "table-row");
            select.append($("<option></option>").val(0).html('Выберете район'));
            for(var i = 0; i < data.length; i++)
            {
                select.append($("<option></option>").val(data[i].id).html(data[i].title));
            }
        });
    });

    //Подгужаем станции метро
    $('#selarea').change(function() {
        $('#selsubway').html('');
        $.getJSON('/ajax.php?act=select_subway&ajax=true', {id: this.value}, function(data, textStatus) {
            var select = $('#selsubway');

            if(data == false)
            {
                select.parent().parent().css("display", "none");
                return;
            }

            select.parent().parent().css("display", "table-row");
            select.append($("<option></option>").val(0).html('Выберете метро'));
            for(var i = 0; i < data.length; i++)
            {
                select.append($("<option></option>").val(data[i].id).html(data[i].title));
            }
        });
    });
    
    $('#add_topic').validate({
        rules: {
            title: {
                required: true,
                minlength: 5
            },
            description: {
                required: true,
                minlength: 10
            }
        },
        submitHandler: function(form) {
            $(form).send();
        },
        errorPlacement: function(error, element) {
            $("<div />").html(error).insertAfter(element);
            element.parent().addClass("errorValidate");
        },
        success: function(label) {
            label.parent().parent().removeClass("errorValidate");
        }
    });

    $('#add_post').validate({
        rules: {
            description: {
                required: true,
                minlength: 10
            }
        },
        submitHandler: function(form) {
            $(form).send();
        },
        errorPlacement: function(error, element) {
            $("<div />").html(error).insertAfter(element);
            element.parent().addClass("errorValidate");
        },
        success: function(label) {
            label.parent().parent().removeClass("errorValidate");
        }
    });
    
    //Снимаем фокусировку со ссылок
    $('a').focus(function() { $(this).blur(); });

    $('.regions > a').each(function() {
        if($('.regions > a').index(this) % 4 == 0)
        {
            $(this).addClass('first');
        }
        if($('.regions > a').index(this) % 4 == 3)
        {
            $(this).addClass('end').after($('<div />').addClass('separator'));
        }
    });
    
    $('#login').focus(function(){
        var login = $(this);
        if(login.val() == 'логин')
            login.val('');
    });
    
    $('#password').focus(function() {
        var passwd = $(this);
        if(passwd.val() == 'пароль')
            $(this).val('');
    });

    $('#club_menu_cuisine_add').click(function()
    {
        add_cuisine_menu();
    });

    $('.club_menu_cuisine_remove').click(function()
    {
        var index = $(this).parent().parent().attr('index');
        var cuisine_id = $(this).parent().parent().attr('cuisine_id');

        index = parseInt(index);
        cuisine_id = parseInt(cuisine_id);
        if(isNaN(cuisine_id)) cuisine_id = 0;

        $.post(document.URL, {'cuisine_delete': '1', 'id': cuisine_id}, function(responce) {
            if(responce == 'true')
                $('#club_menu_cuisine').find('tr[index='+index+']').remove();
        });

        return false;
    });

    var i = 0;
    var val = 0;
    for(i = 0; i < 24; i++)
    {
        val = i.toString().length==1?'0'+i:i;
        if(i == 12)
            $('<option value="'+val+'" selected="selected">'+val+'</value>').appendTo('#tournament_time_h');
        else
            $('<option value="'+val+'">'+val+'</value>').appendTo('#tournament_time_h');
    }

    for(i = 0; i < 60; i++)
    {
        val = i.toString().length==1?'0'+i:i;
        if(i == 0)
            $('<option value="'+val+'" selected="selected">'+val+'</value>').appendTo('#tournament_time_m');
        else
            $('<option value="'+val+'">'+val+'</value>').appendTo('#tournament_time_m');
    }

    $('#filterByArea').change(function()
    {
        var value = $(this).val();

        if(value == 0)
        {
            $('div.club_list').show();
            $('#filterBySubwaySpan').hide();
            return false;
        }
        else
        {
            $('div.club_list').show();
            $('div.club_list[area!='+value+']').hide();

            $.getJSON('/ajax.php?act=select_subway&ajax=true', {'id': value}, function(data, textStatus)
            {
                var select = $('#filterBySubway');

                if(data == false)
                {
                    $('#filterBySubwaySpan').hide();
                    return false;
                }

                select.html('').show();
                $('#filterBySubwaySpan').show();
                select.append($('<option></option>').val(0).html('Все станции'));
                for(var i = 0; i < data.length; i++)
                {
                    select.append($('<option></option>').val(data[i].id).html(data[i].title));
                }
            });
            
            return false;
        }
    });

    $('#news-edit').tinymce({
        script_url : '/admin/mods/editor/tiny_mce.js',
        theme : "advanced",
        plugins: 'table',
        theme_advanced_buttons1 : "mybutton,bold,italic,underline,separator,strikethrough,justifyleft,justifycenter,justifyright,justifyfull,bullist,numlist,undo,redo,link,unlink",
        theme_advanced_buttons2 : "tablecontrols",
        theme_advanced_buttons3 : "",
        theme_advanced_toolbar_location : "top",
        theme_advanced_toolbar_align : "left",
        theme_advanced_statusbar_location : "bottom",
        width: '600',
        height: '400'
    });

    $('#filterBySubway').change(function()
    {
        var value = $(this).val();

        if(value == 0)
        {
            var areaValue = $('#filterByArea').val();
            $('div.club_list').show();
            $('div.club_list[area!='+areaValue+']').hide();
        }
        else
        {
            $('div.club_list').show();
            $('div.club_list[subway!='+value+']').hide();
        }

        return false;
    });

    function rememberPass()
    {
        //$('<div />').addClass('remember').append('body');
    }
});