//------------------------------------
//	STRADA.JS
//	Author: 	Engage Interactive
//	Requires:	jquery 1.5
//	Version:	0.1
//------------------------------------

//////////////////////////
// CUFON

Cufon.replace('h2, h3, #primary nav a, #footer-content h4, .intro, .cufon, #prizedraw label, #email-only label, #news-content h1, .video h4, #location-content h1, h1.title, .location_nav li a');

Cufon.replace('#menu-navigation ul li a.section', {
	hover: true
});

Cufon.CSS.ready(function(){
	setTimeout(function(){
		$('#content').equalHeights();
	},20);
});


////////////////////////////
// BEGIN JQUERY

$(function(){

	//////////////////////////
	// LOCATION PICKERS
	
	// Locations page
	$('a[href$=italian-restaurants]').location({
		url:		'/italian-restaurant/[location]',
		mainTitle:	'Find a Strada',
		intro:		'Please tell us your current location or choose from the list below',
		formWrapperClass:	'form-wrapper'
	});
	
	// Book online page
	$('a[href$=bookonline]').location({									  	
		url:		'/bookonline/[location]',
		mainTitle:	'Book a table',
		intro:		'Which Strada would you like to book a table at?',
		formWrapperClass: 	'form-wrapper'
	});
	
	// Menu page
	$('a[href$=menus]').location({
		url:		'/menus/[location]',
		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'
	});
	

	//////////////////////////
	// Add classes to lists
	
	$('ul li:first-child').addClass('first');
	$('ul li:last-child').addClass('last');
	$('ul.striped li:even').addClass('even');
	
	
	//////////////////////////
	// DROP DOWNS
	
	$('#key-areas select').dropdown();
	$('#location-info select').dropdown({
		'cta':	'Choose a different restaurant'
	});
	$('#step-1 select').dropdown();
	
	// External link handling
	$('a[href*="http://"]:not([href*="'+location.hostname+'"]):not([class*="internal"]), .external').live('click',function() {
		window.open($(this).attr('href'));
		return false;
	});
	
	
	//////////////////////////
	// GENERIC FORMS
	
	// Stop double click selecting labels
	$('form label').disableSelection();
	
	// Input placeholder replacement for unsupporting browsers
	if( 'placeholder' in document.createElement('input') === false ){
	
		$('input').each(function(){

			var $el = $(this);
			
			// skip if we do not have the placeholder attribute
			if( !$el.is('[placeholder]') )
				return;

			// we cannot do password fields, but supported browsers can
			if( $el.is(':password') )
				return;

			$el.bind('focus.placeholder', function(){
				if( this.value == $el.attr('placeholder' ) )
					$el.val('');
			});
			
			$el.bind('blur.placeholder', function(){
				if(this.value == '')
					$el.val( $el.attr('placeholder') )
            });

            $el.triggerHandler('blur');

			// Prevent incorrect form values being posted
			$el.parents('form').submit(function(){
				$el.triggerHandler('focus.placeholder');
			});
			
		});

	}
	
	
	//////////////////////////
	// PROMOTIONS PAGE
	
	$('a[href=#terms]').showHide({
		'hideText':	'Hide terms &amp; conditions &uarr;'
	});
	
	
	//////////////////////////
	// FOOTER ON LONG PAGES

	if( $(window).height() < $(document).height() ){
	
		$('#credits').addClass('no-border');
		
	}

});


//////////////////////////
// PLUGINS

(function($) {

	//////////////////////////
	// DROP DOWN PLUGIN
	
	$.fn.dropdown = function(settings) {
		
		// Settings
		var defaults = {
			'delay':		200,
			'btnClass':		'drop-down',
			'listClass':	'drop-down-list',
			'prefix':		'dd-',
			'link':			'Find your nearest',
			'cta':			'Choose a restaurant',
			'minHeight':	200,
			'maxHeight':	700,
			'downClass':	'down',
			'upClass':		'up',
			'onClick':		function(){}
		};
		
		var o = $.extend(defaults, settings);

		// Are we on an iPad?
		var isiPad = navigator.userAgent.match(/iPad/i) != null;
		var ua = navigator.userAgent;
		var isiPad = /iPad/i.test(ua) || /iPhone OS 3_1_2/i.test(ua) || /iPhone OS 3_2_2/i.test(ua);
		
		return this.each(function(){

			// Objects
			var $this = $(this);
			var $w = $(window);
			var $d = $(document);
			
			// Variables
			var active = false;
			var hover = false;
			var id = o.prefix + $this.attr('id');
			
			
			// if iPad
			if( !isiPad ){
			
				// Create UL version
				var $list = $('<div>',{
					'class':	o.listClass,
					'id':		id,
					'html':		'<a href="' + $this.closest('form').data('href') + '" class="search">' + o.link + '</a>'
				});
				
				var $ul = $('<ul/>',{
					'class':	o.prefix + 'root'
				}).prependTo($list).hover(function(){
					hover = true;
				},function(){
					hover = false;
				});
				
				$this.find('> *').each(function(){
					var tag = $(this).get(0).tagName.toLowerCase();
					
					if( tag == 'option' ){
						$ul.append('<li><a href="' + $(this).attr('value') + '">' + $(this).text() + '</a></li>');
					}else if( tag == 'optgroup' ){
						var $group = $('<li/>',{
							'html':	'<span>' + $(this).attr('label') + '</span><ul></ul>'
						}).appendTo($ul);
						
						$(this).find('> *').each(function(){
							$group.children('ul').append('<li><a href="' + $(this).attr('value') + '">' + $(this).text() + '</a></li>');
						});
					}
				});
				
				// Add it into body
				$list.appendTo('body').hide();
			
			}
			
			// What to use as the text on the drop down?
			$selected = $this.find('option[selected=selected]');
			
			if( $selected.length != 0 && $selected.text() != $this.find('option:first').text() ){
				var topText = $selected.text();
			}else{
				var topText = o.cta;
			}
			
			// Create new select body
			var $select = $('<div/>',{
				'id':		$this.attr('id'),
				'class':	o.btnClass,
				'html':		'<span>' + topText + '</span><a href="#">Show list</a>'
			}).insertAfter($this);
			
			// Remove select & button
			$this.siblings('button').remove();
			
			// if iPad
			if( !isiPad ){
				
				$this.remove();
			
			}else{
				
				$this.appendTo('body').css({
					'position': 'absolute',
					'z-index':	100,
					'top':		$select.offset().top,
					'left':		$select.offset().left,
					'width':	$select.outerWidth(),
					'height':	$select.outerHeight(),
					'opacity':	0
				}).change(function(){
					window.location = $(this).val();
				});
				
				$hidden = $this;
				
			}
			
			$this = $select;
			
			// Add click event to it
			$this.click(function(e){
				
				// if iPad
				if( isiPad ){
				
					$hidden.click();
				
					return false;
				}
				
				if( !active ){
				
					// Active state
					active = true;
					
					// Hide any active lists
					hideOpen();
					
					$('#' + id).show().css({
						width:	$this.find('span').outerWidth()
					})
					
					function setMetrics(){
						
						var wh = $w.height();
						var offset = $this.offset();
						
						var h = wh - offset.top - 100 + $w.scrollTop();
						
						if( h > wh - 120 ){
							h = wh - 120;
						}else if( h < o.minHeight ){
							h = o.minHeight;
						}
						
						if( h > o.maxHeight ){
							h = o.maxHeight;
						}
						
						// Set the position and height
						$('#' + id).css({
							'top':		offset.top + $this.outerHeight() - 1,
							'left':		offset.left
						}).children('ul').height( h );
						
					}
					
					// Bind some stuff
					$w.bind('resize scroll',function(){
						setMetrics();
					})
					
					$d.bind('mouseup',function(){
						if( !hover ){
							hideOpen();
						}
					});
					
					// Hide if opening the location picker
					$('.' + o.list + ' a.search').click(function(){
						hideOpen();
					});
					
					setMetrics();
					
				}else{
				
					// De-Activate
					active = false;
					
					// Hide the drop down div
					$('#' + id).hide();
					
					// Un-Bind some stuff
					$d.unbind('mouseup');
				
				}
				
				$this.toggleClass('active');
				
				e.preventDefault();
				
			}).hover(function(){
				$this.addClass('hover');
				hover = true;
			},function(){
				$this.removeClass('hover');
				hover = false;
			}).disableSelection();

		});
		
	};
	
	function hideOpen(){
		$('.drop-down.active').click();
	}
	
	$.fn.disableSelection = function(){
		$(this).attr('unselectable', 'on').css('-moz-user-select', 'none').each(function() { 
			this.onselectstart = function(){
				return false;
			};
		});
	};
	
	
	//////////////////////////
	// COLUMN HEIGHTS
	
	$.fn.equalHeights = function(){

		return this.each(function(){
		
			var $these = $(this).find('> section');
			var ct = 0; // Current tallest
			
			// Only go ahead if there are no more than 3 columns
			if( $these.length <= 3 ){
			
				$these.each(function(){
	
					var h = $(this).height();
					
					if( h > ct ){
						ct = h;
					}
	
				});
				
				if( $.browser.msie && $.browser.version == 6.0 ){
					$these.css({
						'height': ct
					});
				}
				
				$these.css({
					'min-height': ct
				});
			
			}
			 
		});
		
	};
	
	
	//////////////////////////
	// SHOW / HIDE
	
	$.fn.showHide = function(settings,show,hide) {
		
		// Settings
		var defaults = {
			'showText':	'Show',		// Uses the text initially set
			'hideText':	'Hide',		// The text that replaces on click
			'onLoad':	'hide',		// By default the item will be hidden
			'speed':	300,
			'easing':	'easeInOutExpo'
		};
		
		var o = $.extend(defaults, settings);
		
		return this.each(function(){
			
			var $this = $(this);
			var $that = $($this.attr('href'));
			var active = true;
			
			if( o.onLoad == 'hide' ){
				$that.hide();
				active = false;
				o.showText = $this.html();
			}else{
				o.hideText = $this.html();
			}
			
			$this.click(function(e){
			
				if( active ){
				
					active = false;
				
					$this.html(o.showText);
					
					if( hide ){
					
						hide.apply($that);
					
					}else{
						
						$that.stop([]).slideUp(o.speed,o.easing);
						
					}
				
				}else{
				
					active = true;
				
					$this.html(o.hideText);
					
					if( show ){
				
						show.apply($that);
					
					}else{
					
						$that.stop([]).slideDown(o.speed,o.easing);
						
					}
				
				}
				
				e.preventDefault();
				
			});
			
		});
	
	}
	
})(jQuery);


//////////////////////////
// EASING

jQuery.extend( jQuery.easing,{
	easeInOutExpo: function (x, t, b, c, d){
		if (t==0) return b;
		if (t==d) return b+c;
		if ((t/=d/2) < 1) return c/2 * Math.pow(2, 10 * (t - 1)) + b;
		return c/2 * (-Math.pow(2, -10 * --t) + 2) + b;
	},
	easeInOutQuart: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return c/2*t*t*t*t + b;
		return -c/2 * ((t-=2)*t*t*t - 2) + b;
	},
	easeOutQuart: function (x, t, b, c, d) {
		return -c * ((t=t/d-1)*t*t*t - 1) + b;
	},
	easeOutExpo: function (x, t, b, c, d) {
		return (t==d) ? b+c : c * (-Math.pow(2, -10 * t/d) + 1) + b;
	},
	easeInExpo: function (x, t, b, c, d) {
		return (t==0) ? b : c * Math.pow(2, 10 * (t/d - 1)) + b;
	}
});

/*
 * jQuery Timer Plugin
 * http://www.evanbot.com/article/jquery-timer-plugin/23
 *
 * @version      1.0
 * @copyright    2009 Evan Byrne (http://www.evanbot.com)
 */

jQuery.timer = function(time,func,callback){
	var a = {timer:setTimeout(func,time),callback:null}
	if(typeof(callback) == 'function'){a.callback = callback;}
	return a;
};

jQuery.clearTimer = function(a){
	clearTimeout(a.timer);
	if(typeof(a.callback) == 'function'){a.callback();};
	return this;
};
