/*!
#######################################################################
# 
# Colibri
# JavaScript setup routines
#
# Hand-crafted by Duke
#
#######################################################################
*/

	////////////////////////////////////////////////////////////////////
    //  Initialise setup routines
    ////////////////////////////////////////////////////////////////////
    
        // Called when DOM is ready
        $(document).ready( domSetup );
        
        // Called when entire page is loaded
        $(window).load( pageSetup );
        
        // Called when DOM is unloaded
        $(window).unload( domUnload );
    
    ////////////////////////////////////////////////////////////////////
    //  Global variables
    ////////////////////////////////////////////////////////////////////
	
		// Set site root
		//var siteRoot = '/colibri/';
		var siteRoot = '/';

    
    ////////////////////////////////////////////////////////////////////
    //  Define setup routines
    ////////////////////////////////////////////////////////////////////
    
    /* 
    domSetup()
    
    All JavaScript requiring initialisation on DOM LOAD should be called
    from this routine.
    -----------------------------------------------------------------------
    */
    
    function domSetup() {

		////////////////////////////////////////////////////////////////////
        //  Navigation
        ////////////////////////////////////////////////////////////////////

			/* Images lightbox */
			$('#product #main_product_image a').colorbox({
				initialWidth	:	'200px',
				initialHeight	:	'200px',
				innerWidth		:	'600px',
				innerHeight		:	'600px',
				opacity			:	'0.8',
				photo			:	true,
				title			:	false
				/* title			:	function () {
					return $(this).siblings('h2').html();
				} */
			});
			
			/* Disable clicks on Collections and Products navigation items,
			for some reason */
			$('#primary-navigation-collections > a, #primary-navigation-products > a').each( function() {
				// Make reference
				var $this = $(this);
				// Remove href
				$this.attr('href', '#');
				// Bind click handler
				$this.bind( 'click', function(e) { 
					e.preventDefault();
				} );
			} );
			
			/*
            Setup external links (target attribute not allowed by XHTML 1.1)
            (see http://www.sitepoint.com/article/standards-compliant-world/)
            */
            $('a[rel="external"]').attr('target','blank');
        
        ////////////////////////////////////////////////////////////////////
        //  /Navigation
        ////////////////////////////////////////////////////////////////////
        
        ////////////////////////////////////////////////////////////////////
		//	Flash embedding
		////////////////////////////////////////////////////////////////////

			// Set express install location
			//var expressInstaller = siteRoot+'assets/templates/colibri/flash/flash-express-install.swf';
			var expressInstaller = null;

			/* Heritage slideshow */
			if ( $('#heritage_slideshow')[0] ) {
				
				var replacedContentID = 'heritage_slideshow';
				var swf = siteRoot+'assets/templates/colibri/flash/heritage_slideshow.swf';	
				var width = '960';
				var height = '478';
				var flashVersion = '9.0.0';
				
				var flashvars = {
					siteRoot			:	siteRoot
				};
				var params = {
					wmode 				: 	'transparent',
					scale				:	'showall',
					allowScriptAccess	:	'always',
					allowFullScreen		: 	'false'
				};
				var attributes = {
					id					:	'heritage_slideshow_flash',
					name				:	'heritage_slideshow_flash'
				};

				// Replace content
				swfobject.embedSWF( swf, replacedContentID, width, height, flashVersion, expressInstaller, flashvars, params, attributes );
				
			}
		
		////////////////////////////////////////////////////////////////////
		//	/Flash embedding
		////////////////////////////////////////////////////////////////////
		
		////////////////////////////////////////////////////////////////////
        //  Enhancements
        ////////////////////////////////////////////////////////////////////
            
			// tell the site that jQ has loaded
			$('html').addClass('loaded');
			
			// add spans to stuff that needs extra markup to display
			$('#home #wrapper, .main_stage, #product #related_items').append('<span class="corner" />');
			$('#logo a, #product .main_stage #view a, #product #related_items p a').not('.main_stage .product_list li.no-results p a').append('<span />');
			$('.main_stage .product_list li p a').wrapInner('<span></span>');
			$('.main_stage .product_list > li:not(.main_stage .product_list li.no-results)').not('#products-carousel .product_list li').prepend('<span class="corner" />');
			$('#related_items .product_list li').prepend('<span class="corner" />');
			$('.pagination .next a, .pagination .previous a').append('<span />');
			$('#collection .main_stage').append('<span class="logo" />');
			
			/* Primary navigation */
			$('#primary_links nav > ul > li > ul').append('<span />'); 
			$('#primary_links nav > ul > li h3').append(':'); 
			
			$('#primary_links nav > ul').superfish({
				delay		: 	1000,
				dropShadows	: 	false,
				autoArrows	: 	true,
				animation	: 	{'height' : 'show'},
				speed		: 	200
			});
			
			/* Secondary navigation */
			$('#secondary_links nav > ul > li > ul').superfish({
				delay		: 	1000,
				dropShadows	: 	false,
				autoArrows	: 	false,
				animation	: 	{'height' : 'show'},
				speed		: 	200
			});
			
			/* Pagination buttons */
			if ( !$('.pagination .disabled')[0] ) {
				$('.pagination .next + .previous').parent().addClass('half');
			}
			
			/* Carousel */
			if ( $('#products-carousel')[0] ) {
				$('#products-carousel .product_list').append('<span class="previous" title="Previous">Previous</span><span class="next" title="Next">Next</span>');
				//$('#products-carousel .product_list li li:nth-of-type(odd) a').after('+');
				$('#products-carousel .product_list').roundabout( {
					shape		:	'lazySusan',
					tilt		:	1.5,
					minOpacity	: 	1.0,
					minScale	: 	0.2,
					easing		: 	'easeOutExpo',
					duration	: 	1000,
					btnPrev		: 	'.previous',
					btnNext		: 	'.next'
				} );
			}
			
			/* Heritage slideshow */
			
			// Set slideshow mode (leave this in to preserve flexibility in future...)
			var heritage_mode = 'simple';
		
			if ( heritage_mode == 'reduced' ) {
				// Hide slides
				$('#heritage #slider li:gt(9), #heritage #slide_navigation li:gt(9)').remove();
			}
			
			$('#heritage #heritage_slideshow').append('<span class="next"><span /></span><span class="previous"><span /></span>');
			
			$("#heritage #slide_navigation li a").wrapInner('<span />').find('span').prepend('<span />');
			
			// Change main images into background images
			$('#heritage .main_stage img.main').each(function() {
				// Get references to slide and image
				var $this = $(this);
				var image = $this.attr('src');
				// Add background image
				$this.parent().css({
					'background-image'  :   'url('+image+')'
				});
				// Remove image
				$this.remove();
			})
			
			$('#heritage .main_stage').
			scrollable({
				items       :   '#slider',
				circular    :   false,
				mousewheel  :   true,
				speed       :   2000,
				easing      :   'easeOutExpo',
				next        :   '#wrapper .next',
				prev        :   '#wrapper .previous'
			}).navigator({
				navi        :   '#slide_navigation',
				naviItem    :   'li',
				activeClass :   'active',
				history     :   false
			});
			
			/* Dynamically position slides to emulate position: fixed
			by updating position at a given interval */
			
			if ( heritage_mode != 'simple' ) {
			
				// Get reference to slides
				var $heritage_slides = $('#heritage #slider li');
				
				if ( $heritage_slides ) {
					// Set interval
					var heritage_image_positions = window.setInterval( function() {
					
						$heritage_slides.each(function(){
							// Make reference to slide
							var $this = $(this);
							// Position slide
							$this.position({
								my      :   'left top',
								at      :   'left top',
								of      :   '.main_stage',
								// Custom function to set position to whole pixel values to prevent juddering
								using   :   function( position )    {
									// Set left offset; we are not interested in the top as it's constant
									var left = Math.ceil( position.left );
									var left = position.left;
									$this.css({
										'background-position'   :   left+'px 0'
									});
								}
							});
						});
					}, 10 );
				}
				
			}
			
			// Select first item by default
			if ( $('#heritage .main_stage')[0] ) {
				$('#heritage .main_stage').data('scrollable').begin();
			}

			/* Home slideshow */
			
			$("#home #slide_navigation li a").wrapInner('<span />').find('span').prepend('<span />');
			
			$('#home .main_stage').
			scrollable({
				items       :   '#slider',
				circular    :   true,
				mousewheel  :   true,
				speed       :   400,
				easing      :   'easeInSine'
			}).autoscroll({
				steps       :   1,
				interval    :   6000,
				autopause   :   true,
				autoplay    :   true
			}).navigator({
				navi        :   '#slide_navigation',
				naviItem    :   'li',
				activeClass :   'active',
				history     :   false
			});
			
			// Select first item by default
			if ( $('#home .main_stage')[0] ) {
				$('#home .main_stage').data('scrollable').begin();
			}
			
			/* Form elements*/

			// Create default values from form labels
			$('.main_stage form label').each( function() {
				// Create reference
				var $this = $(this);
				// Get associated form element
				var $element = $this.siblings( '#' + $this.attr('for') );
				// Copy label to associated form element
				if ( !$element.val() ) {
					$element.val( $this.text() );
				}
				// Store label for reference
				$element.data('label', $this.text() );
			});
			
			// Bind focus event to clear default values
			$('.main_stage form input[type=text], .main_stage form textarea').bind( 'focus', function() {
				// Create reference
				var $this = $(this);
				// Check value
				if ( $this.val() == $this.data('label') ) { 
					$this.val('');
				} else {
					//$this.select();
				}
			});
			
			// Bind blur event to restore default values
			$('.main_stage form input[type=text], .main_stage form textarea').bind( 'blur', function() {
				// Create reference
				var $this = $(this);
				// Check value
				if ( $.trim( $this.val() ) == '') {
					$this.val( $this.data('label') );
				}
			});
			
			// Bind submit event to clear default values
			$('.main_stage form').bind( 'submit', function() {
				// Check elements for default values
				$(this).find('input[type=text], textarea').each( function() {
					// Create reference
					var $this = $(this);
					// Check value
					if ( $this.val() == $this.data('label') ) { 
						$this.val('');
					}
				})
				
			});
			
			// Enhance checkboxes
			$('input[type="checkbox"]').ezMark({
				checkboxCls		: 	'checkbox',
				checkedCls		: 	'checked'
			});
			
			// Toggle checkbox when the adjacent paragraph is clicked
			$('.checkbox + p').click(function(){
				// Get reference to checkbox
				var $checkbox = $(this).prev();
				// Toggle attributes
				$checkbox.toggleClass('checked');
				$checkbox.find(':checkbox').attr('checked', !$checkbox.find(':checkbox').attr('checked') );
			});

			/* Map */
			
			// Create spans
			$('#map .main_stage').append('<img src="' + siteRoot + 'assets/templates/colibri/images/blank.gif" usemap="#distributors_map" width="960" height="570" id="map_cover" /><span class="north_america regions" /><span class="south_america regions" /><span class="europe regions" /><span class="russia regions" /><span class="africa regions" /><span class="middle_east regions" /><span class="far_east regions" />');
			$('#map .main_stage .regions').hide();
			
			// Define hover events
			$('#map .main_stage #distributors_map area').hover(function(){
				var parent = $(this).attr('class');
				var $target = $('#map .main_stage .regions.' + parent);
				$target.dequeue( true, true ).fadeIn('fast');
				$(this).mouseout(function(){
					$target.dequeue( true, true ).fadeOut('fast');
				});
			});
			
			/* Distributors selector */
			if ( $('#distributors_region')[0] ) {

				// Store properties of selector list in array
				var distributors_selector = Array();

				$('#distributors_region #distributors ul li a').each( function(){
					// Make reference
					var $this = $(this);
					distributors_selector.push({
						'text'	:	$this.text(),
						'value'	:	$this.attr('href')
					});
				});
				
				// Store properties of selector list in array
				var stores_selector = Array();

				$('#distributors_region #stores ul li a').each( function(){
					// Make reference
					var $this = $(this);
					stores_selector.push({
						'text'	:	$this.text(),
						'value'	:	$this.attr('href')
					});
				});
				
				// Build select field to replace distributors list
				var output = '<select id="distributors_selector">';
				
				for ( var i in distributors_selector ) {
					output += '<option value="' + distributors_selector[i].value + '">' + distributors_selector[i].text + '</option>';
				}
				
				output += '</select><div id="distributors_details" class="details" />';
				
				// Replace list with selector
				$('#distributors_region #distributors ul').replaceWith( output );
				
				// Select first in list
				$('#distributors_selector option:first-child').attr( 'selected', 'selected' );
				
				// Build select field to replace stores list
				var output = '<select id="stores_selector">';
				
				for ( var i in stores_selector ) {
					output += '<option value="' + stores_selector[i].value + '">' + stores_selector[i].text + '</option>';
				}
				
				output += '</select><div id="stores_details" class="details" />';
				
				// Replace list with selector
				$('#distributors_region #stores ul').replaceWith( output );

				// Select first in list
				$('#stores_selector option:first-child').attr( 'selected', 'selected' );

				// Bind form loader to change event
				$('#distributors_selector, #stores_selector').bind( 'change', function(){
					// Make reference
					var $this = $(this);
					// Get distributor type
					var distributor = $this.children('option:selected').attr('value');
					// Load in distributor details
					$this.next('.details').load( distributor );
				});
				
				// Trigger change event on load
				$('#distributors_selector, #stores_selector').trigger( 'change' );
			
			}
			
		////////////////////////////////////////////////////////////////////
		//  /Enhancements
		////////////////////////////////////////////////////////////////////
		
		////////////////////////////////////////////////////////////////////
		//  Animation
		////////////////////////////////////////////////////////////////////

			
			/**
			 * Collection animation
			 */
			
			if ( $('#collection')[0] ) {
			
				// create assets
				$('#collection .main_stage').append('<span id="left_stage" /><span id="colourway" />');
				// animate them
				var $left_stage      = $('#collection .main_stage #left_stage');
				var $colourway       = $('#collection .main_stage #colourway');
				var $logo            = $('#collection .main_stage .logo');
				var $product         = $('#collection .main_stage #product');
				var $menu            = $('#collection .main_stage .menu');
				var $header          = $('#collection .main_stage h1');
				var $placement       = $('#collection .main_stage .placement');
				var $para            = $('#collection .main_stage p');

				$left_stage
					.css({
						left: '-581px'
						});
				$colourway
					.css({
						left: '-350px'
						});
				$logo
					.hide();
				$product
					.hide();
				$menu
					.css({
						left: '-236px'
					});
				$header
				.css({
					left: '-200px'
					});
				$placement
					.hide();
				$para
					.hide();
					
			}
					
		////////////////////////////////////////////////////////////////////
		//  /Animation
		////////////////////////////////////////////////////////////////////

	} // End domSetup()
	
	/* 
	pageSetup()
	
	All JavaScript requiring initialisation on PAGE LOAD should be called
	from this routine (all images and elements should be loaded and ready to
	manipulate by this point)
	-----------------------------------------------------------------------
	*/
	
	function pageSetup() {

		////////////////////////////////////////////////////////////////////
		//  Animation
		////////////////////////////////////////////////////////////////////
		
			/**
			 * Collection animation
			 */
			
			if ( $('#collection')[0] ) {
			
				// animate them
				var $left_stage      = $('#collection .main_stage #left_stage');
				var $colourway       = $('#collection .main_stage #colourway');
				var $logo            = $('#collection .main_stage .logo');
				var $product         = $('#collection .main_stage #product');
				var $menu            = $('#collection .main_stage .menu');
				var $header          = $('#collection .main_stage h1');
				var $placement       = $('#collection .main_stage .placement');
				var $para            = $('#collection .main_stage p');

				$left_stage
					.animate({
						left: '0'
					}, 2000, 'easeOutExpo' );
				$colourway
					.delay(1000)
					.animate({
						left: '350px'
					}, 1000, 'easeOutExpo' );
				$logo
					.hide()
					.delay(2000)
					.fadeIn(1000, 'easeInExpo' );
				$product
					.hide()
					.delay(1000)
					.fadeIn(3000, 'easeOutExpo' );
				$menu
					.delay(7000)
					.animate({
						left: '56px'
					}, 1000, 'easeOutExpo' );
				$header
				.delay(3000)
				.animate({
					left: '200px'
				}, 1000, 'easeOutExpo' );
				$placement
					.hide()
					.delay(4000)
					.fadeIn(1000, 'easeInExpo' );
				$para
					.hide()
					.delay(5000)
					.fadeIn(1000, 'easeInExpo' );
					
			}

		////////////////////////////////////////////////////////////////////
		//  /Animation
		////////////////////////////////////////////////////////////////////
		
	};

	// End pageSetup()
    
    /* 
    domUnload()
    
    Called when page/DOM is unloaded
    -----------------------------------------------------------------------
    */
    
    function domUnload() {

    } // End domUnload()
