//------------------------------------
//
//	HOME.JS
//	Requires:	jquery 1.5.x
//
//------------------------------------

//////////////////////////
// DISQUS

var disqus_shortname = 'caferouge';
var disqus_developer = document.location.href.search('dev.com') > 0 ? 1 : 0;

(function() {
	var s = document.createElement('script');
	s.type = 'text/javascript';
	s.async = true;
	s.src = 'http://' + disqus_shortname + '.disqus.com/count.js';
	(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(s);
}());


////////////////////////////
// BEGIN JQUERY

$(function(){

	//////////////////////////
	// DROP DOWNS

	$('#smb select').dropdown({
		'defaultText':	'Choose a restaurant'
	});


	//////////////////////////
	// Find your nearest

	$('#find_a_rouge').submit(function(e){

		$.location({
			url: 		'/french-restaurant/[location]',
			searchTerm:	$(this).find('#search').val(),
			mainTitle:	'Find a Caf&eacute; Rouge',
			intro:		'To find your nearest Caf&eacute; Rouge, please enter a search term below or choose from the list.',
			cufon:		false
		});

		e.preventDefault();

	});


	//////////////////////////
	// TWITTER

	$('#twitter').tweet();


	//////////////////////////
	// MAIN PROMOTION AREA

	function promotions(){

		// Objects
		var $p = $('#promotions');
		var $pw = $('#promotions_window');
		var $promotion = new Array();
		var $a = $p.find('nav a');
		var $n;

		// Variables
		var t = $p.find('.promotion').length;
		var w = $pw.width();
		var h = $pw.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('image');

				// 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);

			});

		};

        // Thumbnail plugin
        $.fn.thumbnail = function(callback) {

            return this.each(function(){

                // Objects
                var $this = $(this);
                var $tp = $p.find('.promotion:eq(' + ( $this.text() - 1 ) + ')');
                var $thumb;

                var url = $tp.data('image');

                //console.log(x + ' ' + y + ' ' + url);

                $this.hover(function(){

					if( !$this.hasClass('on') ){

	                    var x = $this.offset().left + 30;
	                    var y = $this.offset().top - 63;

	                    $thumb = $('<div/>',{
	                        'id':   'promotions_thumb',
	                        'css':  {
	                            'top':  y,
	                            'left': x
	                        },
	                        'html': '<img src="' + url + '" alt="Thumbnail" width="180" height="132"><span></span>'
	                    }).appendTo('body');

	                    if( !$tp.data('loaded') ){

	                        setTimeout(function(){
	                            if( !$tp.data('loaded') ) $thumb.addClass('loading');
	                        },200);

	                        $tp.loadBg(function(){
	                            $thumb.removeClass('loading').find('img').fadeIn(200);
	                        });

	                    }else{

	                        $thumb.find('img').show();

	                    }

                    }

                },function(){
					$('#promotions_thumb').remove();
                });

                $this.click(function(){
                	$('#promotions_thumb').remove();
                });

            });

        };

        // Create array of slide objects and the nav
        for( i = 1; i <= t; i++ ){

            // Add to the array
            $promotion[i] = $p.find('.promotion:eq(' + ( i - 1 ) + ')');

            // Generate HTML
            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($p.find('nav'));

                $n.css({
                    'margin-top':   0 - Math.round( $n.outerHeight() / 2 )
                }).find('li:first a').addClass('on');

            }
        }

        // 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){

            mooseBan = true;

            var $old = $p.find('.promotion:visible');
            var $new = $promotion[c];

			if( supports3d() && $('html').hasClass('webkit') ){
			
				$('html').addClass('three_dee');
			
				function endAnim(){
				
					$pw.removeClass('up down');
					$new.removeClass('top bottom').unbind('webkitAnimationEnd');
					$old.hide().removeClass('top bottom');
					
					mooseBan = false;
					
				}
				
				if( dir == 'up' ){

					$new.show().addClass('bottom');
					$old.addClass('top');

				}else{
				
					$new.show().addClass('top');
					$old.addClass('bottom');
				
				}
				
				$pw.addClass(dir);
				
				$new.bind({
					'webkitAnimationEnd':	endAnim
				});
			
			}else{

	            // Show the new slide
				$new.css({
					'display':	'block',
					'top':		dir == 'up' ? h : 0 - h
				}).animate({
					'top':		0
				},800,'easeInOutExpo');
	
				// Hide the old one
				$old.animate({
					'top':		dir == 'up' ? 0 - h : h
				},800,'easeInOutExpo',function(){
	
					$(this).hide();
	
					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
        $promotion[1].loadBg(function(){

            // Stop loading
            $p.removeClass('loading');

            $(this).fadeIn(100,function(){
                mooseBan = false;
            });

            auto();

        });


        // Automatically slide
        function auto(){

            var p = $promotion[c].data('pause');

            if( p == undefined ){
                p = pause;
            }

            timer = $.timer( ( p * 1000 ),function(){

                $.clearTimer(timer);

                if( !$p.hasClass('loading') ) $p.find('a.next').click();
                
                auto();

            });

        }

        // Hovering
        $p.bind({
            'mousemove':    function(){
                $.clearTimer(timer);
                $p.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;

                if( $(this).hasClass('arrow') ){

                    if( $(this).hasClass('next') ){
                        c++;
                        dir = 'down';
                    }else{
                        c--;
                        dir = 'up';
                    }

                    if( c > t ){
                        c = 1;
                    }else if( c < 1 ){
                        c = t;
                    }

                }else{

                    var num = $(this).text();
                    var dir = c > num ? 'up' : 'down';
                    c = num;

                }

                // Check if we are all loaded
                if( $promotion[c].data('loaded') == true ){

                    goTo(dir);

                }else{

                    // Set loading
                    setTimeout(function(){
                        if( !$this.data('loaded') ) $p.addClass('loading');
                    },200);

                    $promotion[c].loadBg(function(){
                        goTo(dir);

                        // Stop loading
                        $p.removeClass('loading');

                    });
                }

            }

            e.preventDefault();

        });
        
	}

	promotions();

	// Small promos
	$('.cycle').cycle();
	
	
	//////////////////////////
	// CHECK FOR 3D
	// Thanks to http://www.modernizr.com/
	
	function supports3d() {
		// borrowed from modernizr
		var div = document.createElement('div'),
			ret = false,
			properties = ['perspectiveProperty', 'WebkitPerspective'];
		for (var i = properties.length - 1; i >= 0; i--){
			ret = ret ? ret : div.style[properties[i]] != undefined;
		};
	    
	    // webkit has 3d transforms disabled for chrome, though
	    //   it works fine in safari on leopard and snow leopard
	    // as a result, it 'recognizes' the syntax and throws a false positive
	    // thus we must do a more thorough check:
	    if (ret){
	        var st = document.createElement('style');
	        // webkit allows this media query to succeed only if the feature is enabled.    
	        // "@media (transform-3d),(-o-transform-3d),(-moz-transform-3d),(-ms-transform-3d),(-webkit-transform-3d),(modernizr){#modernizr{height:3px}}"
	        st.textContent = '@media (-webkit-transform-3d){#test3d{height:3px}}';
	        document.getElementsByTagName('head')[0].appendChild(st);
	        div.id = 'test3d';
	        document.body.appendChild(div);
	        
	        ret = div.offsetHeight === 3;
	        
	        st.parentNode.removeChild(st);
	        div.parentNode.removeChild(div);
	    }
	    return ret;
	}

});


//////////////////////////
// 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:		6,						// 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('a').length;			// Total
			var c = 1;								// Current
			var nav = '';							// Nav
			var timer = {};							// Timer
			var mooseBan = false;					// Bad MOOSE!
			var old = 1;							// The old slide

			// Build navigation and article array
			for( i = 1; i <= t; i++ ){

				// Article array
				$a[i] = $this.find('a: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,
						'class':	'clear dark'
					}).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 slide
				$a[old].stop([]).animate({
					'opacity':	0
				},400,function(){
					
					// Get rid of old slide
					$(this).hide();
					
					// Un ban the moose!
					mooseBan = false;
					
					// Set the old slide
					old = c;
					
				});

				$a[c].stop([]).show().css({
					'opacity':	0
				}).animate({
					'opacity':	1
				},400);

				// 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);
					$this.find('.border').addClass('hover');
				},
				'mouseleave':	function(){
					auto();
					$this.find('.border').removeClass('hover');
				}
			});

		});

	};

})(jQuery);
