$(document).ready(function () {
    
    /// Open top registration popup
    $('.openRegistration').click(function(event) {
        event.preventDefault();
        $('html, body').animate({
            scrollTop: 0
        });
        $(".social_reg span").click();
    });
    
    /// Show need-to-login popup
    $('a.guest-link').fancybox({
        'hideOnContentClick': false
    });

    /// Restore password dialog
    $('#showRestorePasswordDialog').click(function() {
        $('#restorePasswordDialog').show();
    });
    $("#restorePasswordDialog").pngFix();
    $("#restorePasswordDialog").corner();
    $("#restorePasswordDialog .reg_close").click(function() {
        $("#restorePasswordDialog").hide();
        $('#restorePassword_Email').val('E-mail');
    });
    $('#restorePasswordForm').submit(function() {
        return false;
    });
    $('#restorePasswordFormSubmit').click(function(event) {
        event.preventDefault();
        var form = $('#restorePasswordForm');
        var data = form.serialize();
        $.ajax({
            data: data,
            dataType: 'jsonp',
            url: form.attr('action'),
            context: this,
            beforeSend: function() {
                $('restorePasswordFormSubmit .registration_error').empty();
                $(this).attr('disabled', 'disabled');
            },
            success: function(response) {
                if (response.success) {
                    $('#restorePasswordFormSubmit').parent().hide();
                    $('#restorePasswordForm').hide();
                    $('#restorePasswordDialog span').after($('<div/>', {
                        text: response.successText,
                        'class': 'registration_error'
                    }));
                } else {
                    $.each(response.messages, function(index, value) {
                        $('#' + index + '-errors').html(getErrorHtml(value));
                    });
                    $(this).removeAttr('disabled');
                }
            }
        });
    });

    ///
    $(".children_mults").pngFix();
    $(".ch-i_right_imgkont").pngFix();

    /// Feedback form
    $(".mes").pngFix();
    $(".feedback-email").click(function() {
        $(".footer .mes").toggle();
    });
    $(".mes_close").click(function() {
        $(".mes").hide();
        $('#feedback-form')[0].reset();
        $('#feedback_name_error').html('');
        $('#feedback_email_error').html('');
        $('#feedback_text_error').html('');
    });
    $('#feedback-submit').click(function(event) {
        event.preventDefault();
        var form = $('#feedback-form');
        var data = form.serialize();
        $.ajax({
            context: this,
            beforeSend: function() {
                $('#feedback_name_error').html('');
                $('#feedback_email_error').html('');
                $('#feedback_text_error').html('');
                $(this).attr('disabled', 'disabled');
            },
            success: function(response) {
                if (response.isValid) {
                    $.ajax({
                        data: data,
                        dataType: 'jsonp',
                        url: form[0].action,
                        success: function() {
                            $('.mes_close').click();
                            $(this).removeAttr('disabled');
                        }
                    });
                } else {
                    $('#feedback_name_error').html(getErrorHtml(response.messages.name));
                    $('#feedback_email_error').html(getErrorHtml(response.messages.email));
                    $('#feedback_text_error').html(getErrorHtml(response.messages.text));
                    $(this).removeAttr('disabled');
                }
            },
            data: data,
            dataType: 'jsonp',
            url: '/ajax/validate-feedback-form-jsonp'
        });
    });


    $("input:text").attr('title', $(this).val());
    $("input:text").each(function() {
        hobot = $(this).val();
        $(this).attr('title', hobot);
    });
    $("textarea").each(function() {
        hobot2 = $(this).val();
        $(this).attr('title', hobot2);
    });
    inputFocusBlur("input:text.auto-clear");
    inputFocusBlur("textarea.auto-clear");
    passwordFocus("social_input");
    passwordFocus("reg_input");

    /// registration window
    $(".social_reg span").click(function(){
        $(".reg_window").css("display", "block");
    });
    $(".reg_window").pngFix();
    $(".reg_window").corner();
    $(".reg_close").click(function(){
        $(".kiki").attr('title','e-mail' ).val('e-mail');
        $(".helpblock1reg_input").prev().val('').css('display','none')
        $(".helpblock1reg_input").css('display','inline-block')
        $(".reg_window").css("display", "none");
    });

    /// submit registration
    $('#registration-submit').click(function(event) {
        event.preventDefault();
        var form = $('#registration-form');
        var url = '/ajax/validate-registration-form';
        $.ajax({
            context: this,
            beforeSend: function() {
                $('#registration_name_error').html('');
                $('#registration_email_error').html('');
                $('#registration_password_error').html('');
                $(this).attr('disabled', 'disabled');
            },
            success: function(response) {
                if (response.isValid) {
                    form.submit();
                } else {
                    $('#registration_name_error').html(getErrorHtml(response.messages.name));
                    $('#registration_email_error').html(getErrorHtml(response.messages.email));
                    $('#registration_password_error').html(getErrorHtml(response.messages.password));
                    $(this).removeAttr('disabled');
                }
            },
            data: form.serialize(),
            dataType: 'json',
            type: 'POST',
            url: url
        });
    });

    /// open iframes for vkontakte|facebook
    $('a.vk-login').fancybox({
        'hideOnContentClick': false,
        'type': 'iframe',
        'width': 400,
        'height': 300
    });
    $('a.fb-login').fancybox({
        'hideOnContentClick': false,
        'type': 'iframe',
        'width': 400,
        'height': 300
    });

});

/// for ajax form validation
function getErrorHtml(formErrors)
{
    var o = '';
    for (var errorKey in formErrors) {
        o += formErrors[errorKey] + '<br/>';
    }
    return o;
}

function getFormErrors(errors) {
    var html = '';
    for (var errorType in errors) {
        for (var error in errors[errorType]) {
            html += errors[errorType][error] + '<br/>';
        }
    }
    return html;
}

function inputFocusBlur(inputSelector){
    $(inputSelector).focus(function(){
        if( $(this).val()==$(this).attr('title') ){
            $(this).attr('title',$(this).val());
            $(this).val('')
        }
    })
    .blur(function(){
        if ($(this).val()=='') {
            $(this).val($(this).attr('title'))
        }
    })

}

function passwordFocus(passSelector){
    $("."+passSelector+":password.auto-clear").css('display','none').after("<input type='text' value='Пароль' class='helpblock1"+passSelector+" "+passSelector+"' />")
    $(".helpblock1"+passSelector).focus(function(){
        $(this).css('display','none')
        $(".helpblock1"+passSelector).prev().css('display','inline-block').focus()
        .blur(function(){
            if($(".helpblock1"+passSelector).prev().val()==''){
                $(".helpblock1"+passSelector).prev().css('display','none');
                $(".helpblock1"+passSelector).css('display','inline-block')
            }

        })
    }
    )
}

function enableCKEditor() {
    $('textarea:not(".no-editor")').ckeditor({
        language: 'uk',
        filebrowserBrowseUrl : '/ckfinder/ckfinder.html&langCode=ru',
        filebrowserImageBrowseUrl : '/ckfinder/ckfinder.html?Type=Images&langCode=ru',
        filebrowserFlashBrowseUrl : '/ckfinder/ckfinder.html?Type=Flash&langCode=ru',
        filebrowserUploadUrl : '/ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Files',
        filebrowserImageUploadUrl : '/ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Images',
        filebrowserFlashUploadUrl : '/ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Flash'
    });
}
