/*
Ajax validate signup form.

*/
(function($){
        $.fn.ajaxValidate = function(url){
                $(this).blur(function(){
                        var val = $(this).val();
                        var name = $(this).attr('rel');
                        //var diff = this.lastValue?Math.abs(this.value.length - this.lastValue.length):4;
                    if (val == this.lastValue || val == '')return false;
                        if (this.timer) clearTimeout(this.timer);
                        this.timer = setTimeout(function () {
                                $.ajax({
                              url: url,
                              data: 'field='+ name +'&value=' + val,
                              dataType: 'script',
                              type: 'post'
                             });
                         }, 10);
                        this.lastValue = this.value;
                        return $(this);
                });
        };
        // $.fn.checkInRange = function(min,max,valid,invalid){
        //              $(this).blur(function(){
        //                      Signup.checkInRange(this,min,max,valid,invalid);
        //                      
        //              }
        //      }
})(jQuery);

// This is REALLY badly designed. TO REFACTOR
var SignupOld = {
        valid: false,
        init:function(){
                // Ajax validate some fields
                $('input#email_field,input#permalink_field').ajaxValidate('/account/ajax_validate');
                // Check that passwrd is in range
                $('input#password_field').blur(function(){
                        Signup.checkInRange(this,4,10,
                                function(e){//valid
                                        Signup.validate('password','Valid password');
                                },
                                function(e){//invalid
                                        Signup.invalidate('password','Password must be between 4 and 10 characters long');
                                }
                        );              
                });
                $('#signup_form').submit(function(){
                        if(!document.getElementById('agree').checked){
                                alert('You must accept the Terms of Use');
                                return false;
                        }
                        $('#signup_form  button').attr('disabled', true) //don't allow user to click a second time
                        return true;
                });
        },
        validate:function(field,message){
                $('#'+field+'_field').removeClass('invalid');
                $('#'+field+'_validation')
                        .hide('fast').removeClass('invalid').addClass('valid').html(message);
                        
                Signup.valid = true;
        },
        invalidate:function(field,message){
                $('#'+field+'_field').addClass('invalid');
                $('#'+field+'_validation')
                        .show('fast')
                        .removeClass('valid')
                        .addClass('invalid')
                        .html(message);
                        
                Signup.valid = false;
        },
        checkInRange:function(selector,min,max,valid,invalid){
                var openid = $('input#openid_url').val();
                if (openid != ""){valid(selector);return true}
                $(selector).each(function(){
                        var val = $(this).val().length;
                        // run password validation
                        if(val < min || val > max){//out of range!
                                invalid($(this));                               
                        }
                        else{//passed
                                        valid($(this));
                        }       
                });
        }
};

/*
I need: 
1. apply ajax validations to fields based on html attrs. (rel, class)
2. reuse controller validation for entire form or singular input fields

- method that receives key/values and validates them
- can receive form.serialize() or individual fields
- validation method takes optional success callback
- ajax validation uses container form action url
*/
var Signup = function(form){
        this.form               = $(form);
        this.elements   = this.form.find('input.js_validate');
        this.action             = this.form.attr('action');
        this.valid              = false;
        this.all_errors = [];
        var self                = this;
        this.form.submit(function(){
                if(!document.getElementById('agree').checked){
                        alert('You must accept the Terms of Use');
                        return false;
                }
                if(self.valid)return true;
                if($('#password_field').val() == ''){
                        self.valid = false;
                        self.displayInvalid('password','Please provide a password');
                }
                self.validate();
                return false;
        });
        this.elements.blur(function(){
                var val = $(this).val();
            //if (val != '' && val == this.lastValue)return false;
                if (this.timer) clearTimeout(this.timer);
                var element = $(this);
                var data = element.serialize();
                if(m = element.attr('rel')){//confirmations, ugly way
                        data += '&'+$('#'+m).serialize();
                }
                this.timer = setTimeout(function () {
                        self.validate(data);
                 }, 10);
                this.lastValue = this.value;
        });
        this.validate = function(el){
                data = el || this.form.serialize();
                if(el){
                        var auth = $('input[name=authenticity_token]').val();
                        data += "&authenticity_token=" + auth;
                }
                $.ajax({
              url: this.action,
              data: data,
              dataType: 'json',
              type: 'post',
                  success: $.bind(this.success,this)
             });
        };

        this.success = function(r){
                var errors = r.errors;
                this.all_errors = r.all_errors;
                this.valid = r.valid;
                if(this.valid){
                        this.form.submit();
                        return true;
                }
                this.valid = false;
                this.validateAll();
                for(var i=0;i<errors.length;i++){
                        this.displayInvalid(errors[i][0],errors[i][1]);
                }
                //document.location.href = "#"+this.form.attr('id');
        };
        this.displayInvalid = function(field,message){
                $('#'+field+'_field').addClass('invalid');
                $('#'+field+'_validation')
                        .show('fast')
                        .removeClass('valid')
                        .addClass('invalid')
                        .html(message);
        };
        this.validateAll = function(){// validate fields with no errors
                var error_free = [];
                var self = this;
                this.elements.each(function(){
                        var found = 0;
                        for(var i=0;i<self.all_errors.length;i++){
                                
                                if($(this).attr('name').indexOf(self.all_errors[i][0]) > -1)
                                        found++;
                        }
                        if(found < 1) error_free.push($(this));
                });
                jQuery.each(error_free,function(){
                        var name = $(this).attr('name').match(/[^ ]\[(.+)\]/);
                        var field = name[1];
                        $(this).removeClass('invalid');
                        
                        $('#'+field+'_validation')
                                .hide('fast').removeClass('invalid').addClass('valid').html('');
                });
        }
};
Signup.init = function(){
        var signup = new Signup('form#signup_form');
};


