﻿/// <reference path="jquery-1.4.1-vsdoc.js"/>
document.createElement("abbr");

$(document).ready(function()
{
	$('#page').removeClass('no-js').addClass('has-js');

	$('#page').externalLinks();

	// column heights
	$('.tabbed-feature').matchHeight('.aside .product:eq(0)');
	$('.equalise').css({ 'overflow': 'hidden', 'zoom': '1' }).equaliseHeights();

	// LabelToValue
	$('.l2v').labelToValue();

	// big link
	$('.product, .related-products dl, .news-list li').bigLink();

	// IE6 + IE7 fix for incorrect clearing behaviour on DD
	if ($.browser.msie && $.browser.version <= 8)
	{
		$('#main dl:not(.steps) dd').each(function(i)
		{
			$('<div class="clear"/>').insertAfter($(this));
		});
	}

	// IMAGE LOADER
    $('.product-images').each(function(i)
    {
		var mainimage = $(this).prev('.product-image');
		
		$(this).find('a').click(function(e)
		{
			e.preventDefault();
			
			mainimage.load(this.href + ' .product-image img');
        });
    });

	// Increment / Decrement
	$('.qty').each(function(i)
	{
		var increment = $('<img />')
		.attr('src', $.assetsRoot() + '/css/images/btn_increment.png')
		.css({ 'vertical-align': 'middle', 'cursor': 'pointer', 'display': 'inline-block' })
		.addClass('btn-qty-inc')
		.click(function(e)
		{
			var qty = $(this).siblings('.qty');

			qty.val(parseInt(qty.val()) || 0);

			if (qty.val() < 9999)
			{
				qty.val(parseInt(qty.val()) + 1).keyup();
			}
		});

		var decrement = $('<img />')
		.attr('src', $.assetsRoot() + '/css/images/btn_decrement.png')
		.css({ 'vertical-align': 'middle', 'cursor': 'pointer', 'display': 'inline-block' })
		.addClass('btn-qty-dec')
		.click(function(e)
		{
			var qty = $(this).siblings('.qty');

			qty.val(parseInt(qty.val()) || 0);

			if (qty.val() > 0)
			{
				qty.val(parseInt(qty.val()) - 1).keyup();
			}
		});

		if ($.browser.msie)
		{
			increment.add(decrement).dblclick(function(e)
			{
				$(this).click();
			});
		}

		decrement.insertBefore($(this));
		increment.insertAfter($(this));

		$(this).keyup(function()
		{
			$(this).val($(this).val().replace(/\D/g, ''));
		});
	});

	// auto tabbing of multipart fields
	$('.form-row input[class*=multipart-]').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();
						}
					});
				}
			});
		});
	});

	// ajax tabbed panel
	$('.tabbed-feature').each(function(i)
	{
		var self = this;
		var intv;

		$(this)
		.find('.nav a')
		// prefetch
		.each(function(i)
		{
			$(this).data('query', $(this).attr('href').replace(/^.*?(\?section=.+?)(&.*)?$/, '$1'));

			$.ajax({
				url: $.siteRoot() + '/handlers/tabpanel.aspx' + $(this).data('query'),
				dataType: 'html',
				cache: true
			});
		})
		// handle click
		.click(function(e)
		{
			e.preventDefault();

			$(this).parents('li').addClass('current').siblings('li').removeClass('current');

			$.ajax({
				url: $.siteRoot() + '/handlers/tabpanel.aspx' + $(this).data('query'),
				dataType: 'html',
				cache: true,
				success: function(data, textStatus, XMLHttpRequest)
				{
					this.children(':not(.nav)').remove().end().append(data);
				},
				error: function(XMLHttpRequest, textStatus, errorThrown)
				{
					this.children(':not(.nav)').remove().end().append('<div class="copy"><h1>Sorry, there is nothing to show</h1><h2>We&rsquo;re having a problem right now. Please try again in a few minutes.</h2></div>');
				},
				context: $(this).parents('.tabbed-feature')
			});
		});

		function next()
		{
			var next = $(self).find('li.current').next('li');

			if (!next.length)
			{
				next = $(self).find('li.current').siblings('li').eq(0);
			}

			next.find('a').click();
		}

		setTimeout(function()
		{
			intv = setInterval(next, 8000);

			$(self).hover(function(e)
			{
				clearInterval(intv);
			},
			function(e)
			{
				intv = setInterval(next, 8000);
			});
		}, 8000);
	});
});

$.fn.equaliseHeights = 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.matchHeight = function(query)
{
	var height = $(query).height() + (parseInt($(query).css('padding-top')) + parseInt($(query).css('padding-bottom'))) - (parseInt(this.css('padding-top')) + parseInt(this.css('padding-bottom')));
	
	this.css({ minHeight: height + 'px' });

	if ($.browser.msie && $.browser.version < 7)
	{
		this.css({ height: height + 'px' });
	}

	height = null;
	delete height;

	return this;
};

$.siteRoot = function()
{
	var lnk = $('link[rel=home]');
	return (lnk.length) ? lnk.attr('href') : '';
}

$.assetsRoot = function()
{
	var scr = $('script[src*="/global.js"]');
	return (scr.length) ? scr.attr('src').replace(/\/js\/global\.js.*?$/gi, '') : '';
}

$.fn.externalLinks = function()
{
	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.blink = 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.labelToValue = function()
{
	function sanitize(label)
	{
		return $.trim(label).replace(/\s*?\*$/, '');
	}

	function getLabel(id)
	{
		return sanitize($('label[for="' + id + '"]:not(.alert label):last').hide().text());
	}

	function hideLabel()
	{
		if (this.id)
		{
			var field = $(this);
			var label = getLabel(this.id);

			if (sanitize(field.val()) == label)
			{
				field.val('').removeClass('l2v-added');
			}
			else
			{
				field.removeClass('l2v-added');
			}

			field, label = null;
			delete field, label;
		}
	}

	function showLabel()
	{
		if (this.id)
		{
			var field = $(this);
			var label = getLabel(this.id);

			if (sanitize(field.val()) == label || field.val() == '')
			{
				field.addClass('l2v-added').val(label);
			}

			field, label = null;
			delete field, label;
		}
	}

	this.each(function(i)
	{
		$(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.bigLink = 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.googlemap = function(options)
{
	var defaults = {};

	options = $.extend(defaults, options);

	this.each(function(i)
	{
		var canvas = this;

		// load google maps api js
		$.ajax({
			url: 'http://maps.google.com/maps/api/js?sensor=false',
			dataType: 'jsonp',
			context: canvas,
			success: initMap
		});

		// init google map
		function initMap(canvas)
		{
			canvas = canvas || this;

			var myOptions = {
				mapTypeId: google.maps.MapTypeId.ROADMAP
			};

			$(canvas).data('map', new google.maps.Map(canvas, myOptions));

			if (options.markers)
			{
				loadMarkers(canvas, options.markers);
			}

			if (options.localsearch)
			{
				loadMarkersFromLocalSearch(canvas, options.localsearch);
			}
		}

		// load markers
		function loadMarkers(canvas, markers)
		{
			var postcodeMarkers = [];

			$.each(markers, function(i)
			{
				if (this.lat && this.lng)
				{
					addMarker(canvas, this)
				}
				else if (this.postcode)
				{
					postcodeMarkers.push(this);
				}
			});

			if (postcodeMarkers.length)
			{
				loadMarkersFromPostCode(canvas, postcodeMarkers);
			}
		}


		// local search
		function loadMarkersFromLocalSearch(canvas, searches)
		{
			var canvas = canvas;

			$.each(searches, function(i)
			{
				$.ajax({
					url: 'http://ajax.googleapis.com/ajax/services/search/local?v=1.0',
					data: this,
					dataType: 'jsonp',
					context: this,
					success: function(data)
					{
						//console.log(data.responseData);

						if (data.responseStatus == 200)
						{
							$.each(data.responseData.results, function(i)
							{
								addMarker(canvas, {
									"title": this.titleNoFormatting,
									"lat": this.lat,
									"lng": this.lng,
									"infowindow": {
										"content": '<strong>' + this.titleNoFormatting + '</strong><br />' + this.addressLines.join('<br />') + '<br />' + '<a href="' + this.ddUrlToHere + '" target="_blank">Get Directions</a>'
									}
								});
							});
						}
					}
				});
			});
		}

		// postcode lookup
		function loadMarkersFromPostCode(canvas, markers)
		{
			var canvas = canvas;

			$.each(markers, function(i)
			{
				$.ajax({
					url: 'http://ajax.googleapis.com/ajax/services/search/local',
					data: { v: '1.0', q: this.postcode, gl: 'uk' },
					dataType: 'jsonp',
					context: this,
					success: function(data)
					{
						if (data.responseStatus == 200 && data.responseData.results[0])
						{
							this.lat = data.responseData.results[0].lat;
							this.lng = data.responseData.results[0].lng;

							addMarker(canvas, this);
						}
					}
				});
			});
		}

		// add marker
		function addMarker(canvas, marker)
		{
			// create a LatLng object
			var latlng = new google.maps.LatLng(marker.lat, marker.lng);

			var map = $(canvas).data('map');

			var bounds = $(canvas).data('bounds') || new google.maps.LatLngBounds();

			var image = new google.maps.MarkerImage($.assetsRoot() + '/css/markers/image.png',
			// This marker is 32 pixels wide by 30 pixels tall.
							new google.maps.Size(32, 30),
			// The origin for this image is 0,0.
							new google.maps.Point(0, 0),
			// The anchor for this image is the base of the flagpole at 16,30.
							new google.maps.Point(16, 30)
						);

			var shadow = new google.maps.MarkerImage($.assetsRoot() + '/css/markers/shadow.png',
			// The shadow image is larger in the horizontal dimension
			// while the position and offset are the same as for the main image.
							new google.maps.Size(47, 30),
							new google.maps.Point(0, 0),
							new google.maps.Point(16, 30)
						);

			// Shapes define the clickable region of the icon.
			// The type defines an HTML &lt;area&gt; element 'poly' which
			// traces out a polygon as a series of X,Y points. The final
			// coordinate closes the poly by connecting to the first
			// coordinate.
			var shape = {
				coord: [
								22, 0, 24, 1, 26, 2, 27, 3, 28, 4, 29, 5, 30, 6, 30, 7, 30, 8, 30, 9, 30,
								10, 30, 11, 30, 12, 30, 13, 30, 14, 30, 15, 30, 16, 30, 17, 30, 18, 30, 19,
								31, 20, 30, 21, 30, 22, 29, 23, 28, 24, 27, 25, 26, 26, 25, 27, 24, 28, 19,
								29, 17, 29, 14, 28, 11, 27, 10, 26, 9, 25, 8, 24, 9, 23, 8, 22, 7, 21, 6,
								20, 5, 19, 4, 18, 3, 17, 2, 16, 1, 15, 1, 14, 1, 13, 0, 12, 0, 11, 0, 10,
								0, 9, 1, 8, 2, 7, 6, 6, 7, 5, 7, 4, 8, 3, 10, 2, 11, 1, 14, 0
							],
				type: 'poly'
			};

			// extend the bounds object
			bounds.extend(latlng);

			// set up infowindow
			if (marker.infowindow && marker.infowindow.content != '')
			{
				var infowindow = new google.maps.InfoWindow({
					content: $('<div/>').height(110).html(marker.infowindow.content).get(0),
					maxWidth: 200
				});
			}

			// add the marker to the map
			var marker = new google.maps.Marker({
				position: latlng,
				map: map,
				shadow: shadow,
				icon: image,
				shape: shape,
				title: marker.title || ''
			});

			if (infowindow)
			{
				google.maps.event.addListener(marker, 'click', function()
				{
					infowindow.open(map, marker);
				});
			}

			// set the center and zoom of the map to show all markers
			map.setCenter(bounds.getCenter());
			map.fitBounds(bounds);

			$(canvas).data('bounds', bounds);
		}
	});

	return this;
}
