﻿/// <reference path="jquery-1.3.2-vsdoc2.js"/>

Cufon.replace('#branding span', { fontFamily: 'Helvetica53-Extended', separate: 'none', textShadow: '#000 -1px -1.5px' });
Cufon.replace('.panel:not(.p_feature) h2:not(.no-cufon), .footer-list dt, #footer dt, table:not(.in-panel) th', { fontFamily: 'Helvetica53-Extended', textShadow: '#fff 1px 1.5px' });
Cufon.replace('.panel.p_feature h2:not(.no-cufon)', { fontFamily: 'Helvetica53-Extended' });
Cufon.replace('.steps li', { fontFamily: 'Helvetica53-Extended' });

document.createElement("abbr");

$(document).ready(function()
{
	$(".googlemap").googleMap();

	$(document).externalLinks();

	$('.datepicker').datepicker(
	{
		buttonImage: $.assetsRoot() + '/css/images/ico_datepicker.png',
		buttonImageOnly: true,
		showOn: 'button',
		dateFormat: 'dd/mm/yy',
		defaultDate: '+0',
		//yearRange: '1900:2050',
		yearRange: '-1:+5', // from now until 5 years in the future
		minDate: '-6m',
		maxDate: '+5y',
		changeMonth: true,
		changeYear: true,
		duration: '', // show immediatley
		onChangeMonthYear: function(y, m, jq)
		{
			if (jq.currentDay)
			{
				$(this).datepicker('setDate', $.datepicker.parseDate('d/m/yy', jq.currentDay + '/' + m + '/' + y));
			}
		}
	});

	$('.labeltovalue').labelToValue();

	$('.p_feature, .biglink').bigLink();

	// Panel borders, corners and dropshadows
	$('.panel').each(function(i)
	{
		$(this).append('<b class="p_border p_mid"></b>')
			.append('<b class="p_border p_top"><b></b></b>')
			.append('<b class="p_border p_btm"><b></b></b>')
			.addClass('p_border');

		if ($(this).offset().top <= $('#main').offset().top + 10)
		{
			$(this).addClass('alpha');
		}
	});

	// Panel 'comment arrow'
	$('.discussion .panel.post').each(function(i)
	{
		$(this).append('<b class="p_comment p_left"></b>')
	});
	$('.panel.post .post_alt').each(function(i)
	{
		$(this).append('<b class="p_comment p_right"></b>')
	});

	// Tile borders, corners and dropshadows
	$('.tile').each(function(i)
	{
		$(this).append('<b class="t_border t_mid"></b>')
			.append('<b class="t_border t_top"><b></b></b>')
			.append('<b class="t_border t_btm"><b></b></b>')
			.addClass('t_border');
	});

	// IE6 + IE7 fix for incorrect clearing behaviour on DD
	if ($.browser.msie && $.browser.version <= 8)
	{
		$('#main dl:not(.steps):not(.vcard):not(.meta) dd').each(function(i)
		{
			$('<div class="clear"/>').insertAfter($(this));
		});
	}

	// quantity inc/dec buttons
	$('input.quantity').each(function(i)
	{
		var inc = $('<span class="quantity-inc" />');
		var dec = $('<span class="quantity-dec" />');
		var qty = $(this);

		inc.click(function(e)
		{
			if (qty.val() < 9999)
			{
				qty.val(parseInt(qty.val()) + 1);
			}
		});

		dec.click(function(e)
		{
			if (qty.val() > 0)
			{
				qty.val(parseInt(qty.val()) - 1);
			}
		});

		dec.insertBefore(qty);
		inc.insertAfter(qty);
	});

	// image viewer (thumbs)
	// &h=1&w=340&fill=true&fd=false&fe=false
	$('.bigimage').bigImage();
	$('.bigimage').parents('#primary').find('.image-list a').each(function(i)
	{
		var thumb = $(this).click(function(e)
		{
			e.preventDefault();

			var img = $(this).parents('#primary').find('.bigimage img');
			var thm = $(this).find('img');

			var new_src = img.attr('src')
				.replace(/fn=.*?&|$/, thm.attr('src').match(/fn=.*?&|$/))
				.replace(/(\?|\&)([hw]=)\d+/g, '$1$2700')
				.replace(/(\?|\&)(fill=)(true|false)/g, '$1$2true')
				.replace(/(\?|\&)(fd=)(true|false)/g, '$1$2false')
				.replace(/(\?|\&)(fe=)(true|false)/g, '$1$2false');

			img.attr('src', new_src);
			img.attr('alt', thm.attr('alt'));

			return false;
		});

		// converts current showing image (on page load) into bigImage 
		var thm = thumb.find('img[alt="' + thumb.parents('#primary').find('.bigimage img').attr('alt') + '"]:first')

		if (thm.length)
		{
			$(window).load(function(e)
			{
				var img = thumb.parents('#primary').find('.bigimage img');

				var new_src = img.attr('src')
					.replace(/fn=.*?&|$/, thm.attr('src').match(/fn=.*?&|$/))
					.replace(/(\?|\&)([hw]=)\d+/g, '$1$2700')
					.replace(/(\?|\&)(fill=)(true|false)/g, '$1$2true')
					.replace(/(\?|\&)(fd=)(true|false)/g, '$1$2false')
					.replace(/(\?|\&)(fe=)(true|false)/g, '$1$2false');

				img.attr('src', new_src);
				img.attr('alt', thm.attr('alt'));
			});
		}
	});

	// Youtube aspect ratio resizer
	$('.youtube').each(function(i)
	{
		var self = $(this);
		var width = self.width();
		var ytsrc = self.find('param[name=movie]').attr('value') || self.find('embed').attr('src');
		var ytid = ytsrc.replace(/^(http:\/\/)?(www\.)?youtube\.com\/((v\/)|(watch\?v=))([a-z0-9]+?)(&.*)?$/i, "$6");

		$.getJSON('http://gdata.youtube.com/feeds/api/videos/' + ytid + '?v=2&alt=json&callback=?', function(data, status)
		{
			try
			{
				switch (data.entry.media$group.yt$aspectRatio.$t)
				{
					case 'widescreen':
						height = (width / 16) * 9;
						break;
					default:
						height = (width / 4) * 3;
				}
				self.add(self.find('object, embed')).height(height + 25); // 25 = youtube control bar height
			}
			catch (e) { }
		});
	});
});

$.fn.delay = function(time, callback)
{
    jQuery.fx.step.delay = function() { };
    // Return meaningless animation, (will be added to queue)
    return this.animate({ delay: 1 }, time, callback);
};


$.fn.initAddThis = function()
{
    var self = $(this);
    var len = self.length - 1;
    
    self.each(function(i)
    {
        var addthis = $('<ul/>');

        var at_email = $('<li class="alpha email"><a class="addthis_button_email" href="#">Email</a></li>');
        var at_share = $('<li class="omega share"><a class="addthis_button" href="#">Share</a></li>');

        addthis.append(at_email).append(at_share);

        $(this).append($('<div class="social" />').append(addthis));

        if (i == len && $('head script[src*=addthis_widget.js]').length == 0)
        {
            $('head').append($('<script type="text/javascript" src="http://s7.addthis.com/js/250/addthis_widget.js?pub=tallulahlove"><\/script>'));
        }
    });

    return self;
}

$.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.bigLink = function(/**String*/selector)
{
    var self = this;
    var selector = selector || 'a[@href]:eq(0)';

    this.click(function(e)
    {
        var link = $(this).find(selector);

        // the first link within the supplied element
        var prevent_default = false;

        //
        var target_is_link = (e.target.nodeName == 'A');

        // 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');

    return self;
}

$.fn.labelToValue = function()
{
    var self = this;

    self.focus(function()
    {
        var field = $(this);

        if (this.id)
        {
            var label = $.trim($('label[for="' + this.id + '"]:last').hide().text());
        }
        else
        {
            return;
        }

        if (field.val() == label)
        {
            field
			.val('')
			.removeClass('label');
        }
        else
        {
            field
			.removeClass('label');
        }
    })
	.blur(function()
	{
	    var field = $(this);

	    if (this.id)
	    {
	        var label = $.trim($('label[for="' + this.id + '"]:last').hide().text());
	    }
	    else
	    {
	        return;
	    }

	    if (field.val() == label || field.val() == '')
	    {
	        field
			.val(label)
			.addClass('label');
	    }
	})
	.blur()
	.parents('form').submit(function(e)
	{
	    var current = $(':focus');
	    var scrollY = $(document).scrollTop();

	    // trigger the focus event to remove label text from field
	    self.focus();
	    // remove all bound events
	    self.unbind();

	    current.get(0).focus();

	    $(document).scrollTop(scrollY);
	});

    return self;
}

$.fn.bigImage = function()
{
	var self = this;

	self.find('img').each(function(i)
	{
		var img = $(this);

		img.load(function(i)
		{
			if ($(this).data('hasLoaded') == true && $(this).data('imgSrc') == $(this).attr('src'))
			{
				return;
			}

			$(this).data('hasLoaded', true);
			$(this).data('imgSrc', $(this).attr('src'));

			if ($(this).data('intv'))
			{
				clearInterval($(this).data('intv'));
			}

			var container = $(this).parent().removeAttr('style').unbind('mouseenter').unbind('mouseleave').unbind('mousemove');
			var image = container.find('img').removeAttr('style');

			var cont_height = container.height();
			var cont_width = container.width();

			image.css({ height: 'auto', width: 'auto' });

			var img_zoom_height = image.height();
			var img_zoom_width = image.width();

			if (img_zoom_height < cont_height || img_zoom_width < cont_width)
			{
				image.removeAttr('style');
				return; // don't apply to images that are smaller
			}

			if (img_zoom_height / img_zoom_width < cont_height / cont_width)
			{
				image.css({ width: 'auto', height: '100%', margin: '0' });
				//image.css({ marginLeft: (cont_width - image.width()) / 2 });
			}
			else
			{
				image.css({ width: '100%', height: 'auto', margin: '0' });
				//image.css({ marginTop: (cont_height - image.height()) / 2 });
			}

			container.css({
				'background-image': 'url(' + image.attr('src') + ')',
				'background-repeat': 'no-repeat',
				'background-position': '50% 50%',
				'height': cont_height + 'px',
				'width': cont_width + 'px'
			});

			image.css('msInterpolationMode', 'bicubic');

			container
            .mouseenter(function(e)
            {
            	//image.css('msInterpolationMode', 'nearest-neighbor');
            	image.fadeOut(400);
            })
            .mouseleave(function(e)
            {
            	image.fadeIn(400/*, function() { image.css('msInterpolationMode', 'bicubic') }*/);
            });


			var xmouse = 0;
			var ymouse = 0;

			var xdif = cont_width - img_zoom_width;
			var ydif = cont_height - img_zoom_height;

			var xpos = xmouse / cont_width;
			var ypos = ymouse / cont_height;

			var xold = container.scrollLeft();
			var yold = container.scrollTop();

			var xnew = xold;
			var ynew = yold;

			var speed = 10; // larger is slower
			var viscosity = 1.2;

			var xvelocity = 0;
			var yvelocity = 0;

			container
            .mousemove(function(e)
            {
            	xmouse = e.pageX - $(this).offset().left;
            	ymouse = e.pageY - $(this).offset().top;
            });

			function onEnterFrame()
			{
				xpos = xmouse / cont_width;
				ypos = ymouse / cont_height;

				xnew = xdif * xpos;
				ynew = ydif * ypos;

				var xdifference = xnew - xold;
				var ydifference = ynew - yold;

				xvelocity = ((xvelocity + xdifference) / speed) / viscosity;
				yvelocity = ((yvelocity + ydifference) / speed) / viscosity;

				xold += xvelocity;
				yold += yvelocity;

				//container.scrollLeft(Math.abs(xold));
				//container.scrollTop(Math.abs(yold));

				container.css('background-position', xold + 'px ' + yold + 'px');
			}

			$(this).data('intv', setInterval(onEnterFrame, 20));
		});

		img.attr('src', img.attr('src'));
	});

	return self;
}

$.googleMap = function(jq)
{
    jq.each(function(i)
    {
        var cssclass = $(this).attr('class');

        var postcode = cssclass.match(/postcode_(.+?)\b/);
        var latitude = cssclass.match(/latitude_(-?.+?)\b/);
        var longitude = cssclass.match(/longitude_(-?.+?)\b/);

        initMap($(this).get(0), postcode, latitude, longitude);
    });

    function initMap(elm, postcode, lat, lng)
    {
        if (google.maps.BrowserIsCompatible())
        {
            var map = new google.maps.Map2(elm);

            map.setUIToDefault();
            map.disableScrollWheelZoom();

            if (lat && lng && lat[1] != null && lng[1] != null)
            {
                var point = new google.maps.LatLng(lat[1].replace('_', '.'), lng[1].replace('_', '.'));

                if (point)
                {
                    map.setCenter(point, 13);

                    var marker = new google.maps.Marker(point);
                    map.addOverlay(marker);
                }
            }
            else if (postcode[1])
            {
                usePointFromPostcode(postcode[1], function(point)
                {
                    if (point)
                    {
                        map.setCenter(point, 13);

                        var marker = new google.maps.Marker(point);
                        map.addOverlay(marker);
                    }
                });
            }
        }
    }

    function usePointFromPostcode(postcode, callbackFunction)
    {
        var localSearch = new google.search.LocalSearch();

        localSearch.setSearchCompleteCallback(null, function()
        {
            if (localSearch.results[0])
            {
                var resultLat = localSearch.results[0].lat;
                var resultLng = localSearch.results[0].lng;
                var point = new google.maps.LatLng(resultLat, resultLng);

                callbackFunction(point);
            }
        });

        localSearch.execute(postcode + ", UK");
    }
}

$.fn.googleMap = function()
{
    var self = this;

    if (self.length)
    {
        if ($.googleMap.loaded == undefined || (!$.googleMap.loaded['maps'] && !$.googleMap.loaded['search']))
        {
            $.googleMap.loaded = [];

            google.load('maps', '2', { 'other_params': 'sensor=true', 'callback': function() { googleLoaded('maps') } });
            google.load('search', '1', { 'nocss': true, 'nooldnames': true, 'callback': function() { googleLoaded('search') } });
        }
        else
        {
            googleLoaded();
        }
    }

    function googleLoaded(api)
    {
        if (api)
        {
            $.googleMap.loaded[api] = true;
        }

        if ($.googleMap.loaded['maps'] && $.googleMap.loaded['search'])
        {
            $.googleMap(self);
        }
    }

    return self;
}
