/**
 * global.js
 *
 * Copyright (c) 2010 Jaguar.com
 *
 * Requires: jquery-1.4.2.min.js AC_OETags.js
 *
 *
 */

sbWatchVideoLabel = sbPlayFilmLabel;

/* check for IE6 and expose variable for image scale fix */
var isIE6 = ($.browser.msie == true && $.browser.version < 7)? true : false;
	
/*
 * supports_video
 *
 * Check for HTML5 support
 */
function supports_video() {
    return !!document.createElement('video').canPlayType;
}

/*
 * supports_flash (9.115)
 *
 *
 */
function supports_flash() {
	// Major version of Flash required
	var requiredMajorVersion = 9;
	// Minor version of Flash required
	var requiredMinorVersion = 115;
	// Minor version of Flash required
	var requiredRevision = 0;
	
	return DetectFlashVer(requiredMajorVersion, requiredMinorVersion, requiredRevision);
}

/*
 * supports_h264
 *
 * Check for H264 codec support
 */
function supports_h264() {
    if (!supports_video())
        return false;
	
    return document.createElement("video").canPlayType('video/mp4; codecs="avc1.42E01E, mp4a.40.2"');
}

/*
 * is_MP4_media(url)
 *
 * Check URL contains MP4 extension
 */
function is_MP4_media(url) {
    return (url.length >= '.MP4'.length && url.toUpperCase().lastIndexOf('.MP4') + '.MP4'.length == url.length);
}

/*
 * supports_media()
 *
 * Short circuit supports_h264()
 *
 */
function supports_media(url) {
    return (supports_flash() || (is_MP4_media(url) && supports_h264()));
}

/*
 * Check if ipad
 *
 *
 */
function isiPad(){
    return (navigator.platform.indexOf("iPad") != -1);
}

/*
 * endsWith
 *
 *
 */
function endsWith(str, suffix) {
    return str.indexOf(suffix, str.length - suffix.length) !== -1;
}

/*
 * startsWith
 *
 *
 */
function startsWith(str, prefix) {
    return str.substring(0, 1) == prefix;
}

/*
 * JavaScript templating engine functions
 *
 *
 */
(function ($) {
	$.nano = function (template, data) {
		return template.replace(/\{([\w\.]*)\}/g, function (str, key) {
			var keys = key.split("."),
				value = data[keys.shift()];
			$.each(keys, function () {
				value = value[this];
			});
			return (value === null || value === undefined) ? "" : value;
		});
	};
})(jQuery);

/*
 * imagetransition plugin
 *
 *
 */
(function($){
	$.fn.imagetransition = function(options) {
		var defaults = {
			pauseLength: 5000,
			transitionSpeed: 1000
		};
		var options = $.extend(defaults, options);
		var obj = this;
		var currentImageIndex=0;
		var nextImageIndex = obj.length == (currentImageIndex + 1) ? 0 : currentImageIndex + 1;
		var paused = false;
		var timer;
		
		this.filter(":not(:first)").css({opacity: "0", display: "none"}); //initialise css properties...
		
		if (nextImageIndex > currentImageIndex)
			QueueNextTransition();
					
		function RunTransition(from, to)
		{
			$(from).fadeTo(options.transitionSpeed, 0, function() {
				$(from).css("display", "none");
			});
			$(to).css("display", "block").fadeTo(options.transitionSpeed, 1);
			QueueNextTransition();
		}
		
		function QueueNextTransition()
		{
			timer = setTimeout(function() {
				nextImageIndex = obj.length == (currentImageIndex + 1) ? 0 : currentImageIndex + 1;
				RunTransition(obj[currentImageIndex], obj[nextImageIndex]);
				currentImageIndex = nextImageIndex;
			}, options.pauseLength);
		}
		
		this.pause = function() {
			clearTimeout(timer);
			timer = null;
		}
		
		this.start = function() {
			if (timer == null) {
				RunTransition(obj[currentImageIndex],
					obj[obj.length == (currentImageIndex + 1) ? 0 : currentImageIndex + 1]);
				currentImageIndex = nextImageIndex;
			}
		}
		
		return this;
	};	
})(jQuery);

/*
 * fadeToggle
 *
 *
 */
jQuery.fn.fadeToggle = function (speed, easing, callback) {
	return this.animate({
		height: "toggle",
		opacity: "toggle"
	}, speed, easing, callback);
};
		
/*
 * Shop nav
 *
 *
 */
$(function() {
	if ($('#shop-nav').length){
		if ($.browser.msie && parseInt($.browser.version)< 7) { //check for below IE7
			$(".links-nav-inner").hover( //add sfHover class to the following selectors 
				 function() { $(this).addClass("sfHover");  }, //on hover add sfHover class
				 function() { $(this).removeClass("sfHover"); //remove sfHover class  
			}); 
		}
		
		if ($.browser.msie && parseInt($.browser.version)< 7) { //check for below IE7
			var shopMenuW = $('.shop-menu').width(); //Find width of the parent ul item
			$('.shop-menu ul').width(shopMenuW+0); //Match the width for the child ul item as bug in IE6
		} 
		
		$("ul.shop-menu li ul").hover( //add sfHover class to the following selectors 
			 function() { $(this).parents('li').addClass("active")  }, //on hover add sfHover class
			 function() { $(this).parents('li').removeClass("active"); //remove sfHover class  
		}); 
		
		$("#shop-nav .links-nav-inner").removeClass("links-nav-bg"); //JavaScript enabled remove class links-nav-bg from page
	}
});

/*
 * Site navigation
 *
 *
 */
$(function() {
	if ($('#main-nav').length){
		$('.allmodels-container').wrap('<div class="slidingPanel" />');
		var slidingPanel = $('.slidingPanel');
		
		$('.wrapper').append('<div class="overlay">&nbsp;</div>');
		var overlay = $('.wrapper .overlay');
		var overlayed = false;
		
		slidingPanel.appendTo('.wrapper');						   
		slidingPanel.append('<a href="#" class="close">'+ sbLofiCloseLabel +' &nbsp;x</a>');
		btnClose = $('.slidingPanel a.close');
		btnClose.hide();
		
		$('a.all-models, .slidingPanel a.close').click(function() { 
			overlay.css('height', $(document).height() + 'px');
			togglePanel(); 
			return false; 
		});
		
		overlay.click(function() { if (overlayed) togglePanel() });
		
		togglePanel = function() {
			$('a.all-models').parent().toggleClass('active');
			var videoObjects = $('object');
			var selectObjects = $('select');
			var wrapperHeight = $('.wrapper').height(); // Match height of All models overlay with height of wrapper div;
			
			$('.overlay').css('height', wrapperHeight)
			
			if (overlayed)
			{
				btnClose.hide();
				overlay.fadeOut(800);
				overlayed = false;
				
				if($.browser.msie)
				setTimeout(function() {videoObjects.css('visibility', 'visible')}, 800);
				
				if($.browser.msie && $.browser.version <= 6)
				setTimeout(function() {selectObjects.css('visibility', 'visible')}, 800);
			
			} else {
				overlay.fadeTo(800,0.8, function() { btnClose.show() } );
				overlayed = true;
				
				if($.browser.msie)
				videoObjects.css('visibility', 'hidden');
				if($.browser.msie && $.browser.version <= 6)
				selectObjects.css('visibility', 'hidden');
				
			}
			
			slidingPanel.animate({width: 'toggle'}, 800);	
		}
	}
});

/*
 * loadVideo 
 *
 *
 */
function loadVideo(node, options) {
var player;
var defaults = {
"fullscreen":false,
"flowplayer":"/lofi/scripts/flowplayer.commercial-3.1.5.swf",
"controls":"/lofi/scripts/flowplayer.controls-3.1.5.swf",
"captions":"/lofi/scripts/flowplayer.captions-3.1.4.swf",
"content":"/lofi/scripts/flowplayer.content-3.1.0.swf",
"controls":"/lofi/scripts/flowplayer.controls-3.1.5.swf",
"backgroundGradient":"low",
"key":"#@8233f84a64c29263cf3",
"wmode":"opaque",
"unload":true
	};
	var options = $.extend(defaults, options);
		
	if (node) {
		var container = $('#' + node);
		
		if (supports_flash()) {
			var contents = $('#' + node).clone();
			
			player = $f(node,
			{
				src:options.flowplayer,
				cachebusting:false,
				width:options.width,
				height:options.height,
				wmode:options.wmode,
				allowfullscreen:false,
				version:[9, 115], // We need at least this Flash version
				bgcolor:"#000",
				onFail:function() {
					/*  We should not get here since we know we
						have Flash support. If we do then remove
						the default message and replace with image. */
					container.empty().append(contents.html());
				}
			},
			{
				key:options.key,
				plugins:{
					controls : {
						url:options.controls,
						fullscreen: false
					},
					content:{
						url:options.content,
						height:40,
						bottom:26,
						border:0,
						backgroundColor:'transparent',
						backgroundGradient:'none',
						style:{
							body:{
								textAlign:'center',
								fontSize:14,
								fontFamily:'Arial',
								color:'#ffffff'
							}
						}
					},
					captions:{
						url:options.captions,
						captionTarget:'content',
						button:null
					}
				},
				clip:{
					url:options.source,
					title:options.title,
					captionUrl:(options.subtitles) ? options.subtitles : null,
					autoPlay:true,
					autoBuffering:false,
					scaling:'scale',
					onFinish: function() {
						if (options.unload) {
							var fp = this;
							
							setTimeout(function() {
								fp.unload();
							}, 1000); // Wait a second to unload
						}
						
						if(options.onFinish)
							options.onFinish();
					}
				},
				canvas:{
					backgroundColor:'#000',
					backgroundGradient:options.backgroundGradient // Match the backgound
				},
				play:{
					/*
					relative path to the play button, this can be a JPG, PNG or SWF file.
					NOTE: the button can only be changed in the commercial versions
					*/
					//url: 'images/interface/play-again.png',
					opacity: 0,
					replayLabel:null // label text at end of video clip
				},
				onError: function() {
					this.unload();
				}
			}).load();
		} else if (supports_h264()) {
			var playerId = node + '_api';
			
			container.children().hide();
			container.append($.nano('<video id="' + playerId + '"' +
											'controls="controls"' +
											'preload="auto"' +
											'width="{width}"' + // XXX
											'height="{height}"' +
											'autoplay="autoplay">' +
										'<source src="{source}" type="video/mp4; codecs=\'avc1.42E01E, mp4a.40.2\'" />' +
									'</video>' +
									'<div class="video_controls" rel="' + playerId + '">' +
										 '<ul class="video_buttons">' +
											'<li class="video_play"><a href="#">Play</a></li>' +
											'<li class="video_sound"><a href="#">Sound</a></li>' +
										 '</ul>' +
										 '<div class="video_progress">' +								
											 '<div class="video_progressBar"></div>' +
											 '<div class="video_scrubber"></div>' +
										 '</div>' +
									'</div>', options));
			
			var video = document.getElementById(playerId); // Autoplay for iPad
			
			video.load();
			initVideoPlayButtons(); //call html5 skin function
			video.play();
			
			if (options.subtitles)
				loadTTML('#' + node, options.subtitles);
			
			player = $('#' + playerId);
			
			player.bind('ended', function() {
				if (options.unload) {
					setTimeout(function() {
						player.remove();
						
						$('.video_controls').remove(); //Remove video controls
						
						if ($('#subtitles_container').length)
							$('#subtitles_container').remove();
							
						container.children().show();
					}, 1000); // Wait a second to unload
				}
				
				if(options.onFinish)
					options.onFinish();
			});
		}
	}
	
	return player;
}

/*
 * unloadVideo 
 *
 *
 */
function unloadVideo(node) {
	if (node) {
		if (supports_flash()) {
			var fp = $f(node);
			
			if (fp)
				fp.unload();
		} else if (supports_h264())
			$('video', '#' + node).trigger('ended');
	}
}

/*
 * Adding text for Locate Dealer field
 *
 *
 */
$(document).ready(function(){
	var default_value = $('.locate-search label[for=EnterPostcode]').text();
	var locateDealerField = '.locate-search .text-field';
	
	$(locateDealerField).attr('value', default_value);
	$(locateDealerField).focus(function() {
		if(this.value == default_value)
			this.value = '';					
	})
	$(locateDealerField).blur(function() {
		if(this.value == '')
			this.value = default_value;
	})
});

/*
 * JaguarAJAXLoader (singleton)
 *
 * Loads and XML/JSON/TXT data type returning the result to the callback
 *
 */ 
var jaguarAJAXLoader = new function JaguarMobileAJAXLoader() {
	/**
	 * Private members
	 */
	var _TIMEOUT = 10000; // 10 seconds
	
	/**
	 * Retieves the data from the URL formatted according to the
	 * XML 'dataType' and return it to the specified callback
	 * function on obj.
	 *
	 */
	this.retrieve = function(obj, callback, url, options)
	{
		/**
		 * Private members
		 */
		var defaults = {
			dataType: 'xml',
			async: true,
			contentType: 'application/x-www-form-urlencoded'
		};
		var options = $.extend(defaults, options);
		var contentType = options.contentType;
		
		switch(options.dataType)
		{
			case 'json':
			  contentType: "application/json; charset=utf-8";
			  break;
		}
		
		$.ajax({
			type: "GET",
			url: url,
			cache: true,
			dataType: options.dataType,
			timeout: _TIMEOUT,
			contentType: contentType,
			async: true,
   			success: function(data) {
				callback.call(obj, data); // Run the calback in its original context
    		},
			error: function (objAJAXRequest, strError) {
				callback.call(obj, null); // Do it anyway but empty handed
			}
		});
	}
}

/*
 * loadTTML
 *
 * Requires URL to TTML subtitle file.
 *
 */ 
function loadTTML(id, xmlUrl) {
	/*
	 * Initialize loadTTML
	 *
	 */
	function initialize(xml)
	{
		var captions = new Array(); // <p begin="00:00:00" end="00:00:04">All New XJ Touch-screen</p>
		
		$(xml).find('p').each(function(index) {
			captions[index] = new Array();
			captions[index][0] = $(this).text();
			captions[index][1] = convertTTMLTime($(this).attr('begin'));
			captions[index][2] = convertTTMLTime($(this).attr('end'));
		});
		
		var container = $('<div/>', {
			'id':'subtitles_container'
		}).append($('<div/>', {
			'id':'subtitles'
		}));
		
		$(id).append(container);
		
		var subtitles = $('#subtitles'); // Cached reference
		
		if (supports_h264()) { // HTML5			
			$('video', id).bind('timeupdate', function() {
				var now = this.currentTime;
				
				$.each(captions, function(i, caption){
					if(now >= caption[1] && now <= caption[2]) {
						subtitles.text(caption[0]);
						
						return false;
					}
					
					subtitles.html('');
					
					return true;
				});
			});
		}
	}
	
	/*
	 * convertTTMLTime
	 *
	 */
	function convertTTMLTime(ttmlTime) {
		var duration = ttmlTime.split(':', 3) // 00:00:00
		
		// Return in seconds
		return parseInt(duration[0] * 3600, 10) + // hour
					parseInt(duration[1] * 60, 10) + // minute
						parseInt(duration[2], 10);  // seconds
	}
	
	jaguarAJAXLoader.retrieve(this, initialize, xmlUrl); // Retrieve content via REST
}

/*
 * HTML5 video skin
 *
 *
 */	
function findVideoElement(el) {
    var parentControls = $(el).parents('.video_controls[rel]');
	
    if (parentControls.length == 0)
        return $('video[id=]');
    else
        return $('#' + parentControls.attr('rel'));
}

function findControls(el) {
    if ($(el).attr('id') == "")
        return $('.video_controls:first');
	else
        return $('.video_controls[rel=' + $(el).attr('id') + ']');
}

function findEventPosition(e) {
    var $_target = $(e.currentTarget);
    var _offset = $_target.offset();
    var _relativeX = e.pageX - _offset.left;
    var _relativeY = e.pageY - _offset.top;
    
    return {left:_relativeX, top:_relativeY};
}

function initVideoPlayButtons() {
	if(supports_h264()) {          
	  var $_controls =  $('.video_controls'); 
	  $_controls.show(); // If support h264 show video controls 
	} else
	  return false;
	
	initVideoProgress(); // Start video progress bars
	
	$('.video_play a').each(function () {
		var $_video = findVideoElement(this);
		var $_videoSize = {width:$_video.width(), height:$_video.height()}; // Find video dimensions
		
		$_video.attr('controls', ''); // Remove default controls if JS enabled
		
		/* Bind The Click Events */
		$(this).click(function (e) {
			e.preventDefault();
			
			$_video.each(function (index, _video) {
				if (_video.paused) {
					_video.play();
				} else {
					_video.pause();
				}
			});
		});
		
		/* Set Initial State */
		if ($_video.length > 0) {
			if ($_video.get(0).paused)
				$(this).removeClass('active');
			else
				$(this).addClass('active');
		}
	});
	
    /* Bind Video State Changes */
    $('video').each(function (index, _video) {
        var $_controls = findControls(_video);
        var $_playBtn = $_controls.find('.video_play a');
		var $_soundBtn= $_controls.find('.video_sound a');

        $(_video).bind('play', function () {
			$_playBtn.addClass('active');
        }).bind('pause', function () {
            $_playBtn.removeClass('active');
		});
		
		$_soundBtn.bind('click', function(e) {
			e.preventDefault();
			if (_video.muted) {
				_video.muted=false;
				 $_soundBtn.removeClass('active');
			} else {
				_video.muted=true;
				$_soundBtn.addClass('active');
			}
		});
	});
};

function initVideoProgress() {
	$('video').each(function(index, _video) {
		var $_controls = findControls(_video);
		var $_progressBars = $_controls.find('.video_progressBar');
		var $_scrubber = $_controls.find('.video_scrubber');
		
		/* Bind The timeupdate Event For The Video */
		$(_video).bind('timeupdate', function() {
		  var percentage=0;
		
		  if ((typeof this.duration != "undefined") && (this.duration > 0))
				percentage=100 * this.currentTime / this.duration;
		
		  $_progressBars.css("width", percentage+"%");
		  $_scrubber.css("left", percentage+"%");
		});
    });

	$('.video_progress').each(function() {
		var $_video = findVideoElement(this);
		
		/* Bind The click Events On The Progress Bar Track */
		$(this).click(function(e) {
			var _position = findEventPosition(e);
			var _percentage = 100 * _position.left / $(this).width();
					 
			/* Move The Video(s) To The New Position */
			$_video.each(function(index, _video) {		
				if (typeof _video.duration != "undefined") {
					if (_video.duration > 0)
						  _video.currentTime = _video.duration*_percentage / 100;
				}
			});
		});
	});
}

/*
 * functions
 *
 *
 *
 */
$(document).ready(function () {
	$('body').addClass('hasJS');
    var px = 'px';

    // function makes the whole LI clickable (if all the links inside point to the same URL)
    $.fn.clickable = function () {
        var LIs = $(this).children('li');

        LIs.addClass('clickable').click(function () {
        	var thisLink = $(this).find("a:first");
        	if ($(thisLink).attr('target') == "_blank") {
        		window.open($(thisLink).attr('href'));
        	} else {
        		window.location = $(thisLink).attr("href");
        	}
            return false
        });

        for (i = 0; i < LIs.length; i++) {
            var links = $(LIs[i]).find('a');
			
            for (j = 1; j < links.length; j++) {
                if ($(links[0]).attr('href') !== $(links[j]).attr('href')) {
                    $(LIs[i]).removeClass('clickable').unbind('click');
                    break;
                };
            };
        };
    }
 
 	// Setting up carousel
    $.fn.Carousel = function (speed) {
        var theCarousel = this;
        var thumbN = 4;
		var leftIndent = 0;
        var total = $(this).children('li').length;
        var thumbWidth = $(this).find('>li').outerWidth() + 15;
        var visiblePart = thumbWidth * thumbN; // carousel width
        var totalWidth = thumbWidth * total; // total carousel width (all thumbnails)
		
		/*
		 * slide
		 *
		 */
		function slide(where, speed) { // Carousel
			if (where == 'right') {
				if (totalWidth + leftIndent > visiblePart)
					leftIndent -= visiblePart;
			}
			else {
				if (leftIndent < 0)
					leftIndent += visiblePart;
			}
			
			$(theCarousel).animate({ // Animating carousel and then disabling arrows if necessary
				'left': leftIndent
			}, speed, function () {
				disable();
			});
		};
		
		/*
		 * disable
		 *
		 * Disabling arrows
		 */
		function disable() {
			if (totalWidth + leftIndent <= visiblePart)
				$('.carousel .next span').addClass('disabled');
			else
				$('.carousel .next span').removeClass('disabled');
	
			if (leftIndent == 0)
				$('.carousel .prev span').addClass('disabled');
			else
				$('.carousel .prev span').removeClass('disabled');
		}

        // Adding wrapper and previous/next arrows
        $(this).wrap('<div class="carousel">').wrap('<div class="carousel_inner">');
        $('<a href="#" class="prev"><span>' + sbPreviousLabel + '</span></a>').click(function () {
            slide('left', speed);
            return false;
        }).prependTo('.carousel');
        $('<a href="#" class="next"><span>' + sbNextLabel + '</span></a>').click(function () {
            slide('right', speed);
            return false;
        }).appendTo('.carousel');
		
		// Hover event on the thumbnails
		$(theCarousel).find('li div').hide();
		$(theCarousel).find('li').hover(function() { 
			$(this).find('div').fadeIn();
		}, function() {
			$(this).find('div').fadeOut();
		});
		
		disable();
    };
	
    $('.breadcrumbs').css({'visibility':'hidden'});
    
	// Back link
	var subnav = $('.col-two .subnav');
	
	if (subnav.children().length > 0)
		subnav.children(":first").addClass('first-child')
	else
		$(subnav).replaceWith($('<ul />').addClass($(subnav).attr('class')));
	
	if (subnav.attr('class') && subnav.attr('class').indexOf("noback") == -1)
		$('<li class="back"><a href="#"><span>' +
			sbBackLabel +
		  '</span></a></li>').prependTo($('.subnav, .nameplate-nav'));
		
	$('.subnav .back a').live("click", (function () {
		if (document.referrer && document.referrer.indexOf('jaguar.com') > -1)									
			history.go(-1); // If we're inside jaguar then go back a page
		else {
			var pathname = window.location.pathname; //i.e /gb/en/experience/
			
			if(endsWith(pathname, '/'))
				pathname = pathname.substring(0, pathname.length - 1); // i.e. /gb/en/experience
			
			window.location.pathname = pathname.substring(0, pathname.lastIndexOf('/')) + '/'; // i.e. /gb/en/
		}
		
		return false;
	}));
     
	// Unobtrusive print button; does not appear if javascript is not enabled
	(function ($) { 
		if($('#print')) { // Check to see if print button is available
			$('#print').css('display', 'block'); // Show the hidden print button
			$('.print-btn').bind('click', function() { // If true bind a print window 
				window.print();
			});
		}
    })(jQuery);
	
    // Market selector
    $('.countries h3').click(function () {
        if (!($('.countries div').is(':animated'))) {
            $(this).next("div").animate({
                height: 'toggle'
            }, 600).siblings("div:visible").slideToggle(600);
            $(this).toggleClass("active");
            $(this).siblings("h3").removeClass("active");
        }
    })
	
    // DWS post results in an overlay
	$('.overlaySearch').submit(sendForm); // Select our form to target
	
	function sendForm() {
		formUrl = $(this).attr('action').split('?'); // Get form action string
		formData = $(this).serialize(); // Get form data
		$('div#dialog').formOverlay
			(formUrl[0] + '?' +  formData, {'overlayWidth':854,'overlayHeight':558}); // Create dialog using
		
		return false;
	}

    $('.carousel_ul').Carousel(500);
    $('.carousel_ul').clickable();
    $('.listing').clickable();
    $('.article-list').clickable();
	
	$('a.popup').click(function (e) {
		var _FEATURES = 'loction=yes,statusbar=0,menubar=0,resizable=yes,scrollbars=yes,dependent=yes,directories=no';
		var coords = $(this).attr('coords').split(","); // Take the size from the coords attribute
		
		e.preventDefault(); // Removed this events default action
		
		function popup(url, target, popupWidth, popupHeight) {
			if (url != undefined) {	
				popupWidth = (popupWidth) ? parseInt(popupWidth, 10) : '625'; // Radix 10
				popupHeight = (popupHeight) ? parseInt(popupHeight, 10) : '685';
				target = (target) ? target : '_blank';
				
				window.open(url, target, _FEATURES + ',width=' + popupWidth + ',height=' + popupHeight);
			}
			
			return false;
		}
		
        return popup($(this).attr('href'), $(this).attr('target'), coords[0], coords[1]);
	});
	
	$('a[href^=event:hotspot]').click(function(e){
		e.preventDefault();
	});
	
	// Hotspot / Glossary / Tooltips
    if($('a[href^=event:hotspot]')) { // Check if tooltips exists
		var hotCache = []; // hotspot cache
		var hotTip = $('<div id="hotTip"></div>').hide().appendTo('body'); // Create tooltip holder
		
		$('a[href^=event:hotspot]').removeAttr("title"); // Remove title attribute so they dont appear above tooltip firefox/chrome etc
		$('a[href^=event:hotspot]').hover(function () {
		    var RESTUrl = '/rest/item/hotspot/'; // REST service
      		//var RESTUrl = 'xml/'; // REST service
			var hotTipId = $(this).attr('href').split(',')[1]; // Get hotpsot id
			
			//getCacheHotTip(hotTipId, RESTUrl + hotTipId ); // Get hotspots from rest call
			getCacheHotTip(hotTipId, RESTUrl + hotTipId); // Get hotspots from rest call
			
			hotTip.fadeIn('fast');
		},
		function () {
			hotTip.hide(); // Hide tooltip
		}).mousemove(function (e) {
			var mouseX = e.pageX + 20 // Get X coordinates
			var mouseY = e.pageY + 20 // Get Y coordinates
			var tipWidth = hotTip.width(); // Tooltip width	
			var tipHeight = hotTip.height(); // Tooltip height
			
			// Distance of tooltip form right side of the page
			var tipX = $(window).width() - (mouseX + tipWidth);
			var tipY = $(window).width() - (mouseY + tipHeight);
		
			if (tipX < 20) // If tooltip greater than the viewport X value
				mouseX = e.pageX - tipWidth - 20;
		
			if (tipY < 20) // If tooltip greater than the viewport Y value
				mouseY = e.pageY - tipHeight - 20;
		
			hotTip.css({
				top: mouseY - (tipHeight/2),
				left: mouseX
			}); // Align our tooltip from mouse position
		});
		
		// Get Hotspots results
		function getCacheHotTip(id, RESTUrl) {
			(hotCache[id]) ? 
					hotTip.html(hotCache[id]) :  // If cached use cached version
						getHotTip(id, RESTUrl) ; // Else get new tooltip	
		}	
		
		// Make new hotspots rest call
		function getHotTip(id, RESTUrl) {
			function initialize(xml) {
				var hotspots = []; // Hotspots/ tooltips array
		
				$(xml).find('link').each(function (index) {
					hotspots[index] = {
						'title': $(this).find('title').text(), 
						'teaser': $(this).find('teaser').text(),
						'imageUrl': $(this).find('imageUrl').text()
					};
					
					var tipHtml = '<div class="tip-inner">' +
									'<h4>' + hotspots[index].title  + '</h4>' +
									'<p>'  + hotspots[index].teaser + '</p>'  +
							  	  '</div>';
					
					hotTip.html(tipHtml);
					hotCache[id] = tipHtml; // Cache results
				});
			}
		     
			jaguarAJAXLoader.retrieve(this, initialize, RESTUrl); // Retrieve content via REST
		}
	
	}
	
	/*
	 * formOverlay
	 *
	 * Flash cover method
	 */
	formOverlay = function(url, x, y)
	{
		$('div#dialog').formOverlay(url, {'overlayWidth':x, 'overlayHeight':y});
	}
	
	/*
	 * formOverlay
	 *
	 *
	 */
	$.fn.formOverlay = function(url, options) {
		var defaults = {
			'overlayWidth':858,
			'overlayHeight':660,
			'background':(!window.XMLHttpRequest) ?
							'/lofi/images/interface/overlay/background-ie6.png' :
								'/lofi/images/interface/overlay/background.png',
			'offset':16};  // Height plus header, footer etc
		var options = $.extend(defaults, options);
		var overlay = this;
		var container = $('<div>').attr('id','iframe-container').css({'height':options.overlayHeight - 60 + 'px', // - Scrollbars
																	  'width':options.overlayWidth - 42 + 'px',
																	  'margin':'30px auto'});
		var iframe = $('<iframe>').attr({'src': url,
										'allowTransparency':'true',
										'frameborder':0,
										'id':'iframe-overlay',
										'style':'background-color:transparent;display:block;height:100%;width:100%;'});
		
		iframe.appendTo(container);
		overlay.html(container); // Inject the form into the overlay
		formDialog($(this), options);
	}
	
	/*
	 * hotspotOverlay
	 *
	 *
	 */
	$.fn.hotspotOverlay = function(url, options) {
		var defaults = {
			'overlayWidth':486,
			'overlayHeight':310,
			'background':(!window.XMLHttpRequest) ?
							'/lofi/images/interface/overlay/background-blk-ie6.png' :
								'/lofi/images/interface/overlay/background-blk.png',
			'offset':0,
			'onClose':function() { unloadVideo('player0') }, // For IE
			'onOpen':function() { // Autoplay for HTML5 video in overlay
				var player = document.getElementById('player0_api');
				
			     $('body').addClass('hotspotOverlay'); //Add hotspotOverlay class, so we can target hotspots overlays only in global.css
				
				if (player.tagName.toUpperCase() == 'VIDEO') {
					player.load();
					player.play();
				}
			}};
		var options = $.extend(defaults, options);
		var overlay = this;
		var container = '<div id="player0" style="margin:20px auto;width:462px;height:261px;"></div>';
		
		overlay.html(container); // Inject the player wrapper into the overlay
		loadVideo('player0', {"width":"462",
								"height":"261",
								"title":"",
								"source":url,
								"backgroundGradient":"none",
								"unload":false}); // Don't unload video
		
		formDialog($(this), options);
	}
	
	function parseCoords(coords) {
		var coordinates = coords.split(",");
		
		return {'overlayWidth':(coordinates[0]) ? parseInt(coordinates[0], 10) : undefined, // Radix 10
				'overlayHeight':(coordinates[1]) ? parseInt(coordinates[1], 10) : undefined};
	}
	
	$('a.dialog').click(function (e) {
		$('div#dialog').formOverlay($(this).attr('href'), parseCoords($(this).attr('coords')));
		e.preventDefault(); // Removed the event's default action
		
		return false;
	});
	
	if ($('a.hotspot-overlay').length) { // Unhide the watch video links
		if (supports_media($('a.hotspot-overlay').attr('href')))
			$('a.hotspot-overlay').show();
	}
	
	$('a.hotspot-overlay').click(function (e) {
		$('div#dialog').hotspotOverlay($(this).attr('href'), parseCoords($(this).attr('coords')));
		e.preventDefault();
		
		return false;
	});
	
	formDialog = function(node, options)
	{
		var overlay = node;
		
		overlay.dialog({'height':options.overlayHeight, // Calls the jQueryUI Dialog plugin
						'width':options.overlayWidth,
						'modal':true,
						'draggable':false,
						'position':'center',
						'closeText':'',
						'open':function(event, ui) {
							var dialog = $('.ui-dialog');
							var height = dialog.height();
							
							$('.ui-widget-overlay').css('opacity', '0');
							dialog.prepend($('<img>').attr({ // Because we can't resize a background image
								'src':options.background,
								'width':options.overlayWidth,
								'height':height + options.offset,
								'id':'background'
							}));
							$('.ui-widget-overlay').fadeTo('slow', 0.75);
							
							if(options.onOpen)
								options.onOpen();
						},
						'close':function(event, ui) {
							overlay.dialog("destroy");
							overlay.empty();
							
							if(options.onClose)
								options.onClose();
						}});
		
		$(window).resize(function() { overlay.dialog("option", "position", "center"); });
	}
	
	// Hotspots tabs
    $('.hotspots .gallery-subnav a').click(function () {
		if (!startsWith($(this).attr('href'), "#")) // Some nav items may be links
			return true;
		
        tabs($(this));
		
        return false;
    })
	
    // Gallery tabs function
    function tabs(obj) {
		var ids = obj.attr('rel');
		
        $('.hotspots .holder').hide();
        $('.hotspots .gallery-subnav li').removeClass('active');
        $('#' + ids).show();
        obj.parent().addClass('active');
    }
    tabs($('.selected'));
	
	// Dealer locator US state selector
	setStateSelector = function(isChange) {
		if ($('#dealerLocatorSelector').val() == 'ct')  {
			$('#stateSelector').show();
			$('#dlTextControlUS').hide();
		}
		else {
			$('#stateSelector').hide();
			
			if (isChange)
				$('#dlTextControlUS').show().attr( 'value', '' );
			else
				$('#dlTextControlUS').show();
		}
	}
	
	setStateSelector(false);
	$('#dealerLocatorSelector').change
		(function() {setStateSelector(true)});
});


/*
 *	Fix IE6 image scaling
 *
 *	This anonymous jQuery function will set up a custom event listener for certain elements that
 *	need image scaling fixed for IE6, and perform the fix. The event is called like so:
 *
 *	$('div.galleryview div.panel img.mainpic').trigger('fixScaleEvent);
 *
 *	(Obviously, the selector should be replaced with the element to be fixed, and that element should be added below)
 */

$(function(){
	$('img').live("fixScaleEvent", function(e){
		if (isIE6 == true) { // Only do any of this in IE6. The check that determines the value of this variable at the top of this script file.
			/*var _src = $(this).attr('src'); // Get the src of the image
			if (_src.indexOf('1x1.gif') == -1 ) {
				// Use the AlphaImageLoader filter to fix the scaling. Note: This acts as a kind of background image
				$(this).css({"filter": "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"+_src+"', sizingMethod='scale')"});
				// Replace the actual image with a transparent shim so that the new version shows through
				$(this).attr('src', '/lofi/images/interface/1x1.gif'); 
				// Prevent the IE6 image toolbar from appearing
				$(this).attr('galleryimg', 'no'); 
				// Prevent any other default actions
				return false; 
			}*/
		}
	});
})



/*
 * Flash warning message
 * 
 * This will conditionally display a warning disclaimer at the bottom of the page
 * to users who do not have the Flash Player plugin installed, or whose version
 * of the Flash Player plugin is too old
 */

$(function(){
	var meetsRequirements = supports_flash();
	if (meetsRequirements === true) {
		$('p.flash-reqrd').hide();
	}
})
