// JavaScript Document
$(document).ready(function() {
	
	// COLLECTABLE CARDS (START)
	
	function setupCardClickActions() {
		$(".ajax-link").click(function() {
			
			var myHref = $(this).attr('href');
			var myImg = myHref.substring(0, (myHref.indexOf('?')));
			var vars = [], hash;
			var hashes = myHref.slice(myHref.indexOf('?') + 1).split('&');
			for(var i = 0; i < hashes.length; i++)
			{
				hash = hashes[i].split('=');
				vars.push(hash[0]);
				vars[hash[0]] = hash[1];
			}
			var myCardNumber = vars['cardnumber'];
			var myVideoLink = vars['videolink'];
			var myVideoLinkHtml = "";
			if(myVideoLink != ""){
				
				var mySwfLink = "/flash/general_video/dual_video_player.swf?mediaType=youtube&youtubeID="+cardVideoArray[myCardNumber];
				myVideoLinkHtml = '<div class="video-btn-wrap"><a href="'+mySwfLink+'" class="btn_next fl_left"><span>Play video</span></a>';
			}
			$('div.card-info').html('<h3 class="card-title">Card #'+myCardNumber+'</h3><span class="card-img-span"><span class="card-img-holder"><img src="'+myImg+'" alt="Card sample" /></span></span>'+myVideoLinkHtml+'</div>');
			
			$(".btn_next").fancybox({
				'padding'			: 0,
				'autoScale'			: false,
				'width'				: '646',
				'height'			: '362',
				'transitionIn'		: 'none',
				'transitionOut'		: 'none',
				'overlayColor'		: '#000', 
				'type'              : 'swf',
       			'swf'            	: {'flashvars': 'flvPath='+myVideoLink} 
			}); 
			
			$("div.card-info img").bind("load", function () { alignImage(); });
			$(".card-info").css("display","none");
			$( "#card-list li" ).removeClass("selected");
			$(this).parent().addClass("selected");
			return false;
		});
		
		
	}
	
	function displayCardByRef(target){
		var myHref = $(target).attr('href');
		var myImg = myHref.substring(0, (myHref.indexOf('?')));
		var vars = [], hash;
		var hashes = myHref.slice(myHref.indexOf('?') + 1).split('&');
		for(var i = 0; i < hashes.length; i++)
		{
			hash = hashes[i].split('=');
			vars.push(hash[0]);
			vars[hash[0]] = hash[1];
		}
		var myCardNumber = vars['cardnumber'];
		var myVideoLink = vars['videolink'];
		var myVideoLinkHtml = "";
		if(myVideoLink != ""){
			
			var mySwfLink = "/flash/general_video/dual_video_player.swf?mediaType=youtube&youtubeID="+cardVideoArray[myCardNumber];
			myVideoLinkHtml = '<div class="video-btn-wrap"><a href="'+mySwfLink+'" class="btn_next fl_left"><span>Play video</span></a>';
		}
		$('div.card-info').html('<h3 class="card-title">Card #'+myCardNumber+'</h3><span class="card-img-span"><span class="card-img-holder"><img src="'+myImg+'" alt="Card sample" /></span></span>'+myVideoLinkHtml+'</div>');
		
		$(".btn_next").fancybox({
			'padding'			: 0,
			'width'				: '646',
			'height'			: '362',
			'autoScale'			: false,
			'transitionIn'		: 'none',
			'transitionOut'		: 'none',
			'overlayColor'		: '#000', 
			'type'              : 'swf',
			'swf'            	: {'allowFullScreen' : 'true','allowfullscreen' : 'true','flashvars': 'flvPath='+myVideoLink} 
		}); 
		
		$("div.card-info img").bind("load", function () { alignImage(); });
		$(".card-info").css("display","none");
		$( "#card-list li" ).removeClass("selected");
		$(target).parent().addClass("selected");
	}
	
	function alignImage() {
		$(".card-info").css("display","block");
		var ah = $('.card-img-holder img').height();
		var ph = $('.card-img-span').height();
		//alert('ah='+ah);
		//alert('ph='+ph);
		var mh = Math.ceil((ph-ah) / 2);
		$('.card-img-holder').css('margin-top', mh);
		
		
		$(".card-info").css("display","none");
		$('.card-info').fadeIn();
		
		refreshCufon();
		
	}
	
	
	$( ".card-nav" ).each(
		function( intIndex ){
			$( this ).bind (
				"click",
				function(){
					var myStartNum = 1 + (intIndex * 28);
					var myEndNum = 28 + (intIndex * 28);
					if(myEndNum > 150){
						myEndNum = 150;
					}
					buildCardGrid(myStartNum, myEndNum)
					$("#card-list").css("display","none"); 
					$('#card-list').fadeIn();
					$( "#card-nav li" ).removeClass("selected");
					$(this).parent().addClass("selected");
					refreshCufon();
					return false;
				}
			);
		 
		}
	 
	);
	
	function buildCardGrid(cardStartNum, cardEndNum){
		$('#card-list').empty();
		var items = [];
		for( i=cardStartNum; i <= cardEndNum; i++){
			items.push('<li><a href="/imgs/collectable-cards/large/'+i+'.jpg?cardnumber='+i+'&videolink='+cardVideoArray[i]+'" class="ajax-link"><span><img src="/imgs/collectable-cards/'+i+'.png" alt="card '+i+'" /></span></a></li>');
			
			for( j=0; j <= cardVideoArray.length; j++){
				//alert(jQuery.inArray(i, cardVideoArray[j]));
			}
		}
		
		$('#card-list').append( items.join('') );
		setupCardClickActions();
		
		//displayCardByRef("#card-list li:first");
		
		
	}
	if ($('#card-list').length) {
		buildCardGrid(1, 28);
		$( "#card-list li:first" ).addClass("selected"); 
		displayCardByRef("#card-list li:first a");
	}
	// COLLECTABLE CARDS (END)
	
	// HOME PAGE SCROLL AREA (START)
	if ($('.scroll-pane').length) {
		$('.scroll-pane').jScrollPane({showArrows: true});
	}
	// HOME PAGE SCROLL AREA (END)
	
	if ($('.community_feature_nav').length) {
		$(".community_feature_tabdiv").hide(); //Hide all content
		$(".community_feature_nav li:first").addClass("active").show(); //Activate first tab
		$(".community_feature_tabdiv:first").show(); //Show first tab content
		
		var communityFeatureItems = $(".community_feature_nav li");
		var communityFeatureCurr = 0;
		
		//On Click Event
		$(".community_feature_nav li").click(function() {
	
			$(".community_feature_nav li").removeClass("active"); //Remove any "active" class
			$(this).addClass("active"); //Add "active" class to selected tab
			$(".community_feature_tabdiv").hide(); //Hide all tab content
			
			communityFeatureCurr = communityFeatureItems.index(this);
			var activeTab = $(this).find("a").attr("href"); //Find the href attribute value to identify the active tab + content
			$(activeTab).fadeIn(); //Fade in the active ID content
			
			return false;
		});
		
		
		$('#community_feature_controls_next').click(function() { // bind click event to link
			if(communityFeatureCurr == 3){
				communityFeatureCurr = 0;
			} else {
				communityFeatureCurr = (communityFeatureCurr+1);
			}
			$(".community_feature_nav li").removeClass("active");
			$(".community_feature_nav li:nth-child("+(communityFeatureCurr+1)+")").addClass("active");
			$(".community_feature_tabdiv").hide();
			var activeTab = $(".community_feature_nav li:nth-child("+(communityFeatureCurr+1)+")").find("a").attr("href"); 
			$(activeTab).fadeIn(); //Fade in the active ID content
			
			return false;
		});
		
		$('#community_feature_controls_prev').click(function() { // bind click event to link
			if(communityFeatureCurr == 0){
				communityFeatureCurr = 3;
			} else {
				communityFeatureCurr = (communityFeatureCurr-1);
			}
			$(".community_feature_nav li").removeClass("active");
			$(".community_feature_nav li:nth-child("+(communityFeatureCurr+1)+")").addClass("active");
			$(".community_feature_tabdiv").hide();
			var activeTab = $(".community_feature_nav li:nth-child("+(communityFeatureCurr+1)+")").find("a").attr("href"); 
			$(activeTab).fadeIn(); //Fade in the active ID content
			
			return false;
		});
	}

	//When page loads...
	if ($('.tabs').length) {
		$(".tab_content").hide(); //Hide all content
		$("ul.tabs li:first").addClass("active").show(); //Activate first tab
		$(".tab_content:first").show(); //Show first tab content
		refreshCufon();
		//On Click Event
		$("ul.tabs li").click(function() {
	
			$("ul.tabs li").removeClass("active"); //Remove any "active" class
			$(this).addClass("active"); //Add "active" class to selected tab
			$(".tab_content").hide(); //Hide all tab content
	
			var activeTab = $(this).find("a").attr("name"); //Find the href attribute value to identify the active tab + content
			$(activeTab).fadeIn(); //Fade in the active ID content
			
			// TRY $(activeTab).show(); FOR PS3
			
			if ($(activeTab + ' .scroll-pane').length) {
				$(activeTab + ' .scroll-pane').jScrollPane({showArrows: true});
			}
			//var exploreTickerInterval = setInterval(refreshCufon, 2000);
			refreshCufon();
			
			return false;
		});
	}
	
	function refreshCufon() {
		if(fancyFont){Cufon.refresh();}
	}
	
	
	// PROFILE PAGE VEHICLES AND TRACKS (START) 
	if ($('#profile_vehiclestracks_carousel_ul').length) {
        $('#profile_vehiclestracks_carousel_ul li:first').before($('#profile_vehiclestracks_carousel_ul li:last'));  
		
        $('#right_scroll img').click(function(){    
            var item_width = $('#profile_vehiclestracks_carousel_ul li').outerWidth();
            var left_indent = parseInt($('#profile_vehiclestracks_carousel_ul').css('left')) - item_width; 
            $('#profile_vehiclestracks_carousel_ul').animate({'left' : left_indent},500,function(){  
				$('#profile_vehiclestracks_carousel_ul li:last').after($('#profile_vehiclestracks_carousel_ul li:first'));  
				$('#profile_vehiclestracks_carousel_ul').css({'left' : '-200px'});  
            });  
        });  
		
        $('#left_scroll img').click(function(){  
  
            var item_width = $('#profile_vehiclestracks_carousel_ul li').outerWidth(); 
            var left_indent = parseInt($('#profile_vehiclestracks_carousel_ul').css('left')) + item_width;  
            $('#profile_vehiclestracks_carousel_ul').animate({'left' : left_indent},500,function(){  
  				$('#profile_vehiclestracks_carousel_ul li:first').before($('#profile_vehiclestracks_carousel_ul li:last'));  
				$('#profile_vehiclestracks_carousel_ul').css({'left' : '-200px'});  
            });  
  
        });  
	}
	// PROFILE PAGE VEHICLES AND TRACKS (END) 
	
	// HOME PAGE WHAT IS MOTORSTORM (START) 
	if ($('#home_whatis_motorstorm_carousel_ul').length) {
       // $('#home_whatis_motorstorm_carousel_ul li:first').before($('#home_whatis_motorstorm_carousel_ul li:last'));  
		$('#home_whatis_motorstorm_carousel_ul').css({'left' : '0'});
		var $currWhatIsTab = 0;
		
        $('#what_is_right_scroll a').click(function(){    
            var item_width = $('#home_whatis_motorstorm_carousel_ul li').outerWidth();
           // var left_indent = parseInt($('#home_whatis_motorstorm_carousel_ul').css('left')) - item_width; 
			$currWhatIsTab++;
			if($currWhatIsTab > 2){
				$currWhatIsTab = 0;
			}
			var left_indent = 0 - ($currWhatIsTab * item_width);
			
			/*
            $('#home_whatis_motorstorm_carousel_ul').animate({'left' : left_indent},500,function(){  
				$('#home_whatis_motorstorm_carousel_ul li:last').after($('#home_whatis_motorstorm_carousel_ul li:first'));  
				$('#home_whatis_motorstorm_carousel_ul').css({'left' : '-240px'});  
            });*/
			$('#home_whatis_motorstorm_carousel_ul').fadeOut(500, function() {
				// Animation complete.
				//$('#home_whatis_motorstorm_carousel_ul li:last').after($('#home_whatis_motorstorm_carousel_ul li:first'));  
				$('#home_whatis_motorstorm_carousel_ul').css({'left' : left_indent});  
				$('#home_whatis_motorstorm_carousel_ul').fadeIn(500, function() {
				// Animation complete.
			  });
			  });
			return false;
        });  
		
        $('#what_is_left_scroll a').click(function(){  
  
            var item_width = $('#home_whatis_motorstorm_carousel_ul li').outerWidth(); 
            //var left_indent = parseInt($('#home_whatis_motorstorm_carousel_ul').css('left')) + item_width;  
            
			$currWhatIsTab--;
			if($currWhatIsTab < 0){
				$currWhatIsTab = 2;
			}
			var left_indent = 0 - ($currWhatIsTab * item_width);
			
			$('#home_whatis_motorstorm_carousel_ul').fadeOut(500, function() {
				// Animation complete.
				//$('#home_whatis_motorstorm_carousel_ul li:last').after($('#home_whatis_motorstorm_carousel_ul li:first'));  
				$('#home_whatis_motorstorm_carousel_ul').css({'left' : left_indent});  
				$('#home_whatis_motorstorm_carousel_ul').fadeIn(500, function() {
				// Animation complete.
			  });
			  });
  			return false;
        });  
	}
	// PROFILE PAGE VEHICLES AND TRACKS (END) 
	
	// HOME PAGE EXPLORE TICKER (START) 
		if ($('#home_explore_ticker_right_carousel').length) {
			var $exploreTicker = $('#home_explore_ticker_right_carousel ul li');
			var $exploreTickerLength = $exploreTicker.length;
			var $numExploreTabs = Math.ceil($exploreTickerLength / 3);
			var $currExploreTab = 0;
			var $exploreDelay = 7000;
			var explorerStarted = false;
			
			
			function updateExploreTicker() {
				$currExploreTab ++;
				if($currExploreTab >= $numExploreTabs){
					$currExploreTab = 0;
				}
				var item_width = $currExploreTab * 728;
				var left_indent = -(item_width); 
				$('#home_explore_ticker_right_carousel ul').animate({'left' : left_indent},1000,function(){  
					
				}); 
				if(explorerStarted == false){
					explorerStarted = true;
					var exploreTickerInterval = setInterval(updateExploreTicker, $exploreDelay);
				}
			}
			updateExploreTicker();
			
			$("#home_explore_ticker_right_carousel ul li").mouseover(function () {
				clearInterval(exploreTickerInterval);
			});
			
			$("#home_explore_ticker_right_carousel ul li").mouseout(function () {
				exploreTickerInterval = setInterval(updateExploreTicker, $exploreDelay);
			});
		}
	// HOME PAGE EXPLORE TICKER (END) 
	
	
	// GAMES PAGE CAROUSEL (START) 
	if ($('#gamespage_carousel_ul').length) {
		
		var vehicleCounter = 0;
		var items = $('#gamespage_carousel_ul > li');
		
		for (var i=0;i<items.length;i++) {
				//alert(items[i]);
				if($(items[i]).hasClass('active')){
					vehicleCounter = i;
				}
		  }
		
		var vehicleCounterTop = ((Math.floor(vehicleCounter/3))	 * 3) + 3;
		
		var vehicleTotal = $('#gamespage_carousel_ul li').length;
		
		if(vehicleCounterTop > vehicleTotal){
			vehicleCounterTop = vehicleTotal;
		}
		
		var vehiclePages = Math.ceil(vehicleTotal/3);
		var blockAnimation = false;
		var start_item_width = $('#gamespage_carousel_ul li').outerWidth();
		var start_left_indent = 0 - ((Math.floor(vehicleCounter/3))	 * (start_item_width*3)); 
		
		$("#gamespage_carousel_ul li").removeClass("active"); //Remove any "active" class
		$('#gamespage_carousel_ul li:eq('+vehicleCounter+')').addClass("active"); //Add "active" class to selected tab
		$('#gamespage_carousel_ul').css("left",start_left_indent);
		
		var startTrackNum = ((Math.floor(vehicleCounter/3))	 * 3)+1;
		$('#carouselTracker').html((startTrackNum)+'-'+(vehicleCounterTop)+'/'+(vehicleTotal));
		refreshCufon();
		
        $('#gamespage_carousel_right_scroll a').click(function(){   
			if(blockAnimation != true){
				blockAnimation = true;
				var item_width = $('#gamespage_carousel_ul li').outerWidth();
				
				vehicleCounter = ((Math.floor(vehicleCounter/3))	 * 3)+3;
				if(vehicleCounter > (vehicleTotal-1)){
					vehicleCounter = 0;
				}
				vehicleCounterTop = vehicleCounter+3;
				if(vehicleCounterTop > vehicleTotal){
					vehicleCounterTop = vehicleTotal;
				}
				$('#carouselTracker').html((vehicleCounter+1)+'-'+(vehicleCounterTop)+'/'+(vehicleTotal));
				refreshCufon();
				
				var left_indent = 0 - ((vehicleCounter)	 * (item_width)); 
				$('#gamespage_carousel_ul').stop(true, false);
				$('#gamespage_carousel_ul').animate({'left' : left_indent},500,function(){   
					blockAnimation = false;
				});
				refreshCufon();
			}
			return false;
        });  
		
        $('#gamespage_carousel_left_scroll a').click(function(){  
			if(blockAnimation != true){
				blockAnimation = true;
				var item_width = $('#gamespage_carousel_ul li').outerWidth(); 
				
				vehicleCounter = ((Math.floor(vehicleCounter/3))	 * 3) - 3;
				if(vehicleCounter < 0){
					vehicleCounter = (vehiclePages-1) * 3;
				}
				vehicleCounterTop = vehicleCounter+3;
				if(vehicleCounterTop > vehicleTotal){
					vehicleCounterTop = vehicleTotal;
				}
				$('#carouselTracker').html((vehicleCounter+1)+'-'+(vehicleCounterTop)+'/'+(vehicleTotal));
				refreshCufon();
				
				var left_indent = 0 - ((vehicleCounter)	 * item_width);
				$('#gamespage_carousel_ul').stop(true, false);
				$('#gamespage_carousel_ul').animate({'left' : left_indent},500,function(){   
					blockAnimation = false;
				});
				refreshCufon();
  			}
			return false;
        });  
	}
	// GAMES PAGE CAROUSEL (END) 
	
	
	// COMMUNITY PAGE CAROUSEL (START) 
	if ($('#community_events_carousel_ul').length) {
        $('#community_events_carousel_ul li:first').before($('#community_events_carousel_ul li:last'));  
		
        $('#community_carousel_right_scroll a').click(function(){    
            var item_width = $('#community_events_carousel_ul li').outerWidth();
            var left_indent = parseInt($('#community_events_carousel_ul').css('left')) - item_width; 
            $('#community_events_carousel_ul').animate({'left' : left_indent},500,function(){  
				$('#community_events_carousel_ul li:last').after($('#community_events_carousel_ul li:first'));  
				$('#community_events_carousel_ul').css({'left' : '-222px'});  
            });  
        });  
		
        $('#community_carousel_left_scroll a').click(function(){  
  
            var item_width = $('#community_events_carousel_ul li').outerWidth(); 
            var left_indent = parseInt($('#community_events_carousel_ul').css('left')) + item_width;  
            $('#community_events_carousel_ul').animate({'left' : left_indent},500,function(){  
  				$('#community_events_carousel_ul li:first').before($('#community_events_carousel_ul li:last'));  
				$('#community_events_carousel_ul').css({'left' : '-222px'});  
            });  
  
        });  
	}
	// GAMES PAGE CAROUSEL (END) 
	
	// CUSTOMISE PANEL (START)
	
	if ($('#customiseLink').length) {
		
		var customiseOpen = false;
		var customiseLoaded = false;
		
        $('#customiseLink').click(function(){    
            if(customiseOpen == false){
				customiseOpen = true;
				$('#masthead').animate({'height' : 337},500,function(){  
					if(customiseLoaded == false){
						$('#customise-panel').load('customise-panel.html', function() {
						  $('#customise-panel').fadeIn("slow");
						});
						customiseLoaded = true;
					} else {
						$('#customise-panel').fadeIn("slow");
					}
				});
			} else {
				customiseOpen = false;
				$('#customise-panel').fadeOut("slow");
				$('#masthead').animate({'height' : 37},500,function(){  
					
				});
			}
        });
	}
	// CUSTOMISE PANEL (END)
	
	
	// FACEBOOK PANEL (START)
	
	if ($('#facebook_feed').length) {
		
		var facebookLoaded = false;
		if(facebookLoaded == false){
			facebookLoaded = true;
			$('#facebook_feed').load('facebook_feed.html');
		}
	}
	// FACEBOOK PANEL (END)
	
	if ($('select.styled').length) {
			
		$('select.styled').customStyle();
	}
	
});

// CUSTOM LIGHTBOX CODE
	
// display the lightbox
function lightbox(insertContent, ajaxContentUrl){
	
	// add lightbox/shadow <div/>'s if not previously added
	if($('#lightbox').size() == 0){
		var theLightbox = $('<div id="lightbox"/>');
		var theShadow = $('<div id="lightbox-shadow"/>');
		$(theShadow).click(function(e){
			
			closeLightbox();
			
		});
		
		$('body').append(theShadow);
		$('body').append(theLightbox);
	}

	// remove any previously added content
	$('#lightbox').empty();

	// insert HTML content
	if(insertContent != null){
		$('#lightbox').append(insertContent);
	}

	// insert AJAX content
	if(ajaxContentUrl != null){
		// temporarily add a "Loading..." message in the lightbox
		$('#lightbox').append('<p class="loading">Loading...</p>');
		
		
		// request AJAX content
		$.ajax({
			type: 'GET',
			url: ajaxContentUrl,
			success:function(data){
				// remove "Loading..." message and append AJAX content
				$('#lightbox').empty();

				$('#lightbox').append(data);
				
				
			},
			error:function(){
				alert('AJAX Failure!');
			}
		});
	}

	// move the lightbox to the current window top + 100px
	$('#lightbox').css('top', $(window).scrollTop() + 200 + 'px');

	// display the lightbox
	$('#lightbox').show();
	$('#lightbox-shadow').show();
	
}
var flashCode = "";
// display the lightbox
function lightboxInline(insertContent){
	
	// add lightbox/shadow <div/>'s if not previously added
	if($('#lightbox').size() == 0){
		var theLightbox = $('<div id="lightbox"/>');
		var theShadow = $('<div id="lightbox-shadow"/>');
		$(theShadow).click(function(e){
			
			closeLightbox();
			
		});
		
		$('body').append(theShadow);
		$('body').append(theLightbox);
	}

	// remove any previously added content
	$('#lightbox').empty();

	// insert HTML content
	if(insertContent != null){
		$('#lightbox').append(insertContent);
	}

	// insert AJAX content
	alert("flashCode="+flashCode);
	if(flashCode != null){
		$('#lightbox').append(flashCode);
	}
	
	// move the lightbox to the current window top + 100px
	$('#lightbox').css('top', $(window).scrollTop() + 200 + 'px');

	// display the lightbox
	$('#lightbox').show();
	$('#lightbox-shadow').show();
	
}

// close the lightbox
function closeLightbox(){
	
	// hide lightbox and shadow <div/>'s
	$('#lightbox').hide();
	$('#lightbox-shadow').hide();

	// remove contents of lightbox in case a video or other content is actively playing
	$('#lightbox').empty();
}

(function($){
	$.fn.extend({
	
	customStyle : function(options) {
		if(!$.browser.msie || ($.browser.msie&&$.browser.version>6)){
		return this.each(function() {
		
			var currentSelected = $(this).find(':selected');
			$(this).after('<span class="customStyleSelectBox"><span class="customStyleSelectBoxInner">'+currentSelected.text()+'</span></span>').css({position:'absolute', opacity:0,fontSize:$(this).next().css('font-size')});
			var selectBoxSpan = $(this).next();
			var selectBoxWidth = parseInt($(this).width()) - parseInt(selectBoxSpan.css('padding-left')) -parseInt(selectBoxSpan.css('padding-right'));
			var selectBoxSpanInner = selectBoxSpan.find(':first-child');
			selectBoxSpan.css({display:'inline-block'});
			selectBoxSpanInner.css({width:selectBoxWidth, display:'inline-block'});
			var selectBoxHeight = parseInt(selectBoxSpan.height()) + parseInt(selectBoxSpan.css('padding-top')) + parseInt(selectBoxSpan.css('padding-bottom'));
			$(this).height(selectBoxHeight).change(function(){
			selectBoxSpanInner.text($(this).val()).parent().addClass('changed');
			});
			
			});
			}
		}
	});
})(jQuery);


