var validation;

/* Note that the months are zero based in JS while days and years aren't! Confusing. */

function createDateMDY(value) {
	if(/^\d\d\/\d\d\/[12]\d\d\d$/.test(value) && !/Invalid|NaN/.test(new Date(value.slice(3,5) - 1, value.slice(6,10), value.slice(0,2)))) {
		return new Date(value.slice(3,5) - 1, value.slice(6,10), value.slice(0,2));
	}
	else {
		return '';
	}
}

function createDateDMY(value) {
	if(/^\d\d\/\d\d\/[12]\d\d\d$/.test(value) && !/Invalid|NaN/.test(new Date(value.slice(6,10), value.slice(3,5) - 1, value.slice(0,2)))) {
		return new Date(value.slice(6,10), value.slice(3,5) - 1, value.slice(0,2));
	}
	else {
		return '';
	}
}

/* Handy function to evaluate multiple elements for validation
	(validation.element() only takes one at a time) */
function v_element(selector) {
	if(validation && validation.element) {
		$(selector).each(function() {
			validation.element(this);
		});
	};
}

if($) {

	$().ready(function() {

		/* Anti-multiple-submitting code */
		/* "form[action] is because we only want to add the protection to forms that have an action attribute specified */
		/* 		ie, not including simple forms that are just a select box with a JS redirect, etc. */
/*		$("form[action]").submit(function() {
		if (typeof $(this).attr("submitcount") != 'undefined' && $(this).attr("submitcount") > 0) {
				return false;
			}
			else {
				$(this).attr("submitcount", "1");
			};
		});
		$("form[action] *:input").change(function() {
			$(this.form).removeAttr("submitcount");
		}); */

		if($.validator) {

			$.validator.setDefaults({ 
				errorClass: "v_invalid",
				errorPlacement: function(error, element) {
					element.parents(".v_container").eq(0).append(error);
				}
			});

			/* By default, select boxes aren't validated until they've lost focus.
				We want them validated onchange. */
			$("form[action] select").change(function() {
				if(validation && validation.settings.rules[$(this).attr("name")]) {
					validation.element(this);
				};
			});
			/* Make sure all inputs are validated on blur (by default this only happens after the user has tried to
				submit the form for the first time). */
			$("form[action] *:input").blur(function() {
				if(validation && validation.settings.rules[$(this).attr("name")]) {
					validation.element(this);
				};
			});
			/* ...in the case of checkboxes, onclick */
			$("form[action] *:checkbox").click(function() {
				if(validation && validation.settings.rules[$(this).attr("name")]) {
					validation.element(this);
				};
			});

			/* Custom validation functions for jQuery validation plugin */
			$.validator.addMethod(
				"dateDMY",
				function(value) {
					return createDateDMY(value).toString().length;
				},
				"Please enter a date in the format dd/mm/yyyy."
			);
			$.validator.addMethod(
				"dateMDY",
				function(value) {
					return createDateMDY(value).toString().length;
				},
				"Please enter a date in the format mm/dd/yyyy."
			);
			$.validator.addMethod(
				"dateInFutureDMY",
				function(value) {
					var testDate = createDateDMY(value);
					return testDate.toString().length && testDate.getTime() >= new Date().getTime();
				},
				"Please enter a future date in the format dd/mm/yyyy."
			);
			$.validator.addMethod(
				"dateInFutureMDY",
				function(value) {
					var testDate = createDateMDY(value);
					return testDate.toString().length && testDate.getTime() >= new Date().getTime();
				},
				"Please enter a future date in the format mm/dd/yyyy."
			);
			$.validator.addMethod(
				"dateInPastDMY",
				function(value) {
					var testDate = createDateDMY(value);
					return testDate.toString().length && testDate.getTime() <= new Date().getTime();
				},
				"Please enter a past date in the format dd/mm/yyyy."
			);
			$.validator.addMethod(
				"dateInPastMDY",
				function(value) {
					var testDate = createDateMDY(value);
					return testDate.toString().length && testDate.getTime() <= new Date().getTime();
				},
				"Please enter a past date in the format mm/dd/yyyy."
			);
		};

		if($.fn && $.fn.media) {
			$.fn.media.defaults.flvPlayer = '/scripts/jquery/mediaplayer.swf';
			$.fn.media.defaults.mp3Player = '/scripts/jquery/mediaplayer.swf';
			$.fn.media.defaults.bgColor = 'transparent';
			$.fn.media.mapFormat('mp3','quicktime');
			$('.j_drawmedia').media();
		};

		/* Make lightbox click up in groups based on rel attribute. If rel is just "lightbox", that image pops up by itself.
			Otherwise, multiple rels like lightbox[groupname] will pop up as a group (ie you can go back and next between them). */
		$("a[rel=lightbox]").each(function(){$(this).lightBox()});
		var UsedRelGroups = new Array();
		/* Loop through each and collect rels of all rels with groups. */
		$("a[rel^=lightbox][rel!=lightbox]").each(function(){UsedRelGroups[$(this).attr("rel")] = 0;});
		for(key in UsedRelGroups) {
			/* Apply lightbox to each group. */
			$("a[rel='" + key + "']").lightBox();
		};
		
		$("#viewlargerimages").click(function() {
			$("a[rel*=lightbox]").eq(0).click();
			return false;
		});
		$("a[rel*=lightbox]").each(function() { // For every lightbox pic, find its caption and make the caption open the pic
			var ThisPicLink = this;
			$(this).next("span").children("a[rel*=lightcaption]").click(function() {
				$(ThisPicLink).click();
				return false;
			});
		});

		if($.fn.attachDatepicker) {
			/* Attach date selectors to input fields with the class "j_dateselect" */
			$("input.j_dateselect")
				.attachDatepicker({
					speed: '',
					dateFormat: 'dd/mm/yy',
					yearRange: (Number(new Date().getFullYear()) - 100) + ':' + (Number(new Date().getFullYear()) + 100),
					onSelect: function() {
						$(this).change().blur(); <!--- Important for triggering jquery form validation on change --->
					}
				})
				.attr("readonly", "readonly")
			;
		};

		// Trawl for images to preload
		$("img[onmouseover], area[onmouseover]").each(function() {
			var ThisURL = $(this).attr("onmouseover").toString().match(/\/[\/a-z0-9\-]+[^.'"]+\.(gif|jpe?g|png)/i)[0];
			if(ThisURL) $("#preload").append('<img src="' + ThisURL + '" width="1" height="1" alt="Preloaded image"/>');
		});

	});

};
