/**
 *	Creative Spark / BURRDA
 *
 *	@pages			all
 *	@author			Phil Thompson
 *	@author			Jake Dean
 *	@since			17/05/2010
 *	@lastmodified	15/06/2010
 *
 *	Contents 
 *		activatePlaceholders
 *		homepageVideo
 *		clickAndSlide
 *		homepageHeroSlider
 *		jQuery viewportOffset 
 *		homepageCarousel
 *		delayIt - !!!!!DON'T CALL THIS IN PRODUCTION!!!!!!
 *		collectionFilter
 *		pngClass
 *		mediaRoomListings
 *		productImageZoom
 *		teamsMap
 *		wheretobuyImageSwap
 *		window.load
 */
 

jQuery.noConflict();


/**
 *	activatePlaceholders
 *	@copyright		http://www.beyondstandards.com/archives/input-placeholders/
 *	@return	void
 */
function activatePlaceholders() {

	var detect = navigator.userAgent.toLowerCase();
	
	if (detect.indexOf("safari") > 0){
		return false;
	}
	
	var placeholder;
	var text_value;
		
	// Put placeholder text into view
	jQuery('input[type="text"], input[type="email"], input[type="tel"], input[type="url"]').each(function(){
		
		
		placeholder = jQuery(this).attr('placeholder');
		text_value = jQuery(this).val();
		
		if(typeof(placeholder) == 'undefined' || text_value.length > 1 || placeholder.length < 1){
			return false;
		}
		
		jQuery(this).val(placeholder);
		
	});
		
	// Remove placeholder when user enters text field
	jQuery('input[type="text"], input[type="email"], input[type="tel"], input[type="url"]').focus(function(){
	
		placeholder = jQuery(this).attr('placeholder');
		text_value = jQuery(this).val();
		
		// Make sure the user hasn't started typing already
		if(typeof(placeholder) == 'undefined' || (placeholder.length < 1 || (text_value.length > 0 && text_value != placeholder))){
			return false;
		}
		
		if(text_value == placeholder){
			jQuery(this).val('');
		}
		
	});

	
	// Put placeholder back if the user doesn't enter a value
	jQuery('input[type="text"], input[type="email"], input[type="tel"], input[type="url"]').blur(function(){
	
	
		placeholder = jQuery(this).attr('placeholder');
		text_value = jQuery(this).val();
		
		// Don't continue if the user has started typing
		if(typeof(placeholder) == 'undefined' || (placeholder.length === 0 || text_value.length > 0)){
			return false;
		}
		
		jQuery(this).val(placeholder);
			
	});
	
	// Remove placeholder text on submit so that value isn't processed
	jQuery('form').submit(function(){
		
		jQuery('input[type="text"], input[type="email"], input[type="tel"], input[type="url"]').each(function(){
		
			placeholder = jQuery(this).attr('placeholder');
			text_value = jQuery(this).val();
			
			if(typeof(placeholder) == 'undefined' || (placeholder.length === 0)){
				return true;
			}
			
			if(text_value == placeholder){
				jQuery(this).val('');
			}
			
			
			
			
		});
		
	});
	
}



/**
 *	homepageVideo
 *	SWFObject a video onto the homepage
 *	@return	void
 */
 
var homeCycle;
 
function homepageVideo(){
	var s1 = new SWFObject('/assets/flash/player.swf','player','928','400','9');
	s1.addParam('allowfullscreen','true');
	s1.addParam('allowscriptaccess','always');
	s1.addParam('flashvars','videoFile=/assets/videos/burrda.flv');
	s1.addParam("wmode", "transparent");
	s1.write('Video');
		clearInterval(homeCycle);
}

function homepageVideo2(){
	var s2 = new SWFObject('/assets/flash/player2.swf','player','928','400','9');
	s2.addParam('allowfullscreen','true');
	s2.addParam('allowscriptaccess','always');
	s2.addParam('flashvars','videoFile=/assets/videos/burrda-belgium.flv');
	s2.addParam("wmode", "transparent");
	s2.write('Video2');
}

/** 
 *	clickAndSlide
 *	Clicks the next homepageHeroSlider link every x milliseconds
 *	@return	void
 */
function clickAndSlide(){
	var nextSection = jQuery('#HeroSlider li.active').next('li').find('a');
	
	if(nextSection.length === 0){
		 //nextSection = jQuery('#HeroSlider li:first a');
	} else{
		// don't autorun if it's the video
		nextSection.click();
	}
}

/**
 *	homepageHeroSlider
 *	Slide in/out extra bits of content on #HeroSlider section.
 *	@return	void
 */
 
function homepageHeroSlider(){

	var moreHref;
	var h1Title;
	var cssClass = 'item-1';
	var duration1 = 200;
	var duration2 = 400;

	var animating = false;

	// Hover action - show hide different parts on hover
	jQuery('#HeroSlider li a').click(function(){

		var current = jQuery('#HeroSlider li.active a');
		var self = this;

		// if this is already the current item, don't do anything
		if ((animating || current[0] == jQuery(this)[0])) {
			return false;
		}

		animating = true;

		current.find('div.text').fadeOut(duration1, function(){
			jQuery(this).parent().parent().animate({width: 139}, duration2);
			jQuery(self).parent().animate({width: 319}, duration2, 'swing', function(){
				jQuery(this).find('div.text').fadeIn(duration1, function(){
					jQuery('#HeroSlider li').removeClass('active');
					jQuery(self).parent().addClass('active');
					animating = false;
				});
			});
		});

		cssClass = jQuery(this).attr('class');
		moreHref = jQuery(this).attr('href');
		h1Title = jQuery(this).find('h2').html();

		jQuery('#Hero div.inner').
			removeClass('item-1').
			removeClass('item-2').
			removeClass('item-3').
			removeClass('item-4').
			removeClass('video').
			removeClass('video2');

		jQuery('#Hero div.inner').addClass(cssClass);
		jQuery('#Hero a.button').attr('href', moreHref);
		jQuery('#Hero h1').html(h1Title);

		// Videos behave differently
		if(jQuery(this).hasClass('video')){
			//jQuery(this).removeClass('video2');
			jQuery('#Video').show();
			jQuery('#Hero h1, #Hero p:first, #Video2').hide();
			jQuery('#Video2').html('');
			homepageVideo();
		}else if(jQuery(this).hasClass('video2')){
			//jQuery(this).removeClass('video');
			jQuery('#Video2').show();
			jQuery('#Hero h1, #Hero p:first, #Video').hide();
			jQuery('#Video').html('');
			homepageVideo2();
			return false;
			
		}else{
			jQuery('#Video, #Video2').hide().html('');
			jQuery('#Hero h1, #Hero p:first').show();
		}

		return false;
	});



	// Show first item on load
	jQuery('#HeroSlider li:first').addClass('active');

	
}



/*!
 * jQuery viewportOffset - v0.3 - 2/3/2010
 * http://benalman.com/projects/jquery-misc-plugins/
 * 
 * Copyright (c) 2010 "Cowboy" Ben Alman
 * Dual licensed under the MIT and GPL licenses.
 * http://benalman.com/about/license/
 */

// Like the built-in jQuery .offset() method, but calculates left and top from
// the element's position relative to the viewport, not the document.

(function(jQuery){
  
  var win = jQuery(window);
  
  jQuery.fn.viewportOffset = function() {
    var offset = jQuery(this).offset();
    
    return {
      left: offset.left - win.scrollLeft(),
      top: offset.top - win.scrollTop()
    };
  };
  
})(jQuery);




/**
 *	homepageCarousel
 *	Do that dead sexy thing where we sideways scroll through
 *	loads of products.
 *	@return	void
 */
function homepageCarousel(){

	// Don't run for IE6
	if(jQuery('body.ie6').length > 0){
		jQuery('#Collection a.carousel-nav').hide();
		jQuery('#Collection img').attr('width', 92).attr('height', 108);
		return;
	}


	var scrollList = jQuery('#Collection ul');
	var newLeft, cloneBefore, cloneAfter;
	var itemWidth = 122; // how wide (in px) is each product item?
	var duration1 = 600; // speed for animating img size
	var duration2 = 200; // speed of animating opacity
	var xCoordParent = jQuery('#Collection').viewportOffset().left;
	var xCoordItem = 0; // x coordinate of the list item
	var currentItem; // to cache active object
	
	
		
	// Fake a continous carousel by cloning <li>s to make the list 
	// bigger (with twice as many <li>s before and after)
	scrollList.html();
	cloneBefore = scrollList.html();
	cloneAfter = scrollList.html();
	scrollList.prepend(cloneBefore).prepend(cloneBefore);
	scrollList.append(cloneAfter).append(cloneAfter);
	
	
	scrollList.css('width', itemWidth * jQuery('#Collection ul li').length);
	
	// Scroll the 'carousel' upon clicking the nav links
	jQuery('#Collection a.carousel-nav').click(function(){
		
		if(jQuery(this).hasClass('carousel-nav-prev')){
			// Scroll to the left
			newLeft = (scrollList.css('left').replace('px','') + itemWidth);
		} else{
			// Scroll to the right
			newLeft = (scrollList.css('left').replace('px','') - itemWidth);
		}
		
		scrollList.animate({
			left: newLeft
		}, 500);
		
		return false;
		
	});


	// Hover action - show hide different parts on hover
	jQuery('#Collection li a').hoverIntent({
		interval: 100,
		sensitivity: 1,
		over: function(){
		
			currentItem = jQuery(this); //cache object
		
			xCoordItem = jQuery(this).parent().viewportOffset().left;
		
			currentItem.find('*').stop(true);
			currentItem.find('img').animate({
				'width': 131,
				'padding-top': 0
			}, duration1);
			currentItem.parent().animate({width: 215}, duration1, 'swing', function(){
				jQuery(this).find('div.title').css({
					'left': 0,
					'opacity': 0
				}).animate({'opacity': 1}, duration2);
				
				// The last itme in the section is -767px away from #Collection
				// and the animation throws the image off screen. When this item is
				// hovered over - move *everything* to the left			
				if(xCoordParent - xCoordItem < -760){
					jQuery('#Collection a.carousel-nav-next').click();
				}
				
			});
		},
		out: function(){
			
			currentItem = jQuery(this); //cache object
		
			currentItem.parent().stop().find('*').stop(true);
			currentItem.find('div.title').animate({'opacity': 0}, duration2, 'swing', function(){
				jQuery(this).css({
					'left': -110
				}).parent().parent().find('img').animate({
					'width': 92,
					'padding-top': 35
				}, duration1);
				jQuery(this).parent().parent().animate({width: 92}, duration1);
			});
		}
	});

	
	
}


/** 
 *	delayIt
 *	Crude way to delay something
 *	@param	int	time in milliseconds
 *	@copyright http://www.sean.co.uk/a/webdesign/javascriptdelay.shtm
 *	@return	void
 */
function delayIt(millis){
	var date = new Date();
	var curDate = null;

	do { 
		curDate = new Date(); 
	} while(curDate-date < millis);
} 

/**
 *	collectionFilter()
 *	Show/hide/load products as the user (de)selects options.
 *	Also show/hide 'child' filter options as the user (de)selects
 *	parent options.
 *	@return	void
 */
function collectionFilter(){

	var testMode = true; // false for production. true for testing
	var listings = jQuery('#Listings');
	var filterForm = jQuery('#FilterForm');
	var ajaxListings;
	var formData;
	var fade;
	var categoryId;
	
	jQuery('#Listings li').columns();

	if(listings.length === 0 || filterForm.length === 0){
		return;
	}
	
	jQuery('input[type=checkbox]').attr("autocomplete", "off");

	//filterForm.find('fieldset.child').hide();
	
	jQuery('#Container').append('<span class="hide" id="AJAXListings"/>');
	
	jQuery('div.field-checkbox.checked').removeClass('checked');
	jQuery('input:checked').parent().addClass('checked');
	
	// Hide submit button cos we don't need it laddy.
	filterForm.find('button').hide();
	
	filterForm.find('label').append('<span />');
	
	filterForm.find('input[type="checkbox"]').click(function(){
		
		// PART ONE: Show/Hide checkboxes
		// If it is a parent checkbox then we need to show / hide child options
		// If we hide child options we need to wipe them out
		categoryId = jQuery(this).attr('id').replace('category-', '');
		
		/*if(jQuery(this).attr('checked')){
			jQuery('#fieldset-' + categoryId).show();
		} else{
			jQuery('#fieldset-' + categoryId).hide();
			jQuery('#fieldset-' + categoryId + ' input[type="checkbox"]').attr('checked', '');
		}*/
		
		
		jQuery('div.field-checkbox.checked').removeClass('checked');
		jQuery('input:checked').parent().addClass('checked');
		
		// When a grandchild is selected - its parent's siblings need to be unselected
		/*if(jQuery(this).attr('checked') && jQuery(this).parent().parent().hasClass('grandchild')){
			jQuery('div.field-checkbox.parent input:checked, div.field-checkbox.child input:checked').attr('checked', '');
		}*/
			

		// PART TWO: Update the #Listings with new content
		formData = jQuery(filterForm).formSerialize();
		
		// Fade out content 
		listings.append('<div id="Fade"><span>Loading&hellip;</span></div>');
		fade = jQuery('#Fade');
		
		fade.css('height', listings.height());
		fade.show();

		ajaxListings = jQuery('#AJAXListings');
		
		// Load new contents in with AJAX into a hidden place
		ajaxListings.load(filterForm.attr('action') + '?' + formData + ' #Listings', {}, function(responseText, textStatus, XMLHttpRequest){
		
			// Set a fake delay on the code in local testing to mimic
			// real ajax response times
			if(testMode === true){
				//delayIt(2000);
			}
			
			if(textStatus == 'success'){
				// If new content load worked then put it into place
				listings.html(ajaxListings.find('#Listings').html());
				ajaxListings.html('');
				
				// FYI - IE6 doesn't like jQuery('#AJAXListings #Listings')
				// hence the use of find() above
				
				
				// Fade in new content
				jQuery('#Listings li').columns();
				
				
			
				// Update #Listings h2 with new title and count
				//listings.find('h2').html(h2Title + ' (' + listings.find('li').length + ')');
				fade.hide();
			} else{
				filterForm.submit();
			}
			
		});
		
	});
	
	

}


/**
 *	pngClass()
 *	Add a class to all images with a .png extension so we can 
 *	fix them in IE6
 *	@return	void
 */
function pngClass(){
	
	jQuery('#Container img').filter(function() {
		return jQuery(this).attr('src').match(/\.(png)/);
    }).addClass('png_bg');
	
}


/**
 *	mediaRoomListings()
 *	Expand/collapse news/press release details when the headline is clicked on
 *	@return	void
 */
function mediaRoomListings(){
	
	
	// Make all the sectiosn equal height
	jQuery('#ContentSecondary ul.news-items').columns();
	jQuery('#ContentSecondary div.section').columns();
	
	
	
	jQuery('#ContentSecondary ul.news-items li').click(function() {
		
		if(jQuery(this).hasClass('active')){
			// perform default behaviour if we're on an active class
			return true;
		} else{
		
			// Hide all the other div.extra's in this section
			jQuery(this).parent().find('li.active').removeClass('active').find('div.extra').hide();
	
	
			// Now sexily slide the relevant div.extra into view
			jQuery(this).find('div.extra').slideDown('3000', function() {
			    // oh yeah ain't that fresh!
			    jQuery(this).parent().addClass('active');
			});
			
			return false;
		}
		
	});
	
	
	
}


/**
 *	productImageZoom
 *	Zoom the main product image on the product page.
 *	Also swap in/out the thumbnails with the big image.
 *	@see	/assets/behaviour/jquery.colorbox.js
 *	@return	void
 */
function productImageZoom(){

	var agent=navigator.userAgent.toLowerCase();



	var hero, thumb, thumbHref;
	
	hero = jQuery('#HeroImage');
	
	if(hero.length === 0){
		return;
	}

	
	jQuery('#Thumbnails a').click(function(){
	
		thumb = jQuery(this);
		
		thumbHref = thumb.attr('href');
		
		hero.attr('href', thumbHref.replace('/large/', '/extra_large/'));
		hero.find('img').attr('src', thumbHref);
		
		
		return false;
		
	});
	
	// Colorbox (inline pop-up) the big image (don't run on mobiles)
	if (agent.indexOf('mobile') == -1) {
		hero.colorbox();
	}
	
}

/**
 *	teamsMap
 *	Zoom in a world map and show/hide country/team lists
 *	all on click.
 *	Works with a big image that is grown/shrunk and moved
 *	about with absolute positioning.
 *	@return	void
 */
function teamsMap(){


	var coords = {
		UK:      [-2829,  -1113],
		Belgium: [-3004,  -1217],
		Egypt:   [-3415,  -1839],
		Kuwait:  [-3800,  -1775],
		Qatar:   [-10952, -5261],
		USA: [-0, -150]
	};
	var currentCoords;
	var defaultTitle = document.title;
	
	var imageDimensions = [928, 550, 0.593];
	var bigImageWidth = 7000;
	
	if(jQuery('#Hero ul.world-list').length === 0){
		return;
	}

	// set-up
	jQuery('#Back').hide();
	jQuery('#Hero ul.team-list').hide();
	//console.log('hide #Hero ul.team-list');


	// back link functionality:
	// hide team lists, zoom out then show world list
	jQuery('#Back').click(function(){
		jQuery('#Hero ul.team-list').hide();
		//jQuery('#Hero ul.world-list li').removeClass('active');

		document.title = defaultTitle;

		// Zoom out map by resizing and repositioning
		jQuery('#Hero .decoration-map img').animate({
			height:	imageDimensions[1],
			left:	0,
			top:	0,
			width:	imageDimensions[0]
		}, 3000, 'easeInCubic', function(){
			// callback
			jQuery('#Hero h2.subtitle').show();
			jQuery('#Hero ul.world-list').show();
		});

		// Remove the hash
		window.location.hash = '';

		return false;
	});
	
	
	// Hide items when user clicks on the map
	jQuery('#Hero').click(function(){
		//jQuery('#Hero ul.map-list li').removeClass('active');
	});


	jQuery('#Hero ul.map-list a span.container').css('opacity', 0);
	jQuery('#Hero ul.map-list li.reverse a span.container').css('left', '0');

	// Show/hide more info <div> (with CSS) when hovering a marker
	jQuery('#Hero ul.map-list a').hover(function(){
		//jQuery(this).addClass('active');
		jQuery(this).find('span.container').stop().animate({'opacity': 1}, 400);
	}, function(){
	
		if(jQuery(this).parent().hasClass('reverse')){
			jQuery(this).find('span.container').css('left','-220px');
		}
		jQuery(this).find('span.container').stop().animate({'opacity': 0}, 400, 'swing', function(){
			//jQuery(this).parent().removeClass('active');
			jQuery('#Hero ul.map-list li.reverse a span.container').css('left', '0');
		});
	});
	
	
	
	// Show hide country specific team list
	jQuery('#Hero ul.map-list a').click(function(){

		currentListItem = jQuery(this).parents('li');	
		
		if(currentListItem.parent().hasClass('world-list')){
			
			jQuery('#Hero h2.subtitle').hide();
			
			currentCoords = jQuery(this).attr('href').replace('#', '');
			
			// cos Qatar is tiny but has load of teams zoom that
			// bad boy in some more.
			var zoomWidth = bigImageWidth;
			if(currentCoords == 'Qatar'){
				zoomWidth = 18000;
			}
			if(currentCoords == 'USA'){
				zoomWidth = 2000;
			}
			
			// update the hash for bookmarking
			window.location.hash = currentCoords;
			
			// Update the page title
			document.title = 'Teams in ' + currentCoords + ' < ' + defaultTitle;
		
			// zoom in on area of map
			jQuery('#Hero div.decoration-map img').animate({
				height:	(zoomWidth * imageDimensions[2]),
				left:	coords[currentCoords][0],
				top:	coords[currentCoords][1],
				width:	zoomWidth
			}, 3000, 'easeInCubic', function(){
				// callback
				// hide country pointers
				jQuery('#Back').show();
				// show new pointer set
				jQuery('#' + currentCoords + 'Teams').fadeIn('3000');
			});
			
			// hide country list before callback
			jQuery('#Hero ul.world-list').hide();
			
			return false;
		}
		
	});
	

}

/**
 *	@copyright	http://engineeredweb.com/blog/09/12/preloading-images-jquery-and-javascript
 *	@return	object
 */

(function($) {
  var cache = [];
  // Arguments are image paths relative to the current page.
  jQuery.preLoadImages = function() {
    var args_len = arguments.length;
    for (var i = args_len; i--;) {
      var cacheImage = document.createElement('img');
      cacheImage.src = arguments[i];
      cache.push(cacheImage);
    }
  }
})(jQuery)


/**
 *	wheretobuyImageSwap
 *	Swap out the backgorund image on div.image 
 *	with a colour version. Yes yes, we all know CSS sprites are better
 *	just not in this particular situation.
 *	@return	void
 */
function wheretobuyImageSwap(){
	
	var currentLi, currentImage;
	
	
	// Preload colour images
	jQuery.preLoadImages("/assets/images/content/where-to-buy/wolves-colour.png","/assets/images/content/where-to-buy/watford-colour.png","/assets/images/content/where-to-buy/british-handball-colour.png","/assets/images/content/where-to-buy/soccer-scene-colour.png","/assets/images/content/where-to-buy/go-sport-colour.png","/assets/images/content/where-to-buy/gulf-sports-colour.png","/assets/images/content/where-to-buy/galaxy-sports-colour.png","/assets/images/content/where-to-buy/option-sport-colour.png","/assets/images/content/where-to-buy/sportmart-colour.png","/assets/images/content/where-to-buy/milano-sport-colour.png","/assets/images/content/where-to-buy/giant-stores-colour.png","/assets/images/content/where-to-buy/kiddy-zone-colour.png","/assets/images/content/where-to-buy/the-wear-house-colour.png");
	
	
	jQuery('#ContentSecondary li').hover(function(){
		// swap out images for colour ones
		currentLi = jQuery(this);
		currentImage = currentLi.find('div.image').css('background-image');
		currentLi.find('div.image').css('background-image', currentImage.replace('.png', '-colour.png'));
	}, function(){
		// swap out images for default (B&W) ones
		currentLi = jQuery(this);
		currentImage = currentLi.find('div.image').css('background-image');
		currentLi.find('div.image').css('background-image', currentImage.replace('-colour.png', '.png'));
	});
	
}


/**
 *	window.onload
 */
jQuery(document).ready(function(){
	
	
	// Always make the website full height
	jQuery('#Container').css('height', jQuery(document).height());
	
	// Make the new HTML5 attribute 'placeholder' work cross-browser
	activatePlaceholders();

	// Home page behaviours
	if(jQuery('body.home').length > 0){
		homepageHeroSlider();
		homeCycle = setInterval('clickAndSlide()', 4000);
		homepageCarousel();
		
		jQuery('#HeroInner').mouseenter(function(){
												
												if(jQuery(this).hasClass('item-3')){
													
														clearInterval(homeCycle);
												}
													
													});
		
	}
	
	
	
	// Product collection behaviours
	if(jQuery('body.collection').length > 0){
		collectionFilter();
	}
	
	// Media Rooms behaviours
	if(jQuery('body.media-room').length > 0){
		mediaRoomListings();
	}
	
	// Product view behaviours
	if(jQuery('body.product').length > 0){
		productImageZoom();
	}
	
	
	// Where To Buy behaviours
	if(jQuery('body.where-to-buy').length > 0){
		wheretobuyImageSwap();
	}
	
	
	// Add classes to .png images for IE6
	//pngClass();
	
	
	if(jQuery('body.teams').length > 0){
		teamsMap();
		var currentHash = window.location.hash.replace('#', '');
		// check window hash value if it exist launch the click
		if(currentHash.length > 0 && jQuery('#Country' + currentHash).length > 0){
			//console.log('auto load in ' + currentHash);
			jQuery('#Country' + currentHash + ' a').click();
		}
	}

	
});


