//------------------------------------
//	ROUGE.JS
//	Requires:	jquery 1.5.x
//------------------------------------

////////////////////////////
// BEGIN JQUERY

$(function(){

	//////////////////////////
	// DROP DOWNS
	
	// Force the default text
	$('#location_info select').dropdown({
		'defaultText':		'Select a new location',
		'forceDefaultText':	true
	});
	
	// Don't force the default, but supply a fallback
	if( window.location.href.search('bookonline') > 0 ){
		$('.step:first select').dropdown({
			'defaultText': 'Please choose a restaurant'
		});
	}
	

	//////////////////////////
	// LOCATION PICKERS
	
	function toggleTwitter(){
		if( $('html').hasClass('webkit safari') && !$('html').hasClass('chrome') ) $('#follow').toggle();
	}
	
	// Locations page
	$('a[href$=french-restaurants]').location({
		url:		'/french-restaurant/[location]',
		mainTitle:	'Find a Caf&eacute; Rouge',
		intro:		'Please tell us your current location or choose from the list below',
		cufon:		false,
		//no3D:		true,
		beforeShow:	function(){
			toggleTwitter();
		},
		afterHide:	function(){
			toggleTwitter();
		}
	});
	
	// Book online page
	$('a[href$=bookonline]').location({									  	
		url:		'/bookonline/[location]',
		mainTitle:	'Book a table',
		intro:		'Which Caf&eacute; Rouge would you like to book a table at?',
		cufon:		false,
		//no3D:		true,
		beforeShow:	function(){
			toggleTwitter();
		},
		afterHide:	function(){
			toggleTwitter();
		}
	});
	
	// Menu page
	$('a[href$=menus]').location({
		url:		'/menus/[location]',
		mainTitle:	'Our menus',
		intro:		'Our menus can vary between restaurants so please choose which Caf&eacute; Rouge you would like to see the menu for',
		cufon:		false,
		//no3D:		true,
		beforeShow:	function(){
			toggleTwitter();
		},
		afterHide:	function(){
			toggleTwitter();
		}
	});


	//////////////////////////
	// 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');
			});
			
		});

	}
	
	
	//////////////////////////
	// FOOTER COLUMNS
	
	$('footer > div').equalHeights();
	$('.equal1').equalHeights();
	
	
	//////////////////////////
	// ON LONG PAGES

	function checkWindow(){
		var $dw = $('#decorations_wrapper');
		$(window).height() < $(document).height() ? $dw.addClass('long_page') : $dw.removeClass('long_page');
	}
	
	checkWindow();
	
	$(window).resize(function(){
		checkWindow();
	});
	
	
	//////////////////////////
	// 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
	
	// News page scroll to
	$('header .comments').scrollTo();
	
});


//////////////////////////
// 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,
			'noResize': 		false,
			'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 ){

				// We don't need the button
				$this.next('button').remove();
				
				// Apply simple select with change event to go to url
				$this.simpleSelect({
					'change':	function(){
						window.location = $(this).val();
					}
				});
			
			}else{
			
				// Create UL version
				var $list = $('<div>',{
					'class':	o.listClass,
					'id':		id,
					'html':		'<a href="' + $this.closest('form').data('href') + '" class="search button"><span>' + o.link + '</span></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="#"><span></span></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();
							
							if(!o.noResize)
							{
								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,
			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.defaultText == null ){
			
				var initial = $this.find('option:selected').text();
				
			}else{
			
				var initial = o.defaultText;
			
			}
			
			$s.prepend('<span class="body">' + initial + '</span><a href="#" tabIndex="-1"><span></span></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);
	
		});

	};
	
	
	//////////////////////////
    // COLUMN HEIGHTS
     
    $.fn.equalHeights = function(){
 
        return this.each(function(){
         
            var $these = $(this).find('> .column');
            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
                });
             
            }
              
        });
         
    };
    
    
    //////////////////////////
	// SCROLL TO
	
	$.fn.scrollTo = function (settings){	
		return this.click(function(e){
		
			$.scrollTo(settings,$(this))
			
			e.preventDefault();
			
		});
	}

	$.scrollTo = function(settings,$this){
	
		// Settings
		var defaults = {
			target:		'href',				// If left, it will assume that the target is an href. If you set the target, it must be either: top, bottom, or an object
			speed:		600,				// Speed of scroll
			offset:		0,					// Add or subtract from the final position
			easing:		'easeInOutExpo',	// Easing to use
			before:		function(){},		// Callback before scrolling
			after:		function(){}		// Callback after scrolling
		};
		
		var o = $.extend(defaults, settings);
		
		// Just creating it for now
		var y = 0;
		
		// The max scroll (to stop sudden stops)
		var max = $(document).height() - $(window).height();

		// Target detection
		if( o.target == 'href' ){
		
			y = $($this.attr('href')).offset().top;
		
		}else{
		
			if( o.target == 'top' ){
				
				y = 0;
				
			}else if( o.target == 'bottom' ){
			
				y = max;
			
			}else{
			
				y = o.target.offset().top;
			
			}
		
		}
		
		// Add the offset
		y = y + o.offset;
	
		// If the page isn't long enough just go as far as possible
		if( y > max ){
			y = max;
		}
		
		// Animate
		$('html, body').animate({
			'scrollTop':	y
		},o.speed,o.easing,function(){
			o.before.apply($this);
		});
		
	};
	
	
	//////////////////////////
	// ERROR AND VALID
	// Used on various forms
	
	$.fn.error = function(container) {
	
		var $this = $(this);
		
		var $f = $this.closest(container);
		
		if( !$f.hasClass('error') ){
		
			var error = $f.data('error');
			
			if( error == undefined ) error = 'Please complete this field';
			
			$this.closest(container).addClass('error').removeClass('valid');
			
			var $error = $('<p/>',{
				'class':	'error',
				'html':		'<span>' + error + '</span>',
				'css':		{
					'opacity':	0
				}
			}).appendTo($f).hide().slideDown(200,'easeInOutExpo').animate({
				'opacity':	1
			},100);
			
		}
	};
	
	$.fn.valid = function(e) {
		var $f = $(this).closest(e);
		$f.addClass('valid').removeClass('error').find('.error').animate({
			'opacity':	0
		}).slideUp(200,'easeInOutExpo',function(){
			$(this).remove();
		});
	};

})(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;
};

// jQuery.support.transition
// to verify that CSS3 transition is supported (or any of its browser-specific implementations)
$.support.transition = (function(){ 
    var thisBody = document.body || document.documentElement,
    thisStyle = thisBody.style,
    support = thisStyle.WebkitTransition !== undefined || thisStyle.MozTransition !== undefined || thisStyle.OTransition !== undefined || thisStyle.transition !== undefined;
    
    return support; 
})();
