/*
 * GroupCollection - jQuery plugin 1.0.0
 *
 * Copyright (c) 2009 Squins
 */

;(function($) {
	$.fn.extend({
		inlineValidate: function() {
			return this.each(function() {
				new $.InlineValidator(this);
			});
		}
	});
	
	$.InlineValidator = function(element) {
		// Create the variables to work with
		var parent = $(element).parents("div.group")[0];
		var input = element;
		var isValidated = false;  
		
		// Check if the validator is already started
		$(input).bind("blur", function(event) {
			// Bind the validator to the change event when the field is blurred
			// for
			// the first time
			if (!isValidated) {
				$(input).bind("change", function(event) {
					validate();
					return false;
				});
				isValidated = true;
				validate();
			}			
		});
		$(input).bind("validate", function() {
			validate();
		});
		
		/**
		 * Validate the value of the input
		 */
		function validate() {
			// Fetch variables
			var sessionId = $("input[name='sessionId']", $(input).parents("form")[0])[0].value;
			var entityChildName = $("object.inlineValidation > param[name='entityDataChild']", $(input).parents("div")[0])[0].value;
			var fieldName = input.name;
			
			// Place Ajaxrequest
			$.ajax({
				url: "/text-request/",
				data: {
					action: "inlineValidation",
					sessionId: sessionId,
					entityChildName: entityChildName,
					value: input.value
				},
				success: function(message) {
					fieldError(message);
				}
			});
		}
		
		/**
		 * Create an error field
		 */
		function fieldError(message) {
			// Delete all errors
			$("div.error", $(input.parentNode)).remove();
			
			// If the message is set, the field should be in error mode
			if (message != "") {
				$(input.parentNode).prepend("<div class=\"error\">"+message+"</div>");
			}
		}
	}
})(jQuery);

/**
 * SQUINS Find all fields with the class inlineValidation and initialize them
 */
$(document).ready(function() {
	function addInlineValidation(context) {
		
		$("object.inlineValidation:not(.inlineValidation-enabled)", context.getElement()).each(function() {
			// Add the validator to the input/select field
			var inputs = this.parentNode.getElementsByTagName("input");
			var selects = this.parentNode.getElementsByTagName("select");
			
			if (inputs.length == 1) {
				// Inputs need to be verified
				var input = inputs[0];
				$(input).inlineValidate();
				
			} else if(selects.length == 1) {
				// Selects do not need to be verified
			} else {
				// No inputs, no selects, multiple inputs or multiple selects
				// detected, do nothing
			}
		});
	}
	PageRequest.addOnPageStructureChangeEvent(addInlineValidation);
});
