$(document).ready(function(){

    $(":image, :checkbox, :radio").css({
        'border':'none'
    });

    $(":submit, :button").css({
        'cursor':'pointer'
    });

    $(":text, :password").css({
        'background-color':'#FFFFFF'
    });

    /**
     *
     */
    $.fn.errorPromt = function (removeAlso) {
        var from_left = ($(document).width() / 2) - ($('#errorPromt').width()/2);

        $('#errorPromt').css({
            'left': from_left
        }).fadeIn('slow',function(){

            });

    }


    /**
     *
     */
    $.fn.messagePromt = function (removeAlso) {
        var from_left = ($(document).width() / 2) - ($('#messagePromt').width()/2);

        $('#messagePromt').css({
            'left': from_left
        }).fadeIn('slow',function(){

            });

        setTimeout(function(){
            $('#messagePromt').fadeOut('slow');
            
            if(removeAlso){

                $('#' + removeAlso.name + '_error').fadeOut('slow',function(){
                    $(this).remove();
                });

            }
   
            
        },5000);


        $('#messagePromt').click(function(){
            $('#messagePromt').hide('slow');
        })

    }


    /**
     *
     */
    $.fn.removeErrorMsg = function (){
        if ($(this).next(".alertText,.alertTextSmall").size() == 1) {
            $(this).next(".alertText,.alertTextSmall").remove();
        }
    }

    /**
     *
     */
    $.extend({
        stop: function(e){
            if (!e) e = window.event;
            if (e.preventDefault) e.preventDefault();
            if (e.stopPropagation) e.stopPropagation();
        }
    }); 

    /**
     *
     */
    $.fn.addErrorMsg = function (relative, msg){
        
        $(relative).after('<div id="' + relative.name + '_error" class="alertTextSmall">' + msg + '</div>');
            
        $(relative).effect("pulsate", {
            times:2,
            mode:'show'
        }, 750);

    }


    /**
     *
     */
    $.fn.validatorInit = function() {
        
        this.each(function (){
        
            var form = this;

            $(form).submit(function(e){
                
                $('.field_required,.field_email,.field_number,.field_integer,.field_alphaNumeric,.field_password,.field_confirmPassword,.field_dateTime,.validateUsernameAvailability,.validateUserEmailAvailability,.field_Username,.field_phone', form).each(function(){
                    $(this).blur();
                });
                if($('.input-error', form).size() > 0){
                    $.stop(e);
                    return false;
                }
                return true;
            }
    
            );


            $('.field_required,.field_email,.field_number,.field_integer,.field_alphaNumeric,.field_password,.field_confirmPassword,.field_dateTime,.validateUsernameAvailability,.validateUserEmailAvailability,.field_Username,.field_phone', form).blur(function(){
                $(this).removeClass('input-error');
                $(this).removeErrorMsg()

            });

            $('.field_required').bind('blur', function(e){
                if ($(this).val() == '') {
                    $(this).addClass('input-error');
                    $(this).addErrorMsg(this, $(this).attr('errorMsg'));
                    $.stop(e);
                    return false;
                }
            });

            $('.field_confirmPassword').bind('blur', function(e){
                
                if ($('#password').val() != $(this).val()){
                    $(this).addClass('input-error');
                    $(this).addErrorMsg(this, $(this).attr('errorMsg'));
                    $.stop(e);
                    return false;
                }
            });

            $('.field_email', form).bind('blur', function(e){
                if ($(this).val() != '') {
                    if (!/^[A-Za-z][A-Za-z0-9_.-]*@[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+[.A-za-z]+$/.test($(this).val())) {
                        $(this).addClass('input-error');
                        $(this).addErrorMsg(this, $(this).attr('errorMsg'));
                        $.stop(e);
                        return false;
                    }
                }
            });

            $('.field_password',form).bind('blur',function(e){
                if ($(this).val() != '') {
                    if (!/^.*(?=.{8,})(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z]).*$/.test($(this).val())) {
                        $(this).addClass('input-error');
                        $(this).addErrorMsg(this, $(this).attr('errorMsg'));
                        $.stop(e);
                        return false;
                    }
                }
            });

            $('.field_alphaNumeric').bind('blur',function(e){
                if ($(this).val() != '') {
                    if (!/^[A-Za-z0-9\s-\.]*$/.test($(this).val())) {
                        $(this).addClass('input-error');
                        $(this).addErrorMsg(this, $(this).attr('errorMsg'));
                        $.stop(e);
                        return false;
                    }
                }

            });

            $('.field_Username').bind('blur',function(e){
                if ($(this).val() != '') {
                    if (!/^[A-Za-z0-9_-]*$/.test($(this).val())) {
                        $(this).addClass('input-error');
                        $(this).addErrorMsg(this, $(this).attr('errorMsg2'));
                        $.stop(e);
                        return false;
                    }
                }

            });

            $('.field_phone', form).bind('blur', function(e){
                if ($(this).val() != '') {
                    if (!/^\+?([0-9]+\.?\-?\/?[0-9]*)+$/.test($(this).val())) {
                        $(this).addClass('input-error');
                        $(this).addErrorMsg(this, $(this).attr('errorMsg'));
                        $.stop(e);
                        return false;
                    }
                }
            });

            $('.field_number', form).bind('blur', function(e){
                if ($(this).val() != '') {
                    if (!/^[0-9]+\.?[0-9]*$/.test($(this).val())) {
                        $(this).addClass('input-error');
                        $(this).addErrorMsg(this, $(this).attr('errorMsg'));
                        $.stop(e);
                        return false;
                    }
                }
            });

            $('.field_integer', form).bind('blur', function(e){
                if ($(this).val() != '') {
                    if (!/^[0-9]+$/.test($(this).val())) {
                        $(this).addClass('input-error');
                        $(this).addErrorMsg(this, $(this).attr('errorMsg'));
                        $.stop(e);
                        return false;
                    }
                }
            });


            $('.field_dateTime', form).bind('blur', function(e){
                if ($(this).val() != '') {
                    if (!/^\d{2}\-\d{1,2}\-\d{1,4}\s\d{1,2}\:\d{1,2}\:\d{1,2}$/.test($(this).val())) {
                        $(this).addClass('input-error');
                        $(this).addErrorMsg(this, $(this).attr('errorMsg'));
                        $.stop(e);
                        return false;
                    }
                }
            });

            $('.validateUsernameAvailability', form).bind('blur', function(e){
                
                if ($(this).val() != '') {
                    var currentField = this;
                    $(currentField).css({
                        'background-image':'url(/images/layout_images/loading.gif)',
                        'background-repeat':'no-repeat',
                        'background-position':'center right'
                    });

                    var results = $.ajax({
                        url: "/available_username_email.php",
                        type :'POST',
                        data:({
                            check : 'userUnameAvailable',
                            userUsername : $(this).val(),
                            relId : $('#relId').val(),
                            relGroup : $('#relGroup').val()
                        }),
                        async: false
                    }).responseText;

                    

                    $(currentField).css({
                        'background-image':'none'
                    });

                    if (results == 'stop'){

                        $(currentField).addClass('input-error');
                        $(currentField).addErrorMsg(currentField, 'Nombre Usuario no disponible');
                        $.stop(e);

                        return false;
                    }
                }
            });

            $('.validateUserEmailAvailability', form).bind('blur', function(e){

                if ($(this).val() != '') {

                    var currentField = this;
                    $(currentField).css({
                        'background-image':'url(/images/layout_images/loading.gif)',
                        'background-repeat':'no-repeat',
                        'background-position':'center right'
                    });
                    
                    var results = $.ajax({
                        url: "/available_username_email.php",
                        type :'POST',
                        data:({
                            check : 'userEmailAvailable',
                            userEmail : $(this).val(),
                            relId : $('#relId').val(),
                            relGroup : $('#relGroup').val()
                        }),
                        async: false
                    }).responseText;

                    
                    $(currentField).css({
                        'background-image':'none'
                    });

                    if (results == 'stop'){

                        $(currentField).addClass('input-error');
                        $(currentField).addErrorMsg(currentField, 'El e-mail seleccionado existe ya en la base de datos');
                        $.stop(e);

                        return false;
                    }
                    
                }

            });

        })
    };




    $(function() {

        $('.datepicker').datetime({
            userLang	: 'es',
            americanMode: false
        });

    });


    $('ul .submenu').hover(
      function () {
        $(this).siblings('.menu').addClass('menuActive');
      },
      function () {
        $(this).siblings('.menuActive').removeClass('menuActive');
      }
    );



    $('a[rev=spinner]').click(function(e){
       // $('#tabSpinner').show();
    });


    $('#errorPromtClose').click(function(e){

        e.preventDefault();


            $('#errorPromt').fadeOut('slow');

            

                $('#errorPromtText').fadeOut('slow',function(){
                    $('#errorPromtText').html('');
                });

            


    });

});

