//Define jquery for ipad rewards

(function ($) {

/* Author: 

*/
	$(document).ready(function()
	{

		// FOR IPAD/IPHONE POPOVER

		// new linking to utilize ipadview template
		

		// if(window.location.href.indexOf('mode=popover') > -1)
		// {
		// 	$('body').addClass('popover');

		// 	$('#menu-faq a, #the-post p a').each(function() {
		//     $(this).attr('href', $(this).attr('href') + '?mode=popover');
		// 	});
		// }
	            
	  if($('#top-scores').length){
	  
	  // create MG leaders table:
	  
	  var lt = document.createElement('table');
	  $(lt).attr('id','leaders');
	  $(lt).append('<tbody></tbody>');
	  
	  $('#top-scores').append(lt);
	  
	  // Get the XML doc. Right now this pulls from the same directory.
	  // Reccommend keeping the XML file on the same server. Otherwise, this
	  // call will need to be expanded on to handle xdomain. This is meant to
	  // be a quick and dirty solution to automating.
	  
	  // XML file works as is. This code assumes that the XML file has already
	  // been sorted with highest score at top (descending). The example I was
	  // sent was sorted. If you want to handle cases where it might not, then
	  // sorting will have to be built into this method.
	  
	  $.get("/misc_viggle_files/leaders.xml", function(d){
	        
	    $(d).find('row').each(function(i){
	                          
	      var values = $(this).children('value');
	      
	      // new row
	      var tr = document.createElement("tr");
	      
	      // rank column
	      var rank = document.createElement('td');
	      $(rank).addClass('rank');
	      $(rank).addClass('collegiate');
	      $(rank).html(i+1);
	      
	      // username column
	      var username = document.createElement('td');
	      $(username).addClass('displayName');
	      $(username).html($(values[2]).text());
	      
	      // score column
	      var score = document.createElement('td');
	      $(score).addClass('score');
	      $(score).html(addCommas($(values[1]).text()));
	      
	      // append columns to row
	      $(tr).append(rank);
	      $(tr).append(username);
	      $(tr).append(score);
	      
	      // append row to table
	      $('#leaders > tbody').append(tr);
	      
	      });
	    }).fail(function(a, b, e){
		    if(window.console)
		    {
		    console.log("FAILLLL " + e);
		    }
		    });
	  };

		// SLIDER
		//
		//
		if ($('#homepage').length)
		{
			
			var features = $('#main-feature li').length; // Count the number of slider items there are
			var featureOffset = (features - 1) * 100;
			var counter = 1;
		
			// This is the default animation for the slider
			interval = setInterval(function() // global
			{
				counter++;
				frontPageSlider();
				if (counter == features)
				{
					counter = 1;
					$('#main-feature li').animate
					({
						left: '+=' + featureOffset + '%',
						easing: 'easeInCubic'
					}, 0, function()
					{
						// animation complete
					});
				}
			}, 6000);

			// This pauses and then restarts the slider on hover
			$('#main-feature li').hover(function()
			{
				clearInterval(interval);
			}, function()
			{
				// This is the default animation for the slider
				interval = setInterval(function() // Needed to set this globally otherwise we essentially had multiple "intervals"
				{
					counter++;
					frontPageSlider();
					if (counter == features)
					{
						counter = 1;
						$('#main-feature li').animate
						({
							left: '+=' + featureOffset + '%',
							easing: 'easeInCubic'
						}, 0, function()
						{
							// animation complete
						});
					}
				}, 6000);
			});

			// Manual navigation
			$('#slider-left').click(function()
			{
				if (counter != 1)
				{
					counter--;
					clearInterval(interval);
					$('#main-feature li').animate
					({
						left: '+=100%',
						easing: 'easeInCubic'
					}, 2000, function()
					{
						// animation complete
					});
					// This is the default animation for the slider
					interval = setInterval(function() // Needed to set this globally otherwise we essentially had multiple "intervals"
					{
						counter++;
						frontPageSlider();
						if (counter == features)
						{
							counter = 1;
							$('#main-feature li').animate
							({
								left: '+=' + featureOffset + '%',
								easing: 'easeInCubic'
							}, 0, function()
							{
								// animation complete
							});
						}
					}, 6000);
				}
				else
				{
					clearInterval(interval);
					$('#main-feature li').animate
					({
						left: '-=' + featureOffset + '%',
						easing: 'easeInCubic'
					}, 0, function()
					{
						// animation complete
					});
					counter = features - 1;
					$('#main-feature li').animate
					({
						left: '+=100%',
						easing: 'easeInCubic'
					}, 2000, function()
					{
						// animation complete
					});
					interval = setInterval(function() // Needed to set this globally otherwise we essentially had multiple "intervals"
					{
						counter++;
						frontPageSlider();
						if (counter == features)
						{
							counter = 1;
							$('#main-feature li').animate
							({
								left: '+=' + featureOffset + '%',
								easing: 'easeInCubic'
							}, 0, function()
							{
								// animation complete
							});
						}
					}, 6000);
				}
			}); // end slider left

			$('#slider-right').click(function()
			{
				if (counter != features)
				{
					counter++;
					clearInterval(interval);
					$('#main-feature li').animate
					({
						left: '-=100%',
						easing: 'easeInCubic'
					}, 2000, function()
					{
						// animation complete
					});
					// This is the default animation for the slider
					interval = setInterval(function() // Needed to set this globally otherwise we essentially had multiple "intervals"
					{
						counter++;
						frontPageSlider();
						if (counter == features)
						{
							counter = 1;
							$('#main-feature li').animate
							({
								left: '+=' + featureOffset + '%',
								easing: 'easeInCubic'
							}, 0, function()
							{
								// animation complete
							});
						}
					}, 6000);
				}
				else
				{
					clearInterval(interval);
					$('#main-feature li').animate
					({
						left: '+=' + featureOffset + '%',
						easing: 'easeInCubic'
					}, 0, function()
					{
						// animation complete
					});
					counter = 2;
					$('#main-feature li').animate
					({
						left: '-=100%',
						easing: 'easeInCubic'
					}, 2000, function()
					{
						// animation complete
					});
					interval = setInterval(function() // Needed to set this globally otherwise we essentially had multiple "intervals"
					{
						counter++;
						frontPageSlider();
						if (counter == features)
						{
							counter = 1;
							$('#main-feature li').animate
							({
								left: '+=' + featureOffset + '%',
								easing: 'easeInCubic'
							}, 0, function()
							{
								// animation complete
							});
						}
					}, 6000);
				}
			});

		}


		// Fade in for show or rewards description

		$('#learnmore').click(function()
		{
			$('#show-meta aside, #reward-meta aside').fadeIn('fast');
			$('#learnmore-close').show();
			$('#learnmore').hide();
			$('#show-meta aside:empty').text('Sorry, we don\'t currently have a description for this show.');
			$('#reward-meta aside:empty').text('Sorry, we don\'t currently have any more information about this reward.');
		});

		$('#learnmore-close').click(function()
		{
			$('#show-meta aside, #reward-meta aside').fadeOut('fast');
			$('#learnmore-close').hide();
			$('#learnmore').show();
		});

		$('.griditem').click(function()
		{
			$('#show-meta aside, #reward-meta aside').hide();
			$('#learnmore-close').hide();
			$('#learnmore').show();
		})


		// My Guy Scrolling
		// Scrolling for #basketballSchedule
		if($('#basketballSchedule').length)
		{
			var basketballTableHeight = $('#basketballSchedule table').height();
			var basketballDivHeight = $('#basketballSchedule').height();
			var basketballMaxOffset = basketballTableHeight/basketballDivHeight;
			var basketballMaxOffset = Math.round(basketballMaxOffset).toFixed(0);
			var basketballOffset = 0;

			$('#basketballSchedule').hover(function()
			{
				$('#basketballSchedule .nav-up').fadeIn();
				$('#basketballSchedule .nav-down').fadeIn();
			}, function()
			{
				$('#basketballSchedule .nav-up').fadeOut();
				$('#basketballSchedule .nav-down').fadeOut();
			});

			// up animation
			$('#basketballSchedule .nav-down').click(function()
			{
				if (basketballOffset != basketballMaxOffset)
				{
					$('#basketballSchedule table').animate
					({
						top: '-=18.625em'
					}, 1000, function()
					{
						//animation complete
					});
					basketballOffset++;
				}
			});

			// down animation
			$('#basketballSchedule .nav-up').click(function()
			{
				if (basketballOffset != 0)
				{
					$('#basketballSchedule table').animate
					({
						top: '+=18.625em'
					}, 1000, function()
					{
						//animation complete
					});
					basketballOffset--;
				}
			});
		}


		// Scrolling for #footballSchedule
		if($('#footballSchedule').length)
		{
			var footballTableHeight = $('#footballSchedule table').height();
			var footballDivHeight = $('#footballSchedule').height();
			var footballMaxOffset = footballTableHeight/footballDivHeight;
			var footballMaxOffset = Math.round(footballMaxOffset).toFixed(0);
			var footballOffset = 0;

			$('#footballSchedule').hover(function()
			{
				$('#footballSchedule .nav-up').fadeIn();
				$('#footballSchedule .nav-down').fadeIn();
			}, function()
			{
				$('#footballSchedule .nav-up').fadeOut();
				$('#footballSchedule .nav-down').fadeOut();
			});

			// up animation
			$('#footballSchedule .nav-down').click(function()
			{
				if (footballOffset != footballMaxOffset)
				{
					$('#footballSchedule table').animate
					({
						top: '-=18.625em'
					}, 1000, function()
					{
						//animation complete
					});
					footballOffset++;
				}
			});

			// down animation
			$('#footballSchedule .nav-up').click(function()
			{
				if (footballOffset != 0)
				{
					$('#footballSchedule table').animate
					({
						top: '+=18.625em'
					}, 1000, function()
					{
						//animation complete
					});
					footballOffset--;
				}
			});
		}

		 // Adding classes to the <body> dependent on browser

	  if($.browser.webkit)
	  {
	    var userAgent = navigator.userAgent.toLowerCase();
	    $.browser.chrome = /chrome/.test(navigator.userAgent.toLowerCase());

	    // Is this a version of Chrome?
	    if($.browser.chrome)
	    {
	      userAgent = userAgent.substring(userAgent.indexOf('chrome/') +7);
	      userAgent = userAgent.substring(0,userAgent.indexOf('.'));
	      $.browser.version = userAgent;
	      // If it is chrome then jQuery thinks it's safari so we have to tell it it isn't
	      $('body') .addClass('chrome');
	    }
	    else
	    {
	      $('body') .addClass('safari');
	    }
	  }

	  if($.browser.mozilla)
	  {
	    $('body') .addClass('mozilla');
	  }

	  if($.browser.msie && $.browser.version.substr(0,1)<8)
	  {
	    $('body') .addClass('ie7 ie');
	  }

	  if($.browser.opera)
	  {
	    $('body') .addClass('opera');
	  }

	  // This should only be running on pages where we need the twitter feed
	  if ($('#homepage').length)
	  {
		  getTwitter();
	  	setInterval("getTwitter()", 10000);
	  }

	  // Kind of a temporary cheat
	  $('.sub-menu .sub-menu .current-menu-item').parent('ul').addClass('active-sub-menu');
	  $('.sub-menu .sub-menu .current-menu-item').parent('ul').parent('li').addClass('current-menu-parent');

	  // 

	});

	// FUNCTIONS
	//
	//

	function totallyEmpty()
	{

	}

	function setIntervalX(func, delay, times, callback) {
	    if (times > 0) {
	        setTimeout(function() {
	            func.apply(arguments.callee);
	            setIntervalX(func, delay, --times, callback);
	        }, delay);
	    } else {
	        callback.apply(this);
	    }
	}

	function addCommas(nStr)
	{
		nStr += '';
		x = nStr.split('.');
		x1 = x[0];
		x2 = x.length > 1 ? '.' + x[1] : '';
		var rgx = /(\d+)(\d{3})/;
		while (rgx.test(x1)) 
		{
			x1 = x1.replace(rgx, '$1' + ',' + '$2');
		}
		return x1 + x2;
	}


	// Front page slider
	var frontPageSlider = function()
	{
		$('#main-feature li').animate
			({
				left: '-=100%'
			}, 2000, function()
			{
				// animation complete
			});
	}


	var getTwitter = function() 
	{
		//Twitter calls
		var twitter_api_url = 'http://search.twitter.com/search.json';
		var num_of_tweets = 2;

		// Enable caching
	  $.ajaxSetup({ cache: true });

		//Getting JSON
		$.getJSON(twitter_api_url + '?q=%23viggletv&with_twitter_user_id=true&rpp=' + num_of_tweets + '?callback=?', twitterFeed);
		
		function twitterFeed(data){

			var htmlString = "";
					item = 4;

			$.each(data.results, function(i,item){

				var date_tweet = new Date(item.created_at),
					  date_now = new Date(),
					  date_diff = date_now - date_tweet,
					  minutes = Math.round(date_diff/ (1000*60)),
					  twitterTime;

				if (minutes < 2) {
					//when it's less than a 2 minutes
					twitterTime = 'a minute ago';

				} else if (minutes < 60 ){
					//when it's less than an hour
					twitterTime = minutes + ' minutes ago';

				} else if (minutes < 1440) {
					//when it's less than a day
					minutes = Math.round(minutes / 60);
					twitterTime = minutes + ' hours ago';
			
				} else {
					twitterTime = date_tweet.format("mmmm d, yyyy");
				}
		      
		 		// Here's where we piece together the HTML
		    htmlString += '<li class="tweet"><img class="twitterUser" src="' + item.profile_image_url + '" />';
		    htmlString += '<div class="tweetCol"><h3>' + item.from_user_name + '</h3>';
		    htmlString += '<p>' + item.text + '</p>';
		    htmlString += '<div class="tweetTime"><img class="twitterBird" src="https://twitter.com/images/resources/twitter-bird-light-bgs.png" /> <span class="twitterTime">' + twitterTime + '</span></div>';
		 		htmlString += '</div><div class="bubble-tip"> </div>';
		 		htmlString += '</li><!-- end tweet -->';
		  });

			$('.twitter-feed').replaceWith('<ul class="twitter-feed">' + htmlString + '</li>');
		}

	}


})(jQuery);