﻿/// <reference path="jquery-1.4.2-vsdoc.js"/>

/**!
* Part of the AYO Framework
* The following notice may not be removed under any circumstances.
*
* @author		Jon Burger
* @version		1.0
* @copyright	2010 AYO Media Limited / Jon Burger. All Rights Reserved - where any exist ;)
* @see			http://ayomedia.co.uk
* @see			http://jonburger.com
*
* @date			2nd July 2010
* @media		Screen
*/

(function ($)
{
	$.ayo = $.ayo || new Object();

	///////////////////////////////////////////////////////////////

	var assetsRoot = $.ayo.assetsRoot = function ()
	{
		var scr = $('script[src*="/global.js"]');
		return (scr.length) ? scr.attr('src').replace(/\/js\/global\.js.*?$/gi, '') : '';
	}

	var siteRoot = $.ayo.siteRoot = function ()
	{
		var lnk = $('*[rel=home]:eq(0)');
		return (lnk.length) ? lnk.attr('href') : '';
	}

	///////////////////////////////////////////////////////////////

	$.fn.ayoShowHide = function ()
	{
		function showhide(e)
		{
			// get all showables and hide
			$('[class*=showable-]').hide();

			// get all checked shows
			$('input:checked[class*=show-], [class*=show-] > input:checked')
		    .each(function (i)
		    {
		    	// get show classes
		    	var match = $(this).add($(this).parent()).filter('[class*=show-]').attr('class').match(/show-([^ ]+)/g);

		    	// rewrite show classes and show any associated showables
		    	$('.' + match.join(', .').replace(/show-/g, 'showable-')).show();
		    });

			// uncheck any hidden radio buttons or checkboxes
			$('input:checked:hidden').removeAttr('checked');

			// hide any visible qtip help-tips
			if ('qtip' in $.fn)
			{
				$('.help-tip').qtip('hide');
			}
		}

		return this.each(function (i)
		{
			// get all inputs with same name (e.g. radio buttons)
			$('[name=' + $(this).attr('name') + ']')
			// attach click event handler
			.click(showhide)
			.each(showhide);
		});
	}

	$.fn.ayoAddBorders = function ()
	{
		if ($.browser.msie && $.browser.version < 7)
		{
			$('head').append('<style type="text/css">b.p_mid { height: expression(this.parentNode.offsetHeight + "px") }</style>');
		}

		var borders = $('<b class="p_border p_mid"></b><b class="p_border p_top"><b></b></b><b class="p_border p_btm"><b></b></b>');

		this.each(function (i)
		{
			$(this).append(borders.clone()).addClass('p_border');
		});

		borders.remove();

		return this;
	}

	$.fn.ayoBlink = function (limit, speed)
	{
		this.data('speed', speed || 300).data('limit', limit || Infinity)
		.fadeTo(speed, this.css('opacity') == 1 ? .2 : 1, function ()
		{
			var limit = $(this).data('limit') - .5;

			if (limit > 0)
			{
				$(this).blink(limit, $(this).data('speed'));
				$(this).data('limit', limit);
			}

			limit = null;
			delete limit;
		});

		return this;
	}

	$.fn.ayoEqualiseHeights = function ()
	{
		var self = this;
		var height = 0;

		self.each(function (i)
		{
			$(this).css({ 'height': 'auto', 'min-height': 0 });

			height = Math.max($(this).height(), height);
		})

		self.css({ minHeight: height + 'px' });

		if ($.browser.msie && $.browser.version < 7)
		{
			self.css({ height: height + 'px' });
		}

		return self;
	};

	$.fn.ayoLabelToValue = function ()
	{
		function sanitize(label)
		{
			return $.trim(label).replace(/\s*?\*$/, '');
		}

		function hideLabel()
		{
			var field = $(this);

			if (this.id)
			{
				var label = sanitize($('label[for="' + this.id + '"]:not(.alert label):last').hide().text());
			}
			else
			{
				return;
			}

			if (sanitize(field.val()) == label)
			{
				field.val('').removeClass('l2v-added');
			}
			else
			{
				field.removeClass('l2v-added');
			}
		}

		function showLabel()
		{
			var field = $(this);

			if (this.id)
			{
				var label = sanitize($('label[for="' + this.id + '"]:not(.alert label):last').hide().text());
			}
			else
			{
				return;
			}

			if (sanitize(field.val()) == label || field.val() == '')
			{
				field.addClass('l2v-added').val(label);
			}
		}

		this.each(function (i)
		{
			if ('placeholder' in this)
			{
				$(this).attr('placeholder', sanitize($('label[for="' + this.id + '"]:not(.alert label):last').hide().text()));

				return;
			}

			$(this)
		.focus(hideLabel)
		.blur(showLabel);

			if (!$(this).parents('form').data('l2v-fields'))
			{
				$(this).parents('form')
			.data('l2v-fields', true)
			.submit(function (e)
			{
				$(this).find('.l2v').each(hideLabel);
			});
			}

			showLabel.call($(this).get(0));
		});

		return this;
	}

	$.fn.ayoBigLink = function (/**String*/selector)
	{
		this
		.addClass('biglink-added')
		.data('biglink', selector || 'a[@href]:eq(0)')
		.click(function (e)
		{
			var link = $(this).find($(this).data('biglink'));

			// the first link within the supplied element
			var prevent_default = false;

			// check through all click events for preventDefault command (so we know whether to redirect or not)
			var all_events = link.data('events');
			var click_events;

			if (all_events && all_events.click)
			{
				click_events = all_events.click;

				for (var k in click_events)
				{
					if (/\.preventDefault\(\)/.test(click_events[k].toString()))
					{
						prevent_default = true;
					}
				}
			}

			// trigger all jquery assigned events
			link.triggerHandler('click');

			// if preventDefault has never been assigned to this link then it is safe to do a standard redirect
			if (!prevent_default)
			{
				//document.location = link.attr('href');
				return !window.open(link.attr('href'), link.attr('target') || '_self');
			}
		})
		.hover(function () { $(this).addClass('hover') }, function () { $(this).removeClass('hover') })
		.css('cursor', 'pointer')
		.find('input, select, textarea, a')
		.click(function (e) { e.stopPropagation() })
		/*.hover(function(e) { $(this).parents('.biglink-added').trigger('mouseout'); },
		function(e) { $(this).parents('.biglink-added').trigger('mouseover'); })*/;

		return self;
	}

	$.fn.ayoAutoTab = function ()
	{
		return this.each(function (i)
		{
			var self = $(this);

			self.attr('class').replace(/\bmultipart-(\d+)\b/, function (matched, captured)
			{
				captured = captured || Infinity;

				self.keydown(function (e)
				{
					if (e.shiftKey && e.which == 9)
					{
						$(this).unbind('keyup');
					}
					else
					{
						$(this).one('keyup', function (e)
						{
							if ($(this).val().length >= captured)
							{
								$(this).val($(this).val().substring(0, captured)).next('input[class*=multipart-]').focus();
							}
						});
					}
				});
			});
		});
	}

	$.ayo.spriteAnimation = function (sprite, delay, frame)
	{
		sprite
		.data('frame', frame || 0)
		.animate({ ayoSpriteAnimation: 0 }, sprite.data('delay')(frame || 0), function ()
		{
			var frame = ($(this).data('frame') + 1) % $(this).data('frames');

			$(this).data('frame', frame)
			.css({ backgroundPosition: '-' + (($(this).data('width') * frame)) + 'px 0' })

			$.ayo.spriteAnimation(sprite, $(this).data('delay'), frame);

			frame = null;
			delete frame;
		});
	}

	$.fn.ayoSpriteAnimation = function (delay)
	{
		this.each(function (i)
		{
			$('<img />')
		.css({ position: 'absolute', left: '-999in', top: '-999in' })
		.data('sprite', $(this))
		.load(function (e)
		{
			var sprite = $(this).data('sprite');

			sprite
			.data('width', sprite.width())
			.data('frames', ($(this).width() / sprite.width()) * 10)
			.data('delay', delay || function () { return 500 });

			// animate
			$.ayo.spriteAnimation(sprite, $(this).data('delay'));

			sprite = null;
			delete sprite;
		})
		.appendTo('body')
		.attr('src', $(this).css('backgroundImage').replace(/^url\("?(.*?)"?\)$/, '$1'));
		});
	}

	/*$.ayo.googleMap = function (el, postcode, lat, lng)
	{
	var self = $(this);
	};



	$.fn.ayoGoogleMap = function (postcode, lat, lng)
	{
	return this.each(function ()
	{
	(new $.ayo.googleMap(this, postcode, lat, lng));


	});
	};*/

})(jQuery);


/**!
* Special event for image load events
* Needed because some browsers does not trigger the event on cached images.

* MIT License
* Paul Irish     | @paul_irish | www.paulirish.com
* Andree Hansson | @peolanha   | www.andreehansson.se
* 2010.
*
* Usage:
* $(images).bind('load', function (e) {
*   // Do stuff on load
* });
* 
* Note that you can bind the 'error' event on data uri images, this will trigger when
* data uri images isn't supported.
* 
* Tested in:
* FF2-3.6
* IE6-8
* Chromium4 Developer
* Opera 9-10
*/
/*(function ($)
{

	$.event.special.load = {
		setup: function (data, namespaces, hollaback)
		{
			var retVal = false;

			if (this.tagName.toLowerCase() === 'img' && this.src !== "")
			{
				// Image is already complete, fire the hollaback (fixes browser issues were cached
				// images isn't triggering the load event)
				if (this.complete || this.readyState === 4)
				{
					$(this).bind('load', data || {}, hollaback).trigger('load');
					retVal = true;
				}

				// Check if data URI images is supported, fire 'error' event if not
				else if (this.readyState === 'uninitialized' && this.src.indexOf('data:') >= 0)
				{
					$(this).trigger('error');
					retVal = true;
				}
			}

			return retVal;
		}
	}

} (jQuery));*/
