//------------------------------------
//
//	BELLA.JS
//	Requires:	jquery 1.6.x
//
//------------------------------------

////////////////////////////
// BEGIN JQUERY

$(function(){

	//////////////////////////
	// DROP DOWNS
	
	// Force the default text
	$('#location_info select').dropdown({
		'defaultText':		'Select a new location',
		'forceDefaultText':	true
	});

	if( window.location.href.search('bookonline') > 0 ){
		$('.step:first select').dropdown({
			'defaultText': 'Please choose a restaurant'
		});
	}
	
	
	//////////////////////////
	// LOCATION PICKERS
	
	// Locations page
	$('a[href$=italian-restaurants]').location({
		url:		'/italian-restaurant/[location]',
		mainTitle:	'Find a Bella Italia',
		intro:		'Please tell us your current location or choose from the list below',
		cufon:		false
	});
	
	// Book online page
	$('a[href$=bookonline]').location({									  	
		url:		'/bookonline/[location]',
		mainTitle:	'Book a table',
		intro:		'Which Bella Italia would you like to book a table at?',
		cufon:		false
	});
	
	// Menu page
	$('a[href$=menus]').location({
		url:		'/menus/[location]',
		mainTitle:	'Our menus',
		intro:		'Our menus can vary between restaurants so please choose which Bella Italia you would like to see the menu for',
		cufon:		false
	});


	//////////////////////////
	// FORMS
	
	// Simple select replacement for forms, not for the location picker
	$('html:not(.ie6) form .field select').simpleSelect();
	
	// Error shakyness!
	$('form p.error:visible').animate({
		'margin-left': -2
	},40).animate({
		'margin-left': 2
	},40).animate({
		'margin-left': -2
	},40).animate({
		'margin-left': 2
	},40).animate({
		'margin-left': -2
	},40).animate({
		'margin-left': 2
	},40).animate({
		'margin-left': 0
	},40);
	
	
	// 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');
			});
			
		});

	}


	//////////////////////////
	// EXTERNAL LINKS
	
	$('a[href*="http://"]:not([href*="'+location.hostname+'"]):not([class*="internal"]), .external').live('click',function() {
	    window.open($(this).attr('href'));
	    return false;
	});
	
	
	//////////////////////////
	// PAGE SPECIFIC STUFF
	// For any tiny bits of JS that are only for one page, that aren't worth a whole js file

});


//////////////////////////
// PLUGINS

(function($) {

	//////////////////////////
	// DROP DOWN PLUGIN
	
	$.fn.dropdown = function(settings) {
		
		// Settings
		var defaults = {
			'delay':			200,
			'btnClass':			'select',
			'listClass':		'drop_down_list',
			'prefix':			'dd_',
			'link':				'Find your nearest',
			'defaultText':		'Please select one',
			'forceDefaultText':	false,
			'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 ){
			
				$this.simpleSelect({
					removeButton:true
				});
			
			}else{
			
				// Create UL version
				var $list = $('<div>',{
					'class':	o.listClass,
					'id':		id,
					'html':		'<a href="' + $this.closest('fieldset').data('href') + '" class="search button">' + 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?
				if( o.forceDefaultText == false ){
				
					// Don't force a default, but if nothing is specifically selected, we use a fallback
					if( $this.find('[selected]').size() == 0 ){
						
						var topText = o.defaultText;
						
					}else{
						
						var topText = $this.find('option:selected').text();
						
					}
					
				}else{
				
					var topText = o.defaultText;
					
				}
				
				// Create new select body
				var $select = $('<div/>',{
					'id':		$this.attr('id'),
					'class':	o.btnClass,
					'html':		'<span class="body">' + topText + '</span><a href="#"></a>'
				}).insertAfter($this);
				
				// Remove select & button
				$this.siblings('button').remove();
				
				$this.remove();
				
				$this = $select;
				
				// Add click event to it
				$this.click(function(e){

					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(){
		$('.select.active').click();
	}
	
	$.fn.disableSelection = function(){
		$(this).attr('unselectable', 'on').css('-moz-user-select', 'none').each(function() { 
			this.onselectstart = function(){
				return false;
			};
		});
	};

	//////////////////////////
	// SELECT PLUGIN
	
	$.fn.simpleSelect = function(settings) {
		
		// Settings
		var defaults = {
			defaultText:	null,
			removeButton:	false,
			ready:			function(){},
			click:			function(){},
			change:			function(){}
		};
		
		var o = $.extend(defaults, settings);
		
		return this.each(function(){
		
			var $this = $(this);
			
			// Are there classes
			var classes = $this.attr('class') == undefined ? 'select' : 'select ' + $this.attr('class');
		
			$this.wrap('<span class="' + classes + '"/>');
			
			var $s = $this.parent('.select');
			
			if( o.removeButton ) $s.next('button').remove();
			
			if( o.defaultText == null ){
			
				var initial = $this.find('option:selected').text();
				
			}else{
			
				var initial = o.defaultText;
			
			}
			
			$s.prepend('<span class="body">' + initial + '</span><a href="#"></a>');
			
			$this.css({
				'width':		$s.outerWidth(),
				'height':		$s.outerHeight(),
				'opacity':		0
			}).bind({
				change:		function(){
				
					$s.find('.body').text($this.find('option:selected').text());
					
					o.change.apply($this);
					
				},
				click:		function(){
			
					o.click.apply($this);
				
				},
				focus:		function(){
				
					$s.addClass('focus');
				},
				blur:		function(){
					
					$s.removeClass('focus');
					
				},
				mouseenter:	function(){

					$s.addClass('hover');

				},
				mouseleave:	function(){

					$s.removeClass('hover');

				}
				
			});
			
			o.ready.apply($this);
	
		});

	};
	
    
    //////////////////////////
	// SCROLL TO

	$.fn.scrollTo = function(target){
		return this.click(function(e){
		
			$this = $(this);
			max = $(document).height() - $(window).height();
		
			// Go to top as a fallback or if specified
			if( target == 'top' || $this.attr('href') == '#' ){
				y = 0;
			}else{
				y = $($this.attr('href')).offset().top;
			}
			
			// If the page isn't long enough just go as far as possible
			if( y > max ){
				y = max;
			}
		
			// Animate
			$('html, body').animate({
				'scrollTop':	y
			},'600','easeInOutExpo');
			
			// Stop badness
			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;
};
