//------------------------------------
//	HOME.JS
//	Author: 	Engage Interactive
//	Requires:	jquery 1.5
//	Version:	0.1
//------------------------------------


Cufon.replace('#key-areas label');


////////////////////////////
// BEGIN JQUERY

$(function(){
	
	//////////////////////////
	// Trigger popup on slideshow panel links 
	
	// Seasonal specials
	$('#seasonal_specials_link').location({
		url:		'/menus/[location]/summer-specials',
		mainTitle:	'Our menus',
		intro:		'Our menus can vary between restaurants so please choose which Strada you would like to see the menu for',
		formWrapperClass: 	'form-wrapper'
	});
	

	//////////////////////////
	// Find your nearest
	
	$('#find-a-strada').submit(function(e){
	
		$.location({
			url:		'/italian-restaurant/[location]',
			searchTerm:	$(this).find('#query').val(),
			mainTitle:	'Find a Strada',
			intro:		'To find your nearest Strada, please enter a search term below or choose from the list.',
			formWrapperClass: 	'form-wrapper'
		});
		
		e.preventDefault();
	});

	//////////////////////////
	// Slideshow
	
	function slideShow(){
		
		// Objects
		var $slideshow = $('#slideshow');
		var $slider = $('#slideshow-slide');
		var $slide = new Array();
		var $a = $slideshow.find('nav a');
		var $n;
		
		// Variables
		var t = $slider.find('.slide').length;
		var w = $slideshow.width() - 8;
		var h = $('#slideshow-window').height();
		var nav = '';
		var timer = {};
		var c = 1;
		
		// Plugins
		$.fn.loadBg = function(callback) {
			
			return this.each(function(){
			
				$this = $(this);
				
				// Create image object
				var img = new Image();
				
				// Get the url
				var url = $this.data('bg');
				
				// Load the image
				$(img).load(function(){
				
					// Set background image
					$this.css({
						'background-image':	'url(' + url + ')'
					}).data('loaded',true);
					
					// Callback
					if( callback ) callback.apply($this);
					
				}).attr('src', url);
		
			});
			
			console.log('loading');

		};
		
		// Thumbnail plugin
		$.fn.thumbnail = function(callback) {
			
			return this.each(function(){
			
				// Objects
				var $this = $(this);
				var $ts = $slider.find('.slide:eq(' + ( $this.text() - 1 ) + ')');
				var $thumb;
				
				var url = $ts.data('bg');
				
				//console.log(x + ' ' + y + ' ' + url);
				
				$this.hover(function(){
				
					var x = $this.offset().left - 240;
					var y = $this.offset().top - 40;
				
					$thumb = $('<div/>',{
						'id':	'slideshow_thumb',
						'css':	{
							'top':	y,
							'left':	x
						},
						'html':	'<img src="' + url + '" alt="Thumbnail" width="212" height="80"><span></span>'
					}).appendTo('body');
					
					if( !$ts.data('loaded') ){
					
						setTimeout(function(){
							if( !$ts.data('loaded') ) $thumb.addClass('loading');
						},200);
						
						$ts.loadBg(function(){
							$thumb.removeClass('loading').find('img').fadeIn(200);
						});
					}else{
						$thumb.find('img').show();
					}
					
				},function(){
					$('#slideshow_thumb').remove();
				});
				
			});

		};
		
		// Create array of slide objects and the nav
		for( i = 1; i <= t; i++ ){
		
			// Add to the array
			$slide[i] = $slider.find('.slide:eq(' + ( i - 1 ) + ')');
			
			// Generate HTML
			nav = nav + '<li><a href="#" title="View this slide">' + i + '</a></li>';
			
			// Finished the loop
			if( i == t ){
			
				// Create the nav
				$n = $('<ul/>',{
					'html':	nav
				}).appendTo($slideshow.find('nav'));
				
				$n.css({
					'margin-top':	0 - Math.round( $n.outerHeight() / 2 )
				}).find('li:first a').addClass('on');
				
			}
		}
		
		
		//////////////////////////
		// NOT IPAD
		
		if( !$('html').hasClass('ipad') ){
		
			// Mouse
			var mooseBan = true;
			
			// Settings
			var pause = 4;
			var s = 800;
			var e = 'easeInOutQuart';
			
			// Set up thumbnail hover
			$n.find('a').thumbnail();
			
			// Go to function
			function goTo(dir,infinite){
			
				mooseBan = true;
			
				var $old = $slider.find('.slide:visible');
				var $new = $slide[c];
				var y = 0;
			
				// Get the slider ready
				if( infinite ){
				
					if( dir == 'down' ){
					
						// Clone the last slide and put it in the first position
						$new.clone().prependTo($slider).addClass('delete').show();
						
						// Position the slider in the now second position
						$slider.css({
							'top':	0 - h
						});
						
					}else{
					
						// Clone the first slide and put it in the last position
						$new.clone().appendTo($slider).addClass('delete').show();
					
						// Position the slider in the now second to last position
						$slider.css({
							'top':	0 - h
						});
					
						// Set final y to minus double the height
						y = 0 - ( h * 2 );
					}
				
				}else{
				
					if( dir == 'down' ){
					
						$slider.css({
							'top':	0 - h
						});
						
					}else{
						y = 0 - h;
					}
				
				}
			
				// Show the new slide
				$new.show();
				
				// Animate
				
				$slider.animate({
					'top':	y
				},s,e,function(){
					$old.hide();
					$slider.removeAttr('style');
					$slider.find('.delete').remove();
					mooseBan = false;
				});
	
			
				// Set nav on state
				$n.find('a.on').removeClass('on');
				$n.find('li:eq(' + ( c - 1 ) + ') a').addClass('on');
			}
			
			
			//////////////////////////
			// THE CLEVER BIT
			
			// Load the first slide
			$slide[1].loadBg(function(){
	
				// Stop loading
				$slideshow.removeClass('loading');
			
				$(this).fadeIn(100,function(){
					mooseBan = false;
				});
				
				auto();
				
			});
			
			
			// Automatically slide
			function auto(){
			
				var p = $slide[c].data('pause');
			
				if( p == undefined ){
					p = pause;
				}
			
				timer = $.timer( ( p * 1000 ),function(){
				
					$.clearTimer(timer);
				
					if( !$slideshow.hasClass('loading') ) $slideshow.find('a.down').click();
					auto();
				
				});
				
			}
			
			// Hovering
			$slideshow.bind({
				'mousemove':	function(){
					$.clearTimer(timer);
					$slideshow.unbind('mousemove');
				},
				'mouseenter':	function(){
					$.clearTimer(timer);
				},
				'mouseleave':	function(){
					auto();
				}
			});
			
			
			// Clicking of links
			$a.live('click',function(e){
			
				if( !mooseBan && !$(this).hasClass('on') ){
	
					var dir = null;
					var infinite = false;
				
					if( $(this).hasClass('arrow') ){
						
						if( $(this).hasClass('down') ){
							c++;
							dir = 'up';
						}else{
							c--;
							dir = 'down';
						}
	
						if( c > t ){
							c = 1;
							infinite = true;
						}else if( c < 1 ){
							c = t;
							infinite = true;
						}
						
					}else{
						
						var num = $(this).text();
						var dir = c > num ? 'down' : 'up';
						c = num;
										
					}
					
					if( $slide[c].data('loaded') == true ){
						goTo(dir,infinite);
					}else{
					
						// Set loading
						setTimeout(function(){
							if( !$this.data('loaded') ) $slideshow.addClass('loading');
						},200);
					
						$slide[c].loadBg(function(){
							goTo(dir,infinite);
							
							// Stop loading
							$slideshow.removeClass('loading');
							
						});
					}
				
				}
				
				e.preventDefault();
				
			});
			
		}else{
		
			//////////////////////////
			// IPAD
			
			// Variables
			c = 0;
			var speed = 200;
			
			// Load all the images
			var i = 0;
			
			function loadAll(){
				$slider.find('.slide:eq(' + i + ')').loadBg(function(){
				
					i++;
					
					if( i < t ){
						loadAll();
					}
					
					if( i == 1 ){
					
						// Add a message in that goes after first swipe
						$('<span/>',{
							'id':	'iPad'
						}).appendTo($slideshow);
					
					}
				
				});
			}
			
			loadAll();
			
			// Initiate plugin
			$slideshow.swipe({
				triggerOnTouchEnd:	true,	
				swipeStatus:		swipeStatus,
				allowPageScroll:	'vertical',
				threshold:			100
			});

			function swipeStatus(event, phase, direction, distance){
			
				//If we are moving before swipe, and we are going Lor R in X mode, or U or D in Y mode then drag.
				
				if( phase == 'move' && ( direction == 'left' || direction == 'right' ) ){
				
					var duration=0;
					
					if ( direction == 'left' ){
					
						scrollImages((w * c) + distance, duration);
						
					}else if( direction == 'right' ){
					
						scrollImages((w * c) - distance, duration);
						
					}
					
				}else if( phase == 'cancel' ){
				
					scrollImages(w * c, speed);
					
				}else if( phase == 'end' ){
				
					if( direction == 'right' ){
					
						previousImage();
						
					}else if( direction == 'left' ){
					
						nextImage();
					}
					
					// Set nav on state
					$n.find('a.on').removeClass('on');
					$n.find('li:eq(' + c + ') a').addClass('on');
					
				}
				
			}
			
			function previousImage(){
			
				c = Math.max(c-1, 0);
				scrollImages( w * c, speed);
				
			}
		
			function nextImage(){
			
				c = Math.min(c+1, t-1);
				scrollImages( w * c, speed);
				
			}
				
			
			// Manually update the position of the imgs on drag
			function scrollImages(distance, duration){
			
				// Set duration
				$slider.css('-webkit-transition-duration', ( duration / 1000 ).toFixed(1) + 's');
				
				//inverse the number we set in the css
				var value = ( distance < 0 ? '' : '-') + Math.abs(distance).toString();
				
				// Set position
				$slider.css({
					'-webkit-transform':	'translate3d(' + value + 'px,0px,0px)',
					'left':					0
				});
				
			}
		
		}
		
		// Clicking a slide
		$slider.find('.image').click(function(e){
			if($(this).hasClass('location_select')){
				$(this).find('a').click();
			}
			else{
				var url = $(this).find('a').attr('href');
				if( $(this).hasClass('external') ){
					window.open(url);
				}else{
					window.location = url;
				}
				e.preventDefault();
			}
		});
		
	}
	
	slideShow();
	
	
	//////////////////////////
	// PROMOTIONS
	
	$('#promotions .cycle').cycle({
		delay:	4
	});
	
	
	//////////////////////////
	// Twitter
	
  	$('#twitter').tweet();

});


//////////////////////////
// PLUGINS

(function($) {

	//////////////////////////
	// CYCLE PLUGIN
	
	$.fn.cycle = function(settings) {
		
		// Settings
		var defaults = {
			easeIn:		'easeInOutExpo',		// Easing for new slide
			easeOut:	'easeInOutExpo',		// Easing for old slide
			speed:		800,					// Anim speed
			pause:		4,						// Between slides in seconds
			delay:		0						// Before start in seconds
		};
		
		var o = $.extend(defaults, settings);
		
		return this.each(function(){
		
			// Objects
			var $this = $(this);					// Targeted element
			var $a = new Array();					// Array to store articles
			var $n = undefined;						// Navigation (eventually)
			
			// Settings
			var e = 'easeInOutExpo';				// Easing
			var s = 800;							// Anim speed
			var d = 4;								// Seconds
			
			// Variables
			var t = $this.find('article').length;	// Total
			var c = 1;								// Current
			var nav = '';							// Nav
			var timer = {};							// Timer
			var mooseBan = false;					// Bad MOOSE!
			
			// Build navigation and article array
			for( i = 1; i <= t; i++ ){
				
				// Article array
				$a[i] = $this.find('article:eq(' + ( i - 1 ) + ')');
				
				// Nav html
				nav = nav + '<li><a href="#">' + i + '</a></li>';
				
				// Are we done yet?
				if( i == t ){
					
					// Build list
					$n = $('<ul/>',{
						'html':	nav
					}).appendTo($this);
					
					// Set first to on
					$this.find('ul li:first a').addClass('on');
					
					// Activate the clicks
					$n.find('a').click(function(e){
					
						if( !$(this).hasClass('on') && !mooseBan ){
							
							c = $(this).text();
							
							goTo();
							
						}
						
						e.preventDefault();
					});
					
					// Show the first slide
					$a[1].show();
					
					// Start slideshow after delay
					setTimeout(function(){
					
						auto();
						
					}, o.delay * 1000 );

				}
			}
			
			// Go To 
			function goTo(){
			
				// Ban that moose!
				mooseBan = true;
				
				// Make sure we're not going outside the range
				if( c > t ){
					c = 1;
				}else if( c < 1 ){
					c = t;
				}
								
				// Old and new slides
				var $old = $this.find('article:visible');
				var $new = $a[c];
				
				// Out with the old
				$old.css({
					'z-index':	1
				}).animate({
					'top':		40,
					'opacity':	0
				},o.speed,o.easeOut,function(){
					$old.removeAttr('style').hide();
				});
				
				// In with the new
				$new.show().css({
					'z-index':	10,
					'top':		-40,
					'opacity':	0
				}).animate({
					'top':		0,
					'opacity':	1
				},o.speed,o.easeIn,function(){
					mooseBan = false;
				});
				
				// Set the nav
				$n.find('li a').removeClass('on');
				$n.find('li:eq(' + ( c - 1 ) + ') a').addClass('on');
			
			}
			
			// Slideshow
			function auto(){
				
				timer = $.timer( ( o.pause * 1000 ),function(){
					
					c++;
					
					goTo();
				
					auto();
					
				});
				
			}
			
			// Hover
			$this.bind({
				'mousemove':	function(){
					$.clearTimer(timer);
					$this.unbind('mousemove');
				},
				'mouseenter':	function(){
					$.clearTimer(timer);
				},
				'mouseleave':	function(){
					auto();
				}
			});
	
		});

	};

})(jQuery);
