(function($) {
	/*
	 * Form Validator 1.4.0 - jQuery plugin
	 *	written by Nico De Backer
	 *
	 *	Copyright (c) 2009-2010 Nico De Backer (http://iamwebdeveloper.com)
	 *	Dual licensed under the MIT and GPL licenses:
	 *	http://www.opensource.org/licenses/mit-license.php
	 *	http://www.gnu.org/licenses/gpl.html
	 *
	 *	Built for jQuery library (1.4 and higher)
	 *	http://jquery.com
	 *
	 *	Performs basic form validation (required, email, numeric)
	 *
	 *	@name		formvalidate
	 *	@param		messages.email			Error message when email is not valid									'This is an invalid email address'
	 *	@param		messages.numeric		Error message when field is not numeric								'This is not a valid number'
	 *	@param		messages.required		Error message when required field is empty							'This is a required field'
	 *	@param		messages.summary		Error message summary (use {0} to display number of errors)		'Please correct the errors with the following {0} fields:'
	 *	@param		requiredFlag				Token to indicate required field											'*'
	 *	@example	$('form').formvalidate();
	 */
	$.fn.formvalidate = function(options) {
		var settings = $.extend(true, $.fn.formvalidate.defaults, options);

		function handleRequiredLabel($aForm) {
			var requiredKey = $('.required:first', $aForm).prev('label').find('span').text(),
					fieldKeys,
					$instructions = $('<p/>');

			requiredKey = requiredKey.replace(/^\((.+)\)$/,"$1");
			fieldKeys = settings.requiredFlag + ' ' + requiredKey;

			$(':input', $aForm)
				.filter('.required').prev('label').find('span').text(settings.requiredFlag).attr('title', requiredKey).end().end()
				.prev('label').addClass('req-label');
			$instructions.addClass('field-keys').append(fieldKeys);
			$aForm.before($instructions);
		}

		function createInlineErrorMessage($aPlace, aText) {
			$('<span/>', {
				className:'error-message',
				text:aText
			}).appendTo($aPlace);  

			$aPlace.addClass('warning');
		}

		String.format = function() {
		  var s = arguments[0];

		  for (var i = 0; i < arguments.length - 1; i++) {       
		    var reg = new RegExp('\\{' + i + '\\}', 'gm');             
		    s = s.replace(reg, arguments[i + 1]);
		  }

		  return s;
		};

		return this.each(function() {
			var $me = $(this);

			handleRequiredLabel($me);

			$(':input', $me).blur(function() {
				var field = this,
						$collection = $(field).parent(),
						val = $.trim(field.value);

				$collection.removeClass('warning').find('span.error-message').remove();

				if ($(field).is('.required')) {
					if (val == '') {
						createInlineErrorMessage($collection, settings.messages.required);
					}
				}

				if ($(field).is('.email')) {
					if (val != '') {
						var reg = new  RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);

						if (reg.test(val) === false) {
							createInlineErrorMessage($collection, settings.messages.email);
						}
					}
				}

				if ($(field).is('.numeric')) {
					if (isNaN(val)) {
						createInlineErrorMessage($collection, settings.messages.numeric);
					}
				}
			});

			$me.submit(function() {
				$('.submit-message', $me).remove();
				$(':input.required').trigger('blur');

				var numWarnings = $('.warning', $me).length,
						errFields = [];

				if (numWarnings > 0) {
					$('.warning label', $me).each(function(){
						var txt = $(this).text();
						errFields.push('<li>' + txt + '</li>');
					});

					var $message = $('<div/>', {className:'submit-message warning', text:String.format(settings.messages.summary, numWarnings)}),
							$lst = $('<ul/>').append(errFields.join(''));
					$message.append($lst);
					$me.prepend($message);

					return false;
				}
			});
		});
	};

	$.fn.formvalidate.defaults = {
		messages: {
			email:'This is an invalid email address',
			numeric:'This is not a valid number',
			required:'This is a required field',
			summary:'Please correct the errors with the following {0} fields:'
		},
		requiredFlag:'*'
	};
})(jQuery);

(function($) {
	/*
	 *	Ttip 1.4.0 - jQuery plugin
	 *	written by Nico De Backer
	 *
	 *	Copyright (c) 2009-2010 Nico De Backer (http://iamwebdeveloper.com)
	 *	Dual licensed under the MIT and GPL licenses:
	 *	http://www.opensource.org/licenses/mit-license.php
	 *	http://www.gnu.org/licenses/gpl.html
	 *
	 *	Built for jQuery library (1.4 and higher)
	 *	http://jquery.com
	 *
	 *	Generates a CSS-customizable tooltip based on the element’s title-attribute
	 *
	 *	@name		ttip
	 *	@param	location		positioning of tooltip in regards to element ('n':above; 'e':right; 's':left; 'w':left)		'n'
	 *	@example	$('.ttipped').ttip();
	 */
	$.fn.ttip = function(options) {
		var settings = $.extend({}, $.fn.ttip.defaults, options);

		function generateTooltip(aControl) {
			var text = $(aControl).attr('title'),
					h = 0,
					w = 0,
					pos = $.extend({}, $(aControl).offset(), {height:aControl.offsetHeight, width:aControl.offsetWidth});

			$(aControl).attr('title', '');

			$('body').append(
				$('<div/>', {
					className:'ttip',
					css:{
						left:0,
						position:'absolute',
						top:0,
						zIndex:9999
					}
				}).append(
					$('<div/>', {
						className:'inner-ttip',
						text:text
					})
				)
			);

			h = $('.ttip').outerHeight();
			w = $('.ttip').outerWidth();

			switch (settings.location) {
				case 's':
					$('.ttip').css({left:pos.left + pos.width / 2 - w / 2, top:pos.top + pos.height}).addClass('south');
					break;
				case 'e':
					$('.ttip').css({left:pos.left + pos.width, top:pos.top + pos.height / 2 - h / 2}).addClass('east');
					break;
				case 'w':
					$('.ttip').css({left: pos.left - w, top:pos.top + pos.height / 2 - h / 2}).addClass('west');
					break;
				default : 
					$('.ttip').css({left:pos.left + pos.width / 2 - w / 2, top:pos.top - h}).addClass('north');
					break;
			}
		}

		function disposeTooltip(aControl) {
			var text = $('.ttip').text();
			$(aControl).attr('title', text);
			$('.ttip').remove();
		}

		return this.hover(
			function() {generateTooltip(this);}, function () {disposeTooltip(this);}
		);
	};

	$.fn.ttip.defaults = {location:'n'};
})(jQuery);

(function($) {
	/*
	 * 	Print Icon 1.4.0 - jQuery plugin
	 *	written by Nico De Backer
	 *
	 *	Copyright (c) 2009-2010 Nico De Backer (http://iamwebdeveloper.com)
	 *	Dual licensed under the MIT and GPL licenses:
	 *	http://www.opensource.org/licenses/mit-license.php
	 *	http://www.gnu.org/licenses/gpl.html
	 *
	 *	Built for jQuery library (1.4 and higher)
	 *	http://jquery.com
	 *
	 *	Displays a print icon with print functionality within element
	 *
	 *	@name		printicon
	 *	@param	alt			Alternative text for print icon image													'Print page'
	 *	@param	append		Boolean to indicate an append (true) or prepend (false) of the icon to the element		true
	 *	@param	id			Id of the <a> wrapped around print icon												'printPage'
	 *	@param	src			Path to the print icon image														'images/printer.png'
	 *	@example	$('body').printicon();
	 */
	$.fn.printicon = function(options) {
		var settings = $.extend({}, $.fn.printicon.defaults, options);

		return this.each(function() {
			var $me = $(this),
					$icon = $('<img/>', {alt:settings.alt, src:settings.src}),
					$a = $('<a/>', {href:'javascript:print();', id:settings.id}).append($icon);

			if (settings.append) {$me.append($a);} else {$me.prepend($a);}
		});
	};

	$.fn.printicon.defaults = {
		alt:'Print page',
		append:true,
		id:'printPage',
		src:'images/printer.png'
	};
})(jQuery);

$(document).ready(function() {
	/* External links in new window */
	$('a[rel*="external"]').attr('target', '_blank');

	/* Show print page icon */
	$('#content').printicon({alt:'Print page', src:'http://iamwebdeveloper.com/images/uploads/print.png'});

	/* Show fancy tooltip on favourite tools */
	if ($('#favtools').length === 1) {$('#favtools').find('img').ttip();}

	/* Contact form validation */
	if ($('#contactform').length === 1) {
		$('#contactform').formvalidate({messages:{email:'This is not a valid email address', required:'This is a required field', summary:'Please correct the errors with the following {0} fields:'}});
	}
});
