/*
*
* jmValidation.js
*
* Author: Moreno Di Domenico
* www.moretech.it
* info@moretech.ti
*
*/

(function ( $, window, document, undefined ) {

    var pluginName = 'jmValidation',
        defaults = {
			'type' 		: 'normal',
			'service' 	: null,
			'dataType'	: 'json',
			'myfunction' : false
		};


    function Plugin( element, options ) {
		$this = this;
        $this.element = element;
		$form = $($this.element);

        $this.options = $.extend( {}, defaults, options) ;

        $this._defaults = defaults;
        $this._name = pluginName;
		
        $this.init();
    }
	
	
    Plugin.prototype.init = function () {
		$form.find('.submitter').live('click', function(){
			
			$errors = false;
			$this.emptyErrors();
			$this.checkFields();

			if(!$errors)
			$this.formSubmit();
			
			else
			$('.msg_error').html('ATTENZIONE! COMPILA CORRETTAMENTE I CAMPI');
			
			return false;
		});
	};	
	
	
	Plugin.prototype.checkFields = function(){
		$form.find('input, textarea, select').each(function(i, e){
			$this.checkRules(e);
		});
	}
	
	Plugin.prototype.checkRules = function(e){
		$obj = $(e);
		$rules = $obj.attr('data-rules');
		$value = $obj.val();
		
		if($rules)
		{
			$rule = $rules.split('|');
			
			for($r in $rule){
				$rclean = $this.cleanRule($rule[$r]);
				switch ($rclean){
					case 'required':
						$this.required();
					break;

					case 'minlength':
						$minlength = $this.ruleDetail($rule[$r]);
						$this.minlength();
					break;
					
					case 'maxlength':
						$maxlength = $this.ruleDetail($rule[$r]);
						$this.maxlength();
					break;
					
					case 'alphanumeric':
						$this.alphanumeric();
					break;
					
					case 'alphabetic':
						$this.alphabetic();
					break;
					
					case 'numeric':
						$this.numeric();
					break;
					
					case 'email':
						$this.email();
					break;
					
					case 'validbirth':
						$this.validbirth();
					break;
					
					case 'checked':
						$this.checked();
					break;
					
				}
			}
		}
		
	}
	
	Plugin.prototype.cleanRule = function(r){
		return r.replace(/ *\([^)]*\) */g, "");
	}
	
	Plugin.prototype.ruleDetail = function(r){
		var regex = new RegExp('\\((.*?)\\)', 'g');
		r = regex.exec(r)
		return (r[1]);
	}
	
	Plugin.prototype.emptyErrors = function()
	{
		$('div.field').find('.tip').empty();
		$('div.field').removeClass('error');
		$('.msg_error').empty();
	}

	Plugin.prototype.addError = function(msg)
	{
		/*$obj.parent('div.field').addClass('error');
		if(msg)
		$obj.parent('div.field').find('.tip').append(msg+' <br />');
		
		$errors = true;*/
		$obj.parent('div.field').addClass('error');
		$('#register_response').html('<span class="error">Attenzione! Tutti i campi sono obbligatori.</span>');
		$errors = true;
	}
	
	Plugin.prototype.yearleap = function(year)
	{
		return (year % 400 == 0 || (year % 100 != 0 && year % 4 == 0));	
	}


	Plugin.prototype.formSubmit = function()
	{
		$('.msg_error').html('REGISTRAZIONE IN CORSO... ATTENDI');
		$('.msg_error').addClass('loading');


		if ( $this.options.type == 'ajax')
		{
			$values = $form.serialize();
			/*var v = $form.serializeArray() ;
			var obj = {} ;
			for(i in v ) {
				obj[v[i].name] = v[i].value ;
			}
			*/
			$method = $form.attr('method');
			$.ajax({
				url			: $this.options.service,
				type 		: $method,
				dataType 	: $this.options.dataType,
				data		: $values,
				success		: function(response)
				{
					$this.options.myfunction(response);
				}
			});
		}
		
		else
		{
			$form.submit();
		}
		
	}


	/* 
	* RULES
	*/
	
	/* required */
	Plugin.prototype.required = function(){
		if($.trim($value) == '')
		$this.addError('Campo Obbligatorio');
		return false;
	}

	/* minlength */
	Plugin.prototype.minlength = function(){
		if($value.length < $minlength)
		$this.addError('Minimo '+$minlength+' caratteri');
	}
	
	/* maxlength */
	Plugin.prototype.maxlength = function(){
		if($value.length > $maxlength)
		$this.addError('Massimo '+$maxlength+' caratteri');
	}
	
	/* alphanumeric */
	Plugin.prototype.alphanumeric = function(r){
		var regex = /^([a-zA-Z0-9 àèìòù//.-]+)$/;
		if(!regex.test($value))
		$this.addError('Consentiti solo caratteri alfanumerici . / e -');
	}

	/* alphabetic */
	Plugin.prototype.alphabetic = function(r){
		var regex = /^([a-zA-Z àèìòù]+)$/;
		if(!regex.test($value))
		$this.addError('Consentiti solo caratteri dell\'alfabeto');
	}

	/* numeric */
	Plugin.prototype.numeric = function(r){
		var regex = /^([0-9]+)$/;
		if(!regex.test($value))
		$this.addError('Consentiti solo numeri');
	}

	/* email */
	Plugin.prototype.email = function(r){
		var regex = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
		if(!regex.test($value))
		$this.addError('Inserire una email valida.');
	}

	/* validbirth */
	Plugin.prototype.validbirth = function(){
		$day = $form.find('select[name="PlayerProfile[day]"]').val();
		$month = $form.find('select[name="PlayerProfile[month]"]').val();
		$year = $form.find('select[name="PlayerProfile[year]"]').val();
		
		$x = 'ok';
		
		var currentDate = new Date()
		$now_day = currentDate.getDate();
		$now_month = currentDate.getMonth()+1;
		$now_year = currentDate.getFullYear();
		
		if($day == '' || $month == '' || $year == '')
		{
		$this.addError('Inserire una data valida.');
		$x = 'bo1';
		}
		
		if($year == $now_year)
		{
			if($month > $now_month)
			$this.addError('Inserire una data valida.');
			
			else if($month == $now_month && $day > $now_day)
			$this.addError('Inserire una data valida.');

		$x = 'bo2';
		}

		if($month == 2)
		{
			if($day > 29){
			$this.addError('Inserire una data valida.');
			$x = 'bo3';
			}
			else if(!$this.yearleap($year) && $day==29){
			$this.addError('Inserire una data valida.');
			$x = 'bo3a';
			}
		}
		
		if($month == 4 && $day > 30 || $month == 6 && $day > 30 || $month == 9 && $day > 30 || $month == 11 && $day > 30)
		{
			$this.addError('Inserire una data valida.');
			$x = 'bo4';
		}
	}
	
	/* checked */
	Plugin.prototype.checked = function(){
		if(!$obj.is(':checked'))
		$this.addError('Campo obbligatorio.');
	}

	
    $.fn[pluginName] = function ( options ) {
        return this.each(function () {
            if (!$.data(this, 'plugin_' + pluginName)) {
                $.data(this, 'plugin_' + pluginName,
                new Plugin( this, options ));
            }
        });
    }
  
  
  
})(jQuery);
