(function($) {

	// Nom du Plugin
	$.fn.niceValidateForm = function(method) {

		// Méthodes publiques
		//
		// Elles peuvent être appelées depuis l'extérieur par
		// element.zoomPhoto('methodName', arg1, arg2, ... argn)
		// où "element" est un objet du DOM auquel on attache la méthode
		//
		// ou, de l'intérieur par
		// methods.methodName(arg1, arg2, ... argn)
		var methods = {

			// Constructeur
			init: function(options) {

				// the plugin's final properties are the merged default and user-provided properties (if any)
				// this has the advantage of not polluting the defaults, making them re-usable
				this.niceValidateForm.settings = $.extend({}, this.niceValidateForm.defaults, options);

				// Boucle sur les éléments attachés au plugin
				return this.each( function() {
					var $element = $(this), // reference to the jQuery version of the current DOM element
					element = this;  // reference to the actual DOM element
                    
                    // Couleur du thème
                    var color = $.fn.niceValidateForm.settings.color;
                  	if($element.data('color'))
                  		color = $element.data('color');                  		
              		$element.find(':input, textarea').data('color', color);
              		$element.find('.link, .require').css('color', color);
              		$element.find(':submit').css('background-color', color);
                              
					var input_text = $(this).find(':text');
					input_text.each( function() {
						helpers.init_text($(this));
						helpers.clear($(this));
					});
					var input_password = $(this).find(':password');
					input_password.each( function() {
						helpers.init_text($(this));
						helpers.clear($(this));
					});
					var textarea = $(this).find('textarea');
					textarea.each( function() {
						helpers.init_textarea($(this));
						helpers.clear($(this));
					});
					var checkbox = $(this).find(':checkbox');
					checkbox.each( function() {
						helpers.init_checkbox($(this));
					});
					$(this).find(':submit').each( function() {
						helpers.init_submit($(this));
					});
					$(this).submit( function(event) {
						var ok   = true;
						var pass = true;
						$.merge(input_text, input_password);
						$.merge(input_text, textarea);
						input_text.each( function() {
							if($(this).data('require') == true) {			
								if(!$(this).val()) {
									helpers.alert($(this));
									ok = false;
								} else if($(this).data('validate')) {
									if($(this).data('validate') == 'email') {
										if(!helpers.validateString('email', $(this).val())) {
											helpers.alert($(this));
											ok = false;
										}
									} else if($(this).data('validate') == 'http')
										if(!helpers.validateString('http', $(this).val())) {
											helpers.alert($(this));
											ok = false;
										}
								}
							}
						});
						
						if(ok){
							var tmp = input_password.first().val();
							input_password.each(function(key){
								if(key != 0)
									if(tmp != $(this).val()){
										$($.fn.niceValidateForm.settings.container).append($('<div class="info info1">Les mots de passe ne correspondent pas.</div>'));
										$('.info').fadeIn(2000, function(){
									        $('.info').fadeOut(1000, function(){
									            $('.info').remove();
									        });
									    }).delay(4000);	
										ok = false;
									}										
							});
						}
												
						if(!ok)
							event.preventDefault();
					});
				});
			}
		}

		// Méthodes privées
		// Elles ne peuvent être appelées que depuis l'intérieur du Plugin par
		// helpers.methodName(arg1, arg2, ... argn)
		var helpers = {
			init_checkbox: function(elt) {
				var checkbox_image = null
				if(elt.data('checkbox'))
					checkbox_image = elt.data('checkbox');
				else if($.fn.niceValidateForm.settings.checkbox)
					checkbox_image = $.fn.niceValidateForm.settings.checkbox;		
				
				if(checkbox_image){
					var checked  = elt.attr('checked');
					var checkbox = $('<div style="margin: 0; display: block; float: left; position: relative; cursor: pointer; width: 22px; height: 22px; background: url(\'' + checkbox_image + '\') left ' + (checked == 'checked' ? 'bottom' : 'top') + ' no-repeat"></div>');
					checkbox.click( function() {
						if(elt.attr('checked')) {
							checkbox.css('background-position', 'left top');
							elt.attr('checked', false);
						} else {
							checkbox.css('background-position', 'left bottom');
							elt.attr('checked', 'checked');
						}
					});
					elt.after(checkbox);
					elt.css({
						'display': 'block',
						'position' : 'absolute',
						'visibility': 'hidden'
					});
				}
			},
			init_text: function(elt) {
				if($.fn.niceValidateForm.settings.input != null) {
					var td = elt.parent('td').first();
					var span = td.children('span');
					var width = 0;
					$.each(span, function(key, item){
						width += $(item).width();
					});					
					elt.css({
						'background': 'transparent url(\'' + $.fn.niceValidateForm.settings.input + '\') left bottom repeat-x',
						'border': 'none',
						'width': td.width() - width - 20
					});
				}
			},
			init_textarea: function(elt) {

			},
			init_submit: function(elt) {

			},
			clear: function(elt){
				if(elt.data('clear') == true)
					elt.val('');
			},
			alert: function(elt, type) {
				if(!$.fn.niceValidateForm.settings.input_over) {
					var border_color = elt.css('border-color');
					elt.css('border-color', elt.data('color'));
					elt.focus( function() {
						$(this).css('border-color', border_color);
					});
				}
				else {
					elt.css('background-image', 'url(' + $.fn.niceValidateForm.settings.input_over + ')');
					elt.focus( function() {
						$(this).css('background-image', 'url(' + $.fn.niceValidateForm.settings.input + ')');
					});
				}
				
				if(elt.data('text')){
					var color = elt.css('color');
					elt.css('color', elt.data('color'));
					elt.val(elt.data('text'));
					elt.focus( function() {
						if($(this).val() == elt.data('text')){
							$(this).css('color', color);
							$(this).val('');
						}						
					});
				}
			},
			validateString: function(type, string) {
				if (type == 'email') {
					var filter = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i
					if (filter.test(string)) {
						return true;
					} else {
						return false;
					}
				} else if (type == 'http') {
					var filter = /http:\/\/[A-Za-z0-9\.-]{3,}\.[A-Za-z]{2,3}/i
					if (filter.test(string)) {
						return true;
					} else {
						return false;
					}
				}
			}
		}

		// if a method as the given argument exists
		if (methods[method]) {
			// call the respective method
			return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
			// if an object is given as method OR nothing is given as argument
		} else if (typeof method === 'object' || !method) {
			// call the initialization method
			return methods.init.apply(this, arguments);
			// otherwise
		} else {
			// trigger an error
			$.error('Method "' + method + '" does not exist in niceValidateForm plugin!');
		}

	}
	// Options par défaut
	$.fn.niceValidateForm.defaults = {
		checkbox: null,
		input: null,
		input_over: null,
		container: 'body',
		color: 'red'
	}

	// this will hold the merged default and user-provided options
	// you will have access to these options like:
	// this.pluginName.settings.propertyName from inside the plugin or
	// element.pluginName.settings.propertyName from outside the plugin, where "element" is the element the
	// plugin is attached to;
	$.fn.niceValidateForm.settings = {}

})(jQuery);
