$(document).ready(function(){

    $("#reg-login").change(checkLogin).keyup(checkLogin);
    $("#reg-submit").click(submitReg);

    $("#registration :input").bind("focus", function(e){
        if (help_mode) $(this).nextAll("div.help_block").show();
    }).bind("blur", function(e){
        if (help_mode) $(this).nextAll("div.help_block").hide();
    });
    
    $("#help_toggle").bind("click", function(e){
        help_mode = 1 - help_mode;
        if (!help_mode) {
            $(".help_block").hide();
            $("#help_toggle").text('Включить').prevAll('strong').text('выключен');
        } else {
            $("#help_toggle").text('Выключить').prevAll('strong').text('включен');
        }
    });
    
    // проверка имени на занятость
    $("#fid-login").bind("change keyup", function(e){
        if (!validUsername(help_mode)) {
            lastchecked = '';
            return;
        }
        clearTimeout(to);
        if (!$(this).attr('value') || $(this).attr('value') == lastchecked) return;
        to = setTimeout(checkUsername, 1000);
    });
    
    $("#agreement").nextAll('a').bind("click", function(e){  
        $("#agreement").nextAll('.help_block').show();
        return false;
    });
    
    $("#agree_close").bind("click", function(e){  
        $("#agreement").nextAll('.help_block').hide();
        return false;
    });
        
    // сохранение
    $("#save_button a").bind("click", function(e) {
        
        var ret = 0;
        $("#user_data :input").each(function() {
            if ($(this).prev('label').hasClass('req') && !$(this).val()) {
                $(this).nextAll('.error').text('Поле обязательно для заполнения').show();
                ret = 1;
            }
        });
        
        if (ret) return false;
        
        $("#save_button div").html('<img src="/img/ajax-loader.gif" /><br />');
        
        $.ajax({
            type: 'POST',
            url : $("#user_data").attr('action'),
            dataType : 'json',
            data: $("#user_data").serializeArray(),
            success: function (data) {  
                $("#save_button div").html('');                              
                if (!data.success) {
                    if (data.field)
                        $("#fid-"+data.field).nextAll('.error').text(data.message).show();
                        else alert(data.message);
                } else {
                    $("#save_button div").html('Данные сохранены.<br /><br />');
                }
            }
        });
        
        return false;
            
    });
        
    // регистрация
    $("#reg_button a").bind("click", function(e){
        $(".error").hide();

        if (!code) {
        // шаг 1

            var ret = 0;
            $("#registration :input").each(function() {
                if ($(this).prev('label').hasClass('req') && !$(this).val()) {
                    $(this).nextAll('.error').text('Поле обязательно для заполнения').show();
                    ret = 1;
                }
            });
            
            if (!$("#agreement").attr('checked')) {
                $("#agreement").nextAll('.error').text('Вы должны принять условия').show();
                ret = 1;       
            }
            
            reg = /[a-z0-9\-_]/;
            if (!$("#fid-login").val().match(reg)) {
                $("#fid-login").nextAll('.error').text('Только латинские буквы, цифры, знаки "-" и "_"').show();
                ret = 1;
            }
            
            if (!isEmail($("#fid-email").val())) {
                $("#fid-email").nextAll('.error').text('Пожалуйста, введите свой настоящий e-mail').show();
                ret = 1;
            }
            
            if (!validUsername(1)) ret = 1;
            
            if (ret) return false;
            
            $.ajax({
                type: 'POST',
                url : '/action/user/register_step1',
                dataType : 'json',
                data: $("#registration").serializeArray(),
                success: function (data) {                                
                    if (!data.success) {
                        if (data.field)
                            $("#fid-"+data.field).nextAll('.error').text(data.message).show();
                            else alert(data.message);
                    } else {
                        $("#registration").parent().hide();
                        $("#registration2").parent().show();
                        $(".registration_pages span.active").removeClass('active').next().addClass('active');
                        code = data.code;
                        $("#step").text('Шаг второй');
                    }
                }
            }); 
            
        } else {
        // шаг 2
        
            var ret = 0;
            $("#registration2 :input").each(function() {
                if ($(this).prev('label').hasClass('req') && !$(this).val())
                    $(this).nextAll('.error').text('Поле обязательно для заполнения').show();
            });
            
            if (ret) return false;
            
            var data = $("#registration2").serializeArray();
            data[data.length] = {name: 'code', value: code};
            
            $.ajax({
                type: 'POST',
                url : '/action/user/register_step2',
                dataType : 'json',
                data: data,
                success: function (data) {                                
                    if (!data.success) {
                        if (data.field)
                            $("#fid-"+data.field).nextAll('.error').text(data.message).show();
                            else alert(data.message);
                    } else {
                        $("#registration2").parent().hide();
                        $("#registration3").parent().show();
                        $(".registration_pages span.active").removeClass('active').next().addClass('active');
                        $(".reg_button").hide();
                        $("#step").text('Шаг третий');
                    }
                }
            }); 
        
        }

        return false;
    });
    
    SolmetraUploader.setErrorHandler('myError');
    SolmetraUploader.setEventHandler('myEvent');
    $('#preview a').bind("click", function(e){
        $('#preview img').attr('src','');
        $('#preview').hide();
        $('#avatar_orig').val('');
        $('#avatar_tmp').val('');
        return false;
    });


});
var help_mode = 1;
var to, lastchecked, code;

function validUsername(display_error) {
    reg = /^[a-z0-9\-_]+$/;
    //$("#fid-login").nextAll('.error').hide();
    if (!$("#fid-login").val().match(reg)) {
        if (display_error)
            $("#fid-login").nextAll('.error').text('Только строчные латинские буквы, цифры, знаки "-" и "_"').show();
        return false;
    }
    return true;
}

// проверка имени на занятость
function checkUsername() {
    lastchecked = $("#fid-login").attr('value');
    $.ajax({
        url : '/action/user/check',
        dataType : 'json',
        data: {login: lastchecked},
        success: function (data) {                                
            $("#fid-login").nextAll('.error').html(data.message).show();
        }
    });   
}

function myError (instance_id, error_id) {
  alert(error_id);
}

var uid;
function myEvent (instance_id, event_id, data) {

    switch(event_id) {
      case 'selected':
		uid = instance_id;
		//setTimeout(do_upload, 1000);
        break;
      case 'complete':
        $('#avatar_orig').val(data.name);
        $('#avatar_tmp').val(data.tmp_name);
        $('#preview img').attr('src', '/library/image.php?width=425&dontenlarge=1&src=/uploads/'+data.tmp_name);
        $('#preview').show();
        SolmetraUploader.flashTriggerCancel(instance_id);
        break;
      default:
        break;
    }
}

function do_upload() {
	SolmetraUploader.flashTriggerUpload(uid);
}

