﻿/// <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.ayoExternalLinks = function ()
	{
		return this.find('a[href^=http]:not([href*=' + location.hostname + ']), a:[rel~=external]').live('focus', function (e) { $(this).attr('target', '_blank') }).end();

		//return this.find('a[href^=http]:not([href*=' + location.hostname + ']), a:[rel~=external]').attr('target', '_blank')/*.append('<em class="ext"> [this link opens in a new window] </em>')*/.end();
	};

	$.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.ayoUpdateBorders = function()
	{
		// Only necessary for IE6
		if ($.browser.msie & $.browser.version < 7)
		{
			$(this).find('.p_btm').css({ position: 'static', bottom: '-10px' }).css({ position: 'absolute', bottom: '0px' });
		}

		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')
		.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.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);
