var infoDialog;

$(document).ready(function() {
    function keyEnter(obj, act) {
       obj.keyup(function(e){
            if (e.keyCode == 13)  {
                act.click();
            }
        });
    }

    if(window.location.hash != '') {
        var hash = window.location.hash;
        if(hash.match(/message\_([0-9]+)/)) {
            var code = hash.replace(/[^0-9]/g, '');
            var msg = '';
            switch(parseInt(code, 10)) {
                case 100:
                    msg = _('Your account was updated');
                    break;
            }
            if(msg != '') {
                EasyGrowl.notify(msg);
                window.location.hash = '';
            }
        }
    }

    // TODO: make this beautiful
    keyEnter($('#l_password'),$('#login-button'));
    keyEnter($('#check'),$('#sign-up-button'));
    keyEnter($('#password-confirmation'),$('#sign-up-button'));
    keyEnter($('#password'),$('#sign-up-button'));
    keyEnter($('#email'),$('#sign-up-button'));
    keyEnter($('#first-name'),$('#sign-up-button'));
    keyEnter($('#last-name'),$('#sign-up-button'));
    keyEnter($('#recover_email'),$('#recover-button'));
    keyEnter($('#u_email'),$('#update-info-button'));
    keyEnter($('#u_first_name'),$('#update-info-button'));
    keyEnter($('#u_last_name'),$('#update-info-button'));
    keyEnter($('#a_agn_pass'),$('#change-pass-button'));

    // ------------------------- signup >> -------------------------------------

    function displaySubmitButton(st) {
        if (st == true) {
            $('#sign-up-button').show();
            $('#sign_image_area').hide();
        
        } else {
            $('#sign-up-button').hide();
            $('#sign_image_area').show();

        }
    }

    function isValidName(name) {

        sInString = name.replace(/ /g, ' ');

        if(sInString.replace(/(^\s+)|(\s+$)/g, '') == '') {
            return false;
        }

        var pattern = new RegExp(/[!#$%\&\=+_*^()<>@,;:\/`~]/i);
        return !pattern.test(name);
    }

    $('#sign-up-button').click(function() {
        var sendStatus = true;
        if(sendStatus && $('#email').val() == '') {
            sendStatus = false;
            EasyGrowl.notify(_('Please, enter your e-mail!'));
            return false;
        }

        if(sendStatus) {
            var firstname = $('#first-name').val();
            if(firstname == '') {
                sendStatus = false;
                EasyGrowl.notify(_('Please, enter your first name!'));
                return false;
            } else if(!isValidName(firstname) || firstname.length < 3) {
                sendStatus = false;
                EasyGrowl.notify(_('Please, enter valid first name!'));
                return false;
            }
        }

        if(sendStatus) {
            var lastname = $('#last-name').val();
            if(lastname == '') {
                sendStatus = false;
                EasyGrowl.notify(_('Please, enter your last name!'));
                return false;
            } else if(!isValidName(lastname) || lastname.length < 3) {
                sendStatus = false;
                EasyGrowl.notify(_('Please, enter valid last name!'));
                return false;
            }
        }

        if(sendStatus && $('#password').val() == '') {
            sendStatus = false;
            EasyGrowl.notify(_('Please, enter password!'));
            return false;
        }

        if(sendStatus && $('#password-confirmation').val() == '') {
            sendStatus = false;
            EasyGrowl.notify(_('Please, confirm password!'));
            return false;
        }
        
        if($('#check').attr('checked')) {
            if(sendStatus) {
                displaySubmitButton(false);
                $.ajax({
                    type: 'POST',
                    url: '/user/join',
                    data: $(".front_user_join_form").serialize(),
                    success: function(data) {
                        eval("data = " + data);
                        if (data.success) {
                            $('.front_user_join_form').css('display', 'none');
                            $('#confirmation-email-block').css('display', 'block');
                            $('#proceed-sign-up-button').focus();
                        } else {
                            EasyGrowl.notify(data.errorMessage);
                        }
                    }
                });
                displaySubmitButton(true);
            }
        } else {
            EasyGrowl.notify($('#check').attr('rel'));
            displaySubmitButton(true);
        }
        
    });

    $('#proceed-sign-up-button').click(function(){
                    if (window.location.hash == '#signup') {
                        window.location.href = window.location.href.slice(0,(window.location.href.length - window.location.hash.length))
                    } else {
                        window.location.reload();
                    }
//                $('form.front_user_join_form input[name="email"]').val();
//                $('form.front_user_join_form input[name="password"]').val();
//
//                $.ajax({
//                    type: 'POST',
//                    url: '/user/auto-login-signup',
//                    data: $("form.front_user_join_form").serialize(),
//                    success: function(data) {
//                        eval("data = " + data);
//                        if (data.success) {
//                            window.location.reload();
//                        } else {
//                            EasyGrowl.notify(data.errorMessage);
//                        }
//                    }
//                });


        })


    // ------------------------- signup << -------------------------------------

    // ------------------------- login >> --------------------------------------

    
    $('#login-button').click(function() {
        $("#sign-up-button").attr('disabled','false');
        $.ajax({
            type: 'POST',
            url: '/user/login',
            data: $(".front_user_entrance_form").serialize(),
            success: function(data) {
                eval("data = " + data);
                if (data.success) {
                    $("#sign-up-button").attr('disabled','true');
                    window.location.reload();
                } else {
                    EasyGrowl.notify(data.outMessage);
                }
            }
        });
    });
    // ------------------------- login << --------------------------------------

    // ------------------------- recover >> ------------------------------------
    $('.recover_pass_start').click(function() {
        $('#user_login_menu').animate({opacity: 0}, 'slow');
        $('#recover_menu').text($('#recover_menu').attr('title'));
        $('#step_1').css('display', 'block');
        $('#step_1').animate({opacity: '1.0'}, 1);
        $('#step_2').css('display', 'none');
        $('#step_2').animate({opacity: '0.0'}, 1);
        $('img[src*="white.png"]').height(450);
        $('.account-formwrapreg').height(240);
        $('#recover_dialog').animate({width: "200px"}).animate({opacity: "1.0"}, 'slow');
        return false;
    });
    
    $('#recover-button').click(function(e) {
        $('#step_1').animate({opacity: '0.0'}, 'slow');
        $('#step_1').css('display', 'none');
        $('#recover_message_layer').animate({opacity: '0.0'}, 100);
        $.ajax({
            type: 'POST',
            url: '/user/forgot',//?email=' + $('#recover_email').val(),
            data: {email: $('#recover_email').val()},
            beforeSend: function(){
                $('body').css('cursor', 'wait');
            },
            success: function(data) {
                $('body').css('cursor', 'default');
                eval("data = " + data);
                if (data.success) {
                    $('#recover_menu').text($('#recover_menu').attr('rel'));
                    $('#step_2').css('display', 'block');
                    $('#step_2').animate({opacity: '1.0'}, 'slow');
                } else {
                    $('#recover_message').text(data.errorMessage);
                    $('#step_1').css('display', 'block');
                    $('#step_1').animate({display: 'block'}).animate({opacity: '1.0'}, 'slow');
                    $('#recover_message_layer').animate({opacity: '0.3'}, 'slow').animate({opacity: '0.6'}, 'slow').animate({opacity: '1.0'}, 'slow');
                }
            }
        });
        e.stopPropagation();
        return false;
    });
    // ------------------------- recover << ------------------------------------

    // ------------------------- info >> ---------------------------------------
    window.infoDialog = $('.user_info[rel]').overlay({
        oneInstance: false,
        closeOnClick: true,
        effect: 'apple',
        api: true,
        expose: {color: '#000', opacity: 0.7},
        onBeforeLoad : (function() {
            $('.account-menu-buton-action-button').css('display', 'block');
            $('.account-menu-buton-action-loader').css('display', 'none');
            $.ajax({
                type: 'POST',
                url: '/user/getinfo',
                success: function(data) {
                    eval("data = " + data);
                    
                    if (data.success) {
                        $('.panels').find('input[name=first_name]').val(data.user.first_name);
                        $('.panels').find('input[name=last_name]').val(data.user.last_name);
                        $('.panels').find('input[name=email]').val(data.user.email);

                        if (data.projects.length > 0) {
                            $("#user-projects-list").append('<ul id="projects-grid"></ul>');
                            for (var i in data.projects) {
                                var content ='<li><div>' +
                                    '<p>' + data.projects[i].name + '</p> <div>' ;

                                if (data.projects[i].isadmin == true) {
                                    content += '<a target="_blank" href="http://' + data.app + '.' + data.domain + '/index/auth/?aid=' + AID + '&pid=' + data.projects[i].id + '">' + _('Admin') + '</a>';
                                }

                                content += '<a target="_blank" href="http://' + data.projects[i].ident + '.' + data.domain + '">' + _('Forums') + '</a>' +
                                    '</div></div></li>';
                                $("#projects-grid").append(content);
//                                $("#projects-grid").append(
//                                    '<li style="background-color: #E0FDFD; padding: 5px; -moz-border-radius: 5px; margin: 3px; border-radius: 5px; -webkit-border-radius: 5px;">' +
//                                    '<span>' + data.projects[i].name + '</span>' +
//                                    '<a style="float: right;" target="_blank" href="http://' + data.projects[i].ident + '.' + data.url + '">' + _('Forums') + '</a>' +
//                                    '</li>'
//                                );
                            }
                        } else {
                            $("#user-projects-list").append('<div class="account-field" style="text-align:center; width:100%"><label style="float:none">' + _('You do not belong to testers of any project.') + '</label></div>');
                        }
                    } else {
                        window.location.reload();
                    }
                }
            });
        }),
        onStart: (function() {
            if(jQuery.browser.msie && jQuery.browser.version == '6.0') {
                window.pngFixture('div.close');
            }
            
            $('div.ord_tabs_controller').css('width', '410px');
            $('#info_id').css('max-height', '220px');
            $('#pass_id').css('max-height', '220px');
            $('#projects_id').css('max-height', '220px');
        }),
        onLoad : (function() {
            if(jQuery.browser.msie && jQuery.browser.version == '6.0') {
                $('#account').css('background-image', 'none');
                $('#account').css('background-color', '#FFFFFF');
                $('#account').css('border', '1px solid #CCCCCC');
                $('img').each(function() {
                    if($(this).attr('width') > 700) {
                        $(this).remove();
                    }
                });
            }
        }),
        onClose: (function() {
            $("#user-projects-list > *").remove();
        })
    });
    $("#user_account_menu ul.acc_upd_tabs").tabs($("div.panels > div"), {api: true});
    // ------------------------- info << ---------------------------------------

    // ------------------------- update info << --------------------------------
    $('#update-info-button').click(function() {
        $('.account-menu-buton-action-button').css('display', 'none');
        $('.account-menu-buton-action-loader').css('display', 'block');
        $.ajax({
            type: 'POST',
            url: '/user/updateinfo',
            data: $('form[name=update_user_info]').serialize(),
            success: function(data) {
                eval("data = " + data);
                if (data.success) {
                    window.location.href = window.location.href + '#message_100';
                    window.location.reload();
                } else {
                    EasyGrowl.notify(data.outMessage);
                    $('.account-menu-buton-action-button').css('display', 'block');
                    $('.account-menu-buton-action-loader').css('display', 'none');
                }
            }
        });
    });
    // ------------------------- update info << --------------------------------

    // ------------------------- change pass << --------------------------------
    $('#change-pass-button').click(function() {
        $('.account-menu-buton-action-button').css('display', 'none');
        $('.account-menu-buton-action-loader').css('display', 'block');
        if(!window.SINGLE_SIGN_ON_MODE) {
            $.ajax({
                type: 'POST',
                url: '/user/changepass',
                data: $('form[name=change_user_pass]').serialize(),
                success: function(data) {
                    eval("data = " + data);
                    if (data.success) {
                        EasyGrowl.notify(data.outMessage);

                        // --- clearing ---
                        $('#a_old_pass').val('');
                        $('#a_new_pass').val('');
                        $('#a_agn_pass').val('');

                        window.infoDialog.close();

                    } else {
                        EasyGrowl.notify(data.outMessage);
                        $('.account-menu-buton-action-loader').css('display', 'none');
                        $('.account-menu-buton-action-button').css('display', 'block');
                    }
                }
            });
        } else {
            EasyGrowl.notify(_('Unable to change password for Single-Sign-On account'));
        }
    });
    // ------------------------- change pass << --------------------------------

    // --------------------- leave project dialog >> ---------------------------
    $('a.leave_project[rel]').overlay({
        oneInstance: false,
        closeOnClick: true,
        expose: {
            color: '#333',
            loadSpeed: 200,
            opacity: 0.9
        }
    });
    
    $("#leave_project_agree").click(function() {
        window.location.href = '/user/leavethis?p_id=' + window.THIS_PROJECT_ID;
    });

    $("#leave_project_no").click(function() {
        if(jQuery.browser.msie && jQuery.browser.version == '6.0') {
            window.location.reload();
        }
    });
    // --------------------- leave project dialog << ---------------------------

    // ------------------------- invitation >> ---------------------------------------
    window.sendInviteDialog = $('.send_invite[rel]').overlay({
        oneInstance: false,
        closeOnClick: true,
        effect: 'apple',
        api: true,
        expose: {color: '#000', opacity: 0.7},
        onBeforeLoad : (function() {
            $('.send-invite-buton-action-button').css('display', 'block');
            $('.send-invite-buton-action-loader').css('display', 'none');
        }),
        onStart: (function() {
            if(jQuery.browser.msie && jQuery.browser.version == '6.0') {
                window.pngFixture('div.close');
            }
        }),
        onLoad : (function() {
            $('img[src*="white.png"]').height(250);
            if(jQuery.browser.msie && jQuery.browser.version == '6.0') {
                $('#send_invite').css('background-image', 'none');
                $('#send_invite').css('background-color', '#FFFFFF');
                $('#send_invite').css('border', '1px solid #CCCCCC');
                $('img').each(function() {
                    if($(this).attr('width') > 700) {
                        $(this).remove();
                    }
                });
            }
        }),
        onClose: (function() {
            
        })
    });
    // ------------------------- invitation << ---------------------------------------

    // ------------------------- send invite << --------------------------------
    $('#send-invite-button').click(function() {
        $('.send-invite-buton-action-button').css('display', 'none');
        $('.send-invite-buton-action-loader').css('display', 'block');
        $.ajax({
            type: 'POST',
            url: '/user/send-invite',
            data: $('form[name=send_invite]').serialize(),
            success: function(data) {
                eval("data = " + data);
                if (data.success) {
                    $('#i_email').val('');
                    $('#i_email').focus();
                } 
                EasyGrowl.notify(data.outMessage);
                $('.send-invite-buton-action-button').css('display', 'block');
                $('.send-invite-buton-action-loader').css('display', 'none');
            }
        });
    });
    // ------------------------- send invite << --------------------------------
    //
    // ------------------------- join project >> ---------------------------------------
    window.joinProjectDialog = $('.join_project[rel]').overlay({
        oneInstance: false,
        closeOnClick: true,
        effect: 'apple',
        api: true,
        expose: {color: '#000', opacity: 0.7},
        onBeforeLoad : (function() {
            $('.join-project-buton-action-button').css('display', 'block');
            $('.join-project-buton-action-loader').css('display', 'none');
        }),
        onStart: (function() {
            if(window.EX_BROWSER_MODE == 'IE6') {
                $('img').each(function() {
                    if($(this).attr('width') > 500) {
                        $(this).remove();
                    }
                });
                window.pngFixture('div.close');
                $('#join_project').css('height', '250px');
            }
        }),
        onLoad : (function() {
            if(window.EX_BROWSER_MODE == 'IE6') {
                $('#join_project').css('background-image', 'none');
                $('#join_project').css('background-color', '#FFFFFF');
                $('#join_project').css('border', '1px solid #CCCCCC');
                $('img').each(function() {
                    if($(this).attr('width') > 500) {
                        $(this).remove();
                    }
                });
            }
        }),
        onClose: (function() {

        })
    });
    // ------------------------- join project << ---------------------------------------

    // ------------------ send join project request << -----------------------------
    $('#join-project-button').click(function() {

        if($('#jp_comment').val() == '') {
            return false;
        }

        $('.join-project-buton-action-button').css('display', 'none');
        $('.join-project-buton-action-loader').css('display', 'block');

        $.ajax({
            type: 'POST',
            url: '/user/join-project',
            data: $('form[name=join_project]').serialize(),
            success: function(data) {
                eval("data = " + data);
                if (data.success) {
                    window.joinProjectDialog.close();
                    EasyGrowl.notify(data.outMessage);
                    window.location.reload();
                } else {
                    EasyGrowl.notify(data.outMessage);
                    $('.send-invite-buton-action-button').css('display', 'block');
                    $('.send-invite-buton-action-loader').css('display', 'none');
                }
            }
        });
    });
    // ----------------- send join project request << ------------------------------


    $('.recovery-change-button').click(function() {

        var pass        = $('.password-recovery-form').find('input[name=recovery-new-password]').val();
        var pass_agn    = $('.password-recovery-form').find('input[name=recovery-new-password-again]').val();

        if(pass == '') {
            EasyGrowl.notify(_('Please, enter New Password'));
            return false;
        }

        if(pass != pass_agn) {
            EasyGrowl.notify(_('Password confirmation is not equal'));
            return false;
        }

        $('.recovery-change-button').css('display', 'none');
        $('.recovery-loader').css('display', 'block');

        $.ajax({
            type: 'POST',
            url: '/recovery/change/' + $('.password-recovery-form').find('input[name=recovery-password-code]').val(),
            data: $('form[name=password-recovery-form]').serialize(),
            success: function(data) {

                try {
                    eval("data = " + data);

                    if (data.success) {
                        $('.password-recovery-dialog').css('display', 'none');
                        $('.password-change-success').css('display', 'block');
                    } else {
                        if(data.message) {
                            EasyGrowl.notify(data.message);
                        } else {
                            EasyGrowl.notify(_('Please check password'));
                        }
                    }
                } catch (exception) {}

                $('.recovery-loader').css('display', 'none');
                $('.recovery-change-button').css('display', 'block');
            },
            error: function() {
                
                EasyGrowl.notify(_('Connection error'));

                $('.recovery-loader').css('display', 'none');
                $('.recovery-change-button').css('display', 'block');
            }
        });

        return false;
    });
});

