function cycleBestTabs(inBox,theWay) {
  theTab = bestActTab[inBox];
  theNext = 0;
  otherWay = "left";
  
  if (theWay == "left") { 
    otherWay = "right"; 
    if (theTab != maxBestSlides) { theNext = theTab + 1; }
  } else {
    if (theTab == 0) { 
      theNext = maxBestSlides; 
    } else {
      theNext = theTab - 1;
    }
  }
  
  
  currentBox = "#best_of_"+inBox+"_"+theTab;
  nextBox = "#best_of_"+inBox+"_"+theNext;

  $(currentBox).hide("slide", { direction: theWay });
  $(nextBox).show("slide", { direction: otherWay });
  
  bestActTab[inBox] = theNext;
  changeTabdot(inBox);
}

function changeTabdot(inSec) {
  theTabRoot = "#tabdot_"+inSec;
  theTabMark = theTabRoot+"_"+bestActTab[inSec];
// alert("TabRoot:"+theTabRoot+" TabMark:"+theTabMark); 
  for (td=0;td<=maxBestSlides;td++) {
    tempDotid="#tabdot_"+inSec+"_"+td;
    $(tempDotid).removeClass('tab_dot_on');
  }
   $(theTabMark).addClass('tab_dot_on');
}

function startTheShow() {
  $(window).everyTime(ss, function() {
    stepThru();
  }, 0);		
}
function stepThru() {
    $(window).stopTime();
    currentSlide = slideIndex;
    nextSlide = currentSlide + 1;
    if (currentSlide == 3) {
      nextSlide = 0;
    }
    targetThumb = ".pos_"+currentSlide;
    nextThumb = ".pos_"+nextSlide;
    targetSlide = ".main_slide_"+currentSlide;
    nextSlide = ".main_slide_"+nextSlide;
    $(targetSlide).hide("slide", { direction: "up" });
    $(nextSlide).show("slide", { direction: "down" });
    $(targetThumb).hide("slide", { direction: "down" });
    $(nextThumb).show("slide", { direction: "up" });
    
    if (slideIndex == 3) {
      slideIndex = 0;
    } else {
      slideIndex++;
    }
    
    startTheShow();
}
function balanceThem (leftT,lBal,rightT,rBal) {
  theDiff = 0;
  lHeight = $(leftT).outerHeight();
  rHeight = $(rightT).outerHeight();
  theDiff = lHeight - rHeight;
  
  if (theDiff > 0) {
    $(rBal).height($(rBal).height()+theDiff);
  } else {
    theDiff = theDiff * -1;
    $(lBal).height($(lBal).height()+theDiff);
  }
}	
		
$(document).ready(function(){		
  startTheShow();
  
  $('.thumb_bottom_caption h2 a').each(function(){
      var theLink = $(this).attr('href');
       $(this).closest($("div[class^='pos_']")).click(function(){
          window.location.href=theLink;
       });
  });
  $('.slide_bottom_caption h2 a').each(function(){
      var theLink = $(this).attr('href');
       $(this).closest($("div[class^='main_slide_']")).click(function(){
          window.location.href=theLink;
       });
  });
  $('#a1_container').hover(function() {
      $(window).stopTime();
    },function(){
      startTheShow();
  });
  $('.vid_thumb_img a').each(function(){
      var theLink = $(this).attr('href');
       $(this).closest($("div[class^='vid_thumb_card'],div[class^='pop_thumb_card']")).click(function(){
          window.location.href=theLink;
       });
  });
  $('.vid_card a').each(function(){
      var theLink = $(this).attr('href');
       $(this).closest($("div[class^='vid_card']")).click(function(){
          window.location.href=theLink;
       });
  });
  $('.email_signup_button').hover(function(){
      $(this).addClass('email_signup_button_on');
     },
     function(){
      $(this).removeClass('email_signup_button_on');
  });
  
  $('.vid_thumb_card, .pop_thumb_card, .gold_tab, .vid_card, .best_of_tab').hover(function(){
      $(this).addClass('vid_thumb_card_over');
     },
     function(){
      $(this).removeClass('vid_thumb_card_over');
  });
  
  var onState = "";
  $('.btn_more, .btn_arrow').hover(function(){
      classRoot = $(this).attr('class');
      onState = classRoot+"_on";
      $(this).addClass(onState);
     },
     function(){
      $(this).removeClass(onState);
  });
  /*AdFactory.loadBillboard(function(html) {
			$('#adspace').html(html);
		});*/
  balanceThem(".popular_clips_column","#pop_col_bal",".gold_eps_column","#gold_col_bal"); 
  balanceThem(".feat_column","#feat_col_bal",".right_two","#best_col_bal");
  balanceThem("#left_column","#feat_col_bal","#right_column","#right_col_bal");
  balanceThem(".feat_column","#feat_col_bal",".right_two","#best_col_bal");
   
  $(window).blur(function() {
     $(window).stopTime();
  });
  $(window).focus(function() {
     startTheShow();
  });    	
  
  if (!swfobject.getObjectById(Player.name)) {
	Player.embed();
  }	
});			

var Player = {
	name: "adultswimPromoPlayer",		//name to refer to the swf object
	currentVideo: 0,					//the current video index playing (cooresponds to the li elements in the html)
	currentSegment: 0,					//the current segment playing in the promo player
	currentVideoInfo: {},				//the info feeding into the playing about the video playing
	pageURL: window.location,			//the url of the page your on
	pageChanged: false,					//boolean for tracking if the user changes the page of content
	goldVideoHTML: [],					//video to play	when user selects the gold tab
	playerURL: (location.hostname == 'video.adultswim.com') ? '/tools/swf/promovplayer.swf' : '/tools/swf/promovplayer_dev.swf',
	playerXML: (location.hostname == 'video.adultswim.com') ? 'player_configs/promo_player.xml' : 'player_configs/promo_player_dev.xml',
	
	embed: function() {
		var params = {
			allowscriptaccess: 'always',
			allownetworking: 'all',
			allowfullscreen: true,
			wmode: 'transparent',
			base: "/tools/swf/"
		}
		
		var attributes = {
			id: Player.name,
			name: Player.name
		};
		
		swfobject.embedSWF(Player.playerURL, "video-swf", "276", "139", "9", false, {configURL: Player.playerXML, JSEventHandler: "Player.onPlayerEvent"}, params, attributes);
			
	},
	
	playVideo: function(videoInfo) {
		Utilities.log('videoInfo: \n\tsegmentIndex: ' + videoInfo.segmentIndex + '\n\tsegmentID: ' + videoInfo.segmentID + '\n\tepisodeID: ' + videoInfo.episodeID + '\n\ttitle: ' + videoInfo.title + '\n\tcontentType: ' + videoInfo.contentType + '\n\tcollectionTitle: ' + videoInfo.collectionTitle + '\n\tcollectionID: ' + videoInfo.collectionID + '\n\tvideoPageURL: ' + videoInfo.videoPageURL + '\n\tsectionID: ' + videoInfo.sectionID + '\n\tduration: ' + videoInfo.duration + '\n\trating: ' + videoInfo.rating);
		
		swfobject.getObjectById(Player.name).setMedia(videoInfo);
	},
	
	/*nextVideo: function() {
		//if the user has changed the page using the pagination
		//set the current video back to the start and reset the boolean
		if (Player.pageChanged == true) {
			Player.currentVideo = 0;
			Player.pageChanged = false;
		}
		//if the page has not changed, iterate up the current video index
		else {
			Player.currentVideo++;
		}
		
		//reset segments
		Player.currentSegment = 0;
	},*/
	
	omniture: function(p_type, p_context_contentType, p_context_collectionTitle, p_context_title, p_context_segmentIndex){

		try{Utilities.log('!!-0-!!')}catch(e){try{Utilities.log('e',e.name,e.message)}catch(e){}};
		try{Utilities.log('p_context_contentType:',p_context_contentType)}catch(e){try{Utilities.log('e',e.name,e.message)}catch(e){}};
		try{Utilities.log('p_context_collectionTitle:',p_context_collectionTitle)}catch(e){try{Utilities.log('e',e.name,e.message)}catch(e){}};
		try{Utilities.log('p_context_title:', p_context_title)}catch(e){try{Utilities.log('e',e.name,e.message)}catch(e){}};
		try{Utilities.log('p_context_segmentIndex:', p_context_segmentIndex)}catch(e){try{Utilities.log('e',e.name,e.message)}catch(e){}};
		try{Utilities.log('p_type:',p_type)}catch(e){try{Utilities.log('e',e.name,e.message)}catch(e){}};
		
		
		var videoData = {};
		if(p_type == "video-start"){
			videoData.autoplayed = true; // watch player = $.cookie(Video._cookie_continuousEnabled);
			videoData.duration = $(Player.getVideoInfo()).attr('duration');
		}
		
		videoData.id = $(Player.getVideoInfo()).attr('segmentID');
		videoData.title = p_context_collectionTitle + ': ' + p_context_title;
		videoData.type = p_context_contentType;
		videoData.promo_video = "";
		videoData.segment = p_context_segmentIndex;
		videoData.showname = p_context_collectionTitle;

		Utilities.log('<-0->',videoData);
		Utilities.log('<-o->',p_type);
		Utilities.log('!<-0->!',videoData.duration,videoData.id,videoData.title,videoData.type,videoData.segment);
		
		try {
			Utilities.log('|-o-|')
			Utilities.log('|-p-|',p_type)
			Utilities.log('|-v-|',videoData)
			trackMetrics({
				type: p_type,
				data: {
					video : videoData
				}
			});
		} catch(e){
			Utilities.log('omni error',e.name, ' : ', e.message)
		}
	},
	getVideoInfo: function() {
		Player.currentVideoInfo = VideoClips.objPlayList[VideoClips.nCount];
		Utilities.log('Player.currentVideoInfo: ' + Player.currentVideoInfo);

		return Player.currentVideoInfo;
	},
	
	onPlayerEvent: function(p_event) {
		Utilities.log(p_event.type);
		
		switch (p_event.type) {
			case 'playerInitSucceeded':
				VideoClips.loadClips();
				
				break;
			case 'contentPlayStarted':
				//turn on next button always
				swfobject.getObjectById(Player.name).setNextEnabled(true);
				
				//turn on the prev button
				swfobject.getObjectById(Player.name).setPreviousEnabled(true);
				
				break;
			case 'contentPlayEnded':
				 setTimeout ( "VideoClips.iterateUp();Player.playVideo(Player.getVideoInfo());", 1800 );
				
				
				break;
			case 'continuousPlaySet':
				
				break;
			case 'nextClicked':
				swfobject.getObjectById(Player.name).setPreviousEnabled(false);
				swfobject.getObjectById(Player.name).setNextEnabled(false);
				
				VideoClips.iterateUp();
				Player.playVideo(Player.getVideoInfo());
		
				break;
			case 'previousClicked':
				//turn off the nav buttons
				swfobject.getObjectById(Player.name).setPreviousEnabled(false);
				swfobject.getObjectById(Player.name).setNextEnabled(false);
				
				//decrement the segment and play it
				//Player.currentSegment--;
				
				VideoClips.iterateDown();
				Player.playVideo(Player.getVideoInfo());
				
				break;
			case 'muteStateChanged':
				
				break;
			case 'adPlayStarted':
				//turn off the buttons
				swfobject.getObjectById(Player.name).setPreviousEnabled(false);
				swfobject.getObjectById(Player.name).setNextEnabled(false);
				
				break;
			case 'adPlayEnded':
				
				break;
			case 'contentPlaylistFailed':
				swfobject.getObjectById(Player.name).showRelateds(true, 'Sorry. Looks like ' + Player.currentVideoInfo.title + ' is no longer available. You may like these instead. Or you may not.');
				
				break;
			default:
				break;
		}
	}
}

var VideoClips = {
	bFail:false,
	nCount:0,
	nTotz:0,
	objPlayList: {},
	iterateUp:function(){
		if(VideoClips.nCount >= VideoClips.nTotz) {
			VideoClips.nCount = 0;
		} else {
			VideoClips.nCount++;
		}
	},
	iterateDown:function(){
		if(VideoClips.nCount <= 0) {
			VideoClips.nCount = VideoClips.nTotz;
		} else {
			VideoClips.nCount--;
		}
	},
	loadClips:function(){
		$.ajax({
			type: "GET",
			url: "/adultswimdynamic/asfix-svc/episodeSearch/getAllEpisodes?limit=10&offset=0&sortByDate=DESC&filterByEpisodeType=CLI&networkName=AS",
			dataType: "xml",
			error: function(xhr, desc, exceptionobj) {
				Utilities.log('error',xhr, desc, exceptionobj)
			},
			success: function(xml) {
				VideoClips.bFail = true;
				VideoClips.nTotz = $(xml).find('episode').length;
				$(xml).find('episode').each(function(i) {
					var obj = VideoClips.objPlayList[i] = {};
					obj.segmentIndex = 0;
					obj.segmentID = $(this).find('segments').find('segment').eq(0).attr('id');
					obj.episodeID = $(this).attr('id');
					obj.customID = 'AS-'+$(this).attr('id');
					obj.title = $(this).attr('title');
					obj.contentType = 'CLI';
					obj.collectionTitle = jQuery.trim($(this).attr('collectionTitle'));
					obj.collectionID = $(this).attr('collectionId');
					obj.videoPageURL = $(this).find('episodeLink').attr('episodeUrl');
					obj.sectionID = Page.freewheelID;
					obj.duration = $(this).find('segments').find('segment').eq(0).attr('duration');
					obj.rating = $(this).attr('rating');
				});
				
				Player.playVideo(Player.getVideoInfo());
			},
			complete: function() {
				
			}
		})
	}
}
