(function($) {
	$.fn.SymphonyInlineValidation = function(o) {
		o = $.extend({

			validate: ".label:contains('*') + input:not(:hidden),.label:contains('*') + textarea:not(:hidden) ",
			canofspam: false,
			url: null,
			action: null,
			update: false

		}, o || {});

		return this.each(function() {
			if(o.url == null) return false;

			var self = $(this);

			/*	Only validate fields that are required, using the form builder is defined as the label containing a * */
			var fields = $('input, textarea', self).filter(o.validate);

			/*	Show message only after user has passed over the field and stuffed up */
			fields.live('blur', function() {
				
				var field = $(this);

				/*	Just send this field, otherwise if all the fields are correct an entry would
				**	be made in Symphony */
				var post = field.serializeArray();

				/*	Without canofspam, the request fails without any detailed field information. */
				if(o.canofspam) {
					var can = [{name: "canofspam", value: $('input[name=canofspam]').val()}];

					post = jQuery.merge(post,can);
				}

				/*	Without the submit action, the validation page doesn't know what event to process */
				if(o.action == null) {
					var action = [
							{name: self.find('[name^=action]').attr("name")}
						];
				} else {
					var action = [
							{name: o.action}
						];
				}

				var send = jQuery.merge(post,action);

				$.post(o.url, send,
					function(data) {
						doInlineValidation(data)
					}, "xml"
				);

				function doInlineValidation(data) {

					/*	Needs fields[{name}] syntax for Symphony, but for the validation, we just want the
					**	{name}, so replace the fields[ and slice off the end ]
					**	2009-10-15 Now supports sub-handle*/
					var name = field.attr('name').replace(/(fields\[|.*\]\[|\]$)/gi,"");

					var invalid = $(data).find(name + "[message]");

					var target = field.parent().next('.information');

					/*	If there's a message for this field, it will always be bad,
					**	show it to the user */
					if(invalid.length == 1 ) {

						/*	Allows you to alias form fields are the field's label */
						var label = $('label',field.parent()).text();

						/*	Again, my RegExp fu is low, this could be better */
						var reg = new RegExp(name, "i");
						var msg = invalid.attr("message").replace(reg, label).replace(/(\*|a\s|\sfield| Please check the contents.)/g,"");
						
//						
						//Hack for existing artists (Show an extra paragraph of information)
//						if (msg.indexOf("Band/Stage Name") != -1) {
//
//							$("#general .exists-msg").fadeIn('slow');
//
//						}
	
						// Hack for Artist Register page as Rob wants user friendly message here for urls.
						if (msg.indexOf("contains invalid data.") != -1 && field.closest('.urls').is('#online-media')) {
						
							msg = "'" + label + "'" + " requires a valid URL.";
						}

						if(o.update) {
							if(ignoreEmail()) {
								showError(msg)
							}
						} else {
							showError(msg)
						}

					} else if($('input[type=password]',self).get(1) == field.get(0)) {

						var prevPass = $('input[type=password]',self).eq(0);

						if(field.val() != prevPass.val() && prevPass.val() != "") {
							showError("Your passwords don't match");
						} else {
							hideError();
						}

					} else {
						hideError();
					}
					

					function showError(msg) {
						if(target.find('.error').length == 0) {
							target.append("<div class='error'><p>" + msg + "</p></div>").fadeIn("fast");
						} else if(target.find('.error').text() != msg) {
							target.find('.error').html("<p>" + msg + "</p>").fadeIn("fast");
						}
						_gaq.push(['_trackEvent', field.closest('form').attr('id'), 'Validation Error: Inline', msg]);
					}

					function hideError() {
						target.find('.error').fadeOut("fast", function() {
							$(this).empty();
						});
					}

					/*	Annoying, if a user is already created, we don't want them getting an
					**	error message for their email is already in use (because it'll be them).
					**	So this function will return bool on if that is the case. If they change
					**	their email and it doesn't equal the :hidden email, then it's valid and
					**	display the error */
					function ignoreEmail() {
						if(name == "email" && msg.indexOf("is already in") != -1) {
							if(field.val() != $('input[name=email][type=hidden]').val()) {
								//console.log('different emails: show error');
								return true;
							} else {
								//console.log('same email: hide error');
								hideError();
								return false;
							}
						} else {
							//console.log("doesn't contain duplicate: show error");
							return true;
						}
					}
				}

			});
		});
	};
})(jQuery);


$(document).ready(function() {
	var root = $('#page-header h1 a').attr('href');

	$('#contact-form, #membership-form, #update').SymphonyInlineValidation({
		canofspam: true,
		url: root + "/special/validation/",
		validate: "label:contains('*') + input:not(:hidden),label:contains('*') + textarea:not(:hidden) "
	});

	
	/*	Register */
	$('#register-form').SymphonyInlineValidation({
		canofspam: true,
		url: root + "/special/validation/",
		validate: "label:contains('*') + input.not(:hidden),label:contains('*') + textarea:not(:hidden) "
	});


	/*	Checkout */
	$('#checkout-customer, #membership').SymphonyInlineValidation({
		canofspam: true,
		url: root + "/special/validation/",
		validate: "label:contains('*') + input:not(:hidden),label:contains('*') + textarea:not(:hidden) ",
		action: "action[make-member]",
		update: true
	});

	$('#payment').SymphonyInlineValidation({
		canofspam: true,
		url: root + "/special/validation/",
		validate: "label:contains('*') + input:not(:hidden),label:contains('*') + textarea:not(:hidden) ",
		action: "action[validation-checkout]"
	});
	
	
	/* Patch for Artist register page - Fields aren't required in Symhpony so need to manually check these.*/
	
	(function(){	
				
		$("#register-form label:contains('*') + input").each(function() {
		
			$(this).blur(function() {
			
				var field = $(this);
				var value = field.val();

				var target = $(this).parent().next('.information');
			
				if((field.val() == "") && (field.closest('.toggled').css('display') != 'none')) {
					var msg = "'" + field.parent().find('label span').text() + "'" + " is required."
					showManualError(target , msg);
				} else {
					hideManualError(target);
				}
			
			});
		
		});
		
		
		$('#register-form').submit(function() {
		
				var error_count = 0;
				
				$("#register-form label:contains('*') + input").each(function() {

						var field = $(this);
						var target = $(this).parent().next('.information');
	
					
						if((field.val() == "") && (field.closest('.toggled').css('display') != 'none')) {
							var msg = "'" + field.parent().find('label span').text() + "'" + " is required."
							showManualError(target , msg);
							
							error_count ++;
						} 
				});
				
				if(error_count > 0) {
					return false;
				}
		
		});
		
		
		function showManualError(target, msg) {
			if(target.find('.manual-error').length == 0) {
				target.append("<div class='manual-error'><p>" + msg + "</p></div>").fadeIn("fast");
			} else if(target.find('.manual-error').text() != msg) {
				target.find('.manual-error').html("<p>" + msg + "</p>").fadeIn("fast");
			}
		}
		
		function hideManualError(target) {
			target.find('.manual-error').fadeOut("fast", function() {
				$(this).empty();
			});
		}	
		
	})();
	
	
});

