/**
 * @author F.biz - http://www.fbiz.com.br/
 */
 if(!window['unilever'])
	var unilever = {};
 
 // forms default
 (function($){
	
	if(!$ || !$.validator){
		return;
	}
	
	var _defaultErrorTag = 'span';
	var _defaultErrorMessage = 'Os dados não foram preenchidos corretamente.';
	
    // default validator stuff
	$.validator.messages.minlength = "";
	$.validator.messages.required = "";
	$.validator.messages.number = "";
    $.validator.messages.equalTo = "";
    $.validator.messages.email = "";
    $.validator.messages.CPF = "";    
    $.validator.addMethod("CPF", function(v, element, params) {
        if (v == "00000000000" || v == "11111111111" || v == "22222222222" || v == "33333333333" || v == "44444444444" || v == "55555555555" || v == "66666666666" || v == "77777777777" || v == "88888888888" || v == "99999999999") return false;
        if (!v) return true;
        var s = null;
        var r = null;
        if (v.length != 11 || v.match(/1{11};|2{11};|3{11};|4{11};|5{11};|6{11};|7{11};|8{11};|9{11};|0{11};/)) return false;
        s = 0;
        for (var i = 0; i < 9; i++) s += parseInt(v.charAt(i)) * (10 - i);
        r = 11 - (s % 11);
        if (r == 10 || r == 11) r = 0;
        if (r != parseInt(v.charAt(9))) return false;
        s = 0;
        for (var i = 0; i < 10; i++) s += parseInt(v.charAt(i)) * (11 - i);
        r = 11 - (s % 11);
        if (r == 10 || r == 11) r = 0;
        if (r != parseInt(v.charAt(10))) return false;
        return true;
    });
	
	var _instances = []; // {form: {jQuery}, scopes: [{unilever.Validation}]}
	var _getByForm = function(form){
		var currScopes;
		for(var i = 0; _instances[i]; i++){
			if(_instances[i].form[0] == form[0]){
				return _instances[i];
			}
		}
		return null;
	};
	var _getByInstance = function(form, scope){
		var currScopes;
		var currInstance = _getByForm(form);
		if(currInstance != null){
			currScopes = currInstance.scopes;
			for(var j=0; currScopes[j]; j++){
				if(currScopes[j] == scope){
					return currInstance;
				}
			}
		}
		return null;
	};
	var _addInstance = function(form, scope){
		var currInstance = _getByForm(form);
		var index = _instances.length;
		if(!currInstance){
			_instances[index] = {
				form: form,
				scopes: []
			};
			_instances[index].scopes.push(scope);
		}else{
			if(!_getByInstance(form, scope)){
				currInstance.scopes.push(scope);
			}
		}
	};
	var _resetValidationStatus = function(scope){
		var formGroup = _getByForm(scope.form) || {};
		var scopes = formGroup.scopes || [];
		for(var i = 0; scopes[i]; i++){
			if(scopes[i] != scope){
				scopes[i].currentValidation = false;
			}
		}
	};
	var _getCurrentInstance = function(form){
		var formGroup = _getByForm(form) || {};
		var scopes = formGroup.scopes || [];
		for(var i = 0; scopes[i]; i++){
			if(scopes[i].currentValidation === true){
				return scopes[i];
			}
		}
		return null;
	};
	
	
	var _applyFormValidation = function(scope){
		scope.form.validate({
			errorElement: scope.options.errorElement,
			errorPlacement: function(error, element) {}, 
			submitHandler: scope.options.submitHandler,
			invalidHandler: function(e, validator) {
				var currInstance = _getCurrentInstance(scope.form);
				if(currInstance)
					currInstance.invalidHandler(e, validator);
				return false;
			},
			errorPlacement: function(error, element) {
				error.appendTo( element.next('span'));
			}
		}); 
	};
	
	
	/**
	 * defaults project validation
	 * @param {jQuery} form
	 * @param {jQuery} feedback message holder
	 * @param {jQuery} sendButton form button for on click submit
	 * @param {Object} rules $.validator rules format {nome: {Object}...}
	 * @param {Object} options {errorElement: {String}, message: {String}}
	 * @see {jQuery}, {jQuery.validator}
	 * @needs {jQuery}, {jQuery.validator}
	 */
	unilever.Validation = function(form, feedback, sendButton, rules, options){
		
		_addInstance(form, this);
		
		var _this = this;
		
		if(!feedback || !form){
			throw new Error('[unilever.Validation] feedback and form are needed.');
		}
		
		this.form = form;
		this.feedback = feedback;
		this.sendButton = sendButton;
		this.rules = rules || {};
		this.options = options || {};
		this.currentValidation = false;
		this.invalidHandler = function(e, validator){
			if (validator.numberOfInvalids()) {
				_this.feedback.html(_this.options.message);
			} else {
				_this.feedback.html('&nbsp;');
			}
		}
		this.options.errorElement = this.options.errorElement || _defaultErrorTag;
		this.options.message = this.options.message || _defaultErrorMessage;
		
		var _avoidSubmitHandler = function(){
			_this.form.unbind('submit', _avoidSubmitHandler);
			return false;
		};
		var _removeFormRules = function(){
			$('input, select, textarea', _this.form).each(function(){
				$(this).rules('remove');
			});
		};
		var _addRules = function(){
			_resetValidationStatus(_this);
			for(var name in _this.rules){
				$('*[name='+name+']').rules('add', _this.rules[name]);
			}
		};
		var _applyValidations = function(){
			if(_this.currentValidation === false){
				_this.currentValidation = true;
				_this.form.bind('submit', _avoidSubmitHandler);
				_removeFormRules();
				_addRules();
			}
		}
		var _onKeyPress = function(e){
			if(e.keyCode == 13){
				_applyValidations();
				_this.form.submit();
				return false;
			}
		};
		
		// init
		if(!_this.form.data('validator')){
			_applyFormValidation(this);
		}
		for(var name in this.rules){
			$('*[name='+name+']')
				.bind('keypress', _onKeyPress);
		}
		this.sendButton.bind('click', _applyValidations);
	};
	
 })(jQuery)
