// Video
var selectedTout = 0;
var selectedToutName = "";
var videoTitles = [];
$(document).ready(function(){
   	//multimedia
	var tb1 = $("#tabChange1");
	var tb2 = $("#tabChange2");
	var tb3 = $("#tabChange3");	
	tb1.bind("click keydown keypress", function(){
	  $("#more").html("<a href='/time/video/'>More Videos &raquo;</a>");
	  changeMultimediaTab(1);
	  return false
	 });
	tb2.bind("click keydown keypress", function(){
		$("#more").html("<a href='/time/podcasts/'>More Podcasts &raquo;</a>");
		changeMultimediaTab(2);
		return false;		
	});	
	tb3.bind("click keydown keypress", function(){
		$("#more").html("<a href='/time/photoessays/'>More Photos &raquo;</a>");
		changeMultimediaTab(3);
		return false;		
	});		
	var vidUrl = $("#videoUrl").text();
	importVideoAjaxXML(vidUrl);
});			
	
function changeMultimediaTab(num) {
	$("#tab1, #tab2, #tab3, #tab4").attr("class", "");
	$("#tabContent1, #tabContent2, #tabContent3, #tabContent4").attr("class", "off");
	$("#tab"+num).attr("class", "on");
	$("#tabContent"+num).attr("class", "");
}

function currentVideoSelect(num, vidTitle) {
	$("#tout"+selectedTout).attr("class", "tout");	
	$("#tout"+num).attr("class", "tout on");
	selectedTout = num;
	selectedToutName = vidTitle;
	$("#videoName").empty();
	$("#videoName").html(vidTitle);
	return(num);
}

function currentVideoHover(num, vidTitle) {
	if (selectedTout != num) {
		$("#tout"+num).attr("class", "tout hover");
	}
	$("#videoName").html(vidTitle);
}

function currentVideoHoverOut(num, vidTitle) {
	if (selectedTout != num) {
		$("#tout"+num).attr("class", "tout");
	}
	$("#videoName").html(selectedToutName);
}

function importVideoAjaxXML(vidUrlVal) {
	$.get(vidUrlVal, "", function(data){
		firstPlayer(data);
  	    createVideo(data);		
		$("#tout0, #tout1, #tout2, #tout3").each(function(i){
			var position = $(this).attr("id").replace("tout", "");
			$(this).bind("click keydown keypress", function(){
				callFlash("loadTitleById", getVideo(data, position));
				var newHTML = $("#videoLink" + position).html();
				$("#curVid").html(newHTML);
			});
		});
	});
}

function firstPlayer(videoRes) {
	var playerId = $(videoRes).find("item:eq(0)").children("bc\\:playerid").eq(0).text();
	var lineupId = $(videoRes).find("item:eq(0)").children("bc\\:lineupid").eq(0).text();
	var videoId = $(videoRes).find("item:eq(0)").children("bc\\:titleid").eq(0).text();
	var title = $(videoRes).find("item:eq(0)").children("title").eq(0).text();
	var config = new Array();
	config["videoId"] = videoId; //the default video loaded into the player
	config["videoRef"] = null; //the default video loaded into the player by ref id specified in console
	config["lineupId"] = lineupId; //the default lineup loaded into the player
	config["playerTag"] = null; //player tag used for identifying this page in brightcove reporting
	config["autoStart"] = false; //tells the player to start playing video on load
	config["preloadBackColor"] = "#FFFFFF"; //background color while loading the player
	config["width"] = 288;
	config["height"] = 255;
	config["playerId"] = playerId;
	config["continuousPlay"] = true;
	createExperience1(config,8,'bcvideo');
}

function onTemplateLoaded(errorMessage) {
	callFlash("addEventListener", "mediaComplete", "onMediaComplete"); //adds a listener for when a title reaches its duration
}
var titleIds; //sets a titleIds variable to null - this is important for the onMediaComplete() function
var counter = 0; //sets a counter variable so that we can increment through the different titles later
var vidState = false;

function getFeaturedLineup_Result(lineupDTO) {
	titleIds = []; //starts an array

	for(i = 0; i < lineupDTO.videoIds.length; i++) {
		titleIds[i] = lineupDTO.videoIds[i]; //increments through the videoIds property and saves each one to the titleIds array
	}
	onMediaComplete(); //run the onMediaComplete function. This is necessary because the first time the onMediaComplete function is run, the titleIds value is null, so this function is run, but we still want it to finish running the onMediaComplete function, so we manually call it again
}

function onMediaComplete() {
	
	if(!titleIds) //if titleIds is null, meaning the getFeaturedLineup_Result function hasn't gone through yet
	{
		callFlash("getFeaturedLineup"); //get the featured lineup and then go to the getFeaturedLineup_Result function
	}
	else
	{
		if(counter < titleIds.length) //makes sure the counter doesn't just keep going forever
		{
			if (counter == 0) {
			    if (!vidState) {
					vidState = true;						
					callFlash("loadTitleById", titleIds[++counter]);				
					currentVideoSelect(counter, videoTitles[counter]);				
				}
				else {
					stopVideo();
				}
		}
		else if (counter == 3) {
			counter = 0;
			vidState = false;	
			stopVideo();
		}
		else {			
			callFlash("loadTitleById", titleIds[++counter]); //loads the title by id by using the counter variable. We increment it first because we just watched the first video, so now we want the next one
			currentVideoSelect(counter, videoTitles[counter]);			
			}
		}
	}
}

function getVideo(videoRes, position) {
	var titleid = $(videoRes).find("item").eq(position).children("bc\\:titleid").eq(0).text();
	return titleid;
}

function createVideo(videoRes) {
	$(videoRes).find("item:lt(4)").each(function(i){
		var title = $(videoRes).find("item:eq("+i+")").children("title").eq(0).text();
		var thumb = $(videoRes).find("item:eq("+i+")").children("media\\:thumbnail").eq(0).attr("url");
		videoTitles[i] = title;
		if (i == 0)	{
			selectedToutName = title;
			selectedTout = i;
			$("#videoName").html(title);		
		}
		$("#tout"+i).bind("click keydown keypress", function(){
		 counter = i;
			if (i == 0)	{
				$("#curVid").html(title);
			}																		   
			$("#videoName").empty();
 			currentVideoSelect(i, title);
		});
		$("#tout"+i).bind("mouseover focus", function(){
			$("#videoName").empty();													  
 			currentVideoHover(i, title);
		});		
		$("#tout"+i).bind("mouseout blur", function(){
		$("#videoName").empty();													  
		currentVideoHoverOut(i, title);
		});
		$("#thumb"+i).html('<img src="'+thumb+'"width="67" height="50" />'+'<img src="http://img.timeinc.net/time/rd/trunk/www/web/feds/i/icon_vid23.png" class="video" alt="Play" />');
	});
}

// By use of this code snippet, I agree to the Brightcove Publisher T and C
// found at http://corp.brightcove.com/legal/terms_publisher.cfm.
function createExperience1(config, flashVersion,divid) {
	var result = "";
	var videodiv = document.getElementById(divid);
   // default version to 7 for backwards compatability
   if (flashVersion == undefined) var flashVersion = 7;
   // Config parameters to pass into the SWF file.
   var servicesURL = "http://services.brightcove.com/services";
   var viewerSecureGatewayURL = "https://console.brightcove.com/services/amfgateway";
   var cdnURL = "http://admin.brightcove.com";
   var bgcolor = config["preloadBackColor"];
   var externalAds = (typeof(playAd) != "undefined");
   var sendReports = (typeof(reportEvent) != "undefined");
   var width = config["width"];
   var height = config["height"];
   if (width == null) {
    width = "100%";
   }
   if (height == null) {
    height = "100%";
   }
  //specify version required Flash version
  if (config["requireFlash8"] || flashVersion == 8){
    requiredMajorVersion = 8;
  } else{
	//mac requires flash 8
	requiredMajorVersion = 7;
	var isMac = navigator.appVersion.toLowerCase().indexOf("mac") > 0;
	if (isMac) requiredMajorVersion = 8;
  }
  var requiredMinorVersion = 0;
  var requiredRevision = 0;
  var hasRightVersion = DetectFlashVer(requiredMajorVersion,requiredMinorVersion,requiredRevision);
  if(hasRightVersion) {
	var pid = getParameter("bcpid");
	if(pid.length < 1  || (pid == config["playerId"]))  {
		var titleParam = getParameter("bctid");
		if (titleParam.length > 0) {
		  config["videoId"] = titleParam;
		  config["autoStart"] = true;
		  config["fromLink"] = true;
		}
		var lineupParam = getParameter("bclid");
		if (lineupParam.length > 0) {
		  config["lineupId"] = lineupParam;
		}
	}
    if (playerIndex == undefined){
		playerIndex = 0;
	}else{
		playerIndex++;
	}
    if (config["flashId"] == undefined) {
      flashId = "flashObj" + playerIndex;
    } else {
      flashId = escapeValue(config["flashId"]) + playerIndex;
    }
    var configItems = "";
    for (var i in config) {
       if (i == "flashId") continue;
       if (typeof(config[i]) == "function" || typeof(config[i]) == "object") continue;
       configItems += "&" + i + "=" + escapeValue(config[i]);
    }
    // Hook for Internet Explorer.
    if (navigator.appName && navigator.appName.indexOf("Microsoft") != -1 && navigator.userAgent.indexOf("Windows") != -1 && navigator.userAgent.indexOf("Windows 3.1") == -1) {
	result = result + '<script language=\"VBScript\"\>\n';
	result = result + 'On Error Resume Next\n';
	result = result + 'Sub ' + flashId + '_FSCommand(ByVal command, ByVal args)\n';
	result = result + '	Call onFSCommand(command, args)\n';
	result = result + 'End Sub\n';
	result = result + '</script\>\n';
    }
    var swfFile = "federated.swf";
    if (flashVersion == 8) {
      swfFile = "federated_f8.swf";
    }
    var file = cdnURL + "/viewer/" + swfFile + "?flashId="+flashId+
         "&servicesURL="+escapeValue(servicesURL)+
         "&viewerSecureGatewayURL="+escapeValue(viewerSecureGatewayURL)+
         "&cdnURL="+escapeValue(cdnURL)+
         configItems+
         "&externalAds="+escapeValue(externalAds)+
         "&sendReports="+escapeValue(sendReports)+
         "&buildNumber=" + 348 +
         "&ranNum=" + Math.floor(Math.random()*1000000);
    if (!DetectFlashVer(8,0,0)) {
      file += "&domain=" + getDomain();
    }
    wmode = config["wmode"];
	if (wmode == null) wmode = "window";
    version = "7,0,0,0"; // why write 7 always??
    quality = "high";
    result = result + "<object classid=\"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000\" codebase=\"http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=" + version + "\" id=\""+flashId+"\" width=\""+width+"\" height=\""+height+"\">";
    result = result + "  <param name=\"allowScriptAccess\" value=\"always\"/>";
    result = result + "  <param name=\"allowFullScreen\" value=\"true\"/>";
    result = result + "  <param name=\"movie\" value=\""+file+"\"/>";
    result = result + "  <param name=\"wmode\" value=\""+wmode+"\"/>";
    result = result + "  <param name=\"quality\" value=\""+quality+"\"/>";
    result = result + "  <param name=\"bgcolor\" value=\"" + bgcolor + "\"/>";
    result = result + "  <param name=\"base\" value=\""+cdnURL+"/viewer/\"/>";
    result = result + "  <param name=\"SeamlessTabbing\" value=\"false\"/>";
    result = result + "  <embed src=\""+file+"\" base=\""+cdnURL+"/viewer/\" quality=\""+quality+"\" bgcolor=\""+bgcolor+"\" allowScriptAccess=\"always\" name=\""+flashId+"\" width=\""+width+"\" height=\""+height+"\" wmode=\""+wmode+"\" seamlesstabbing=\"false\" type=\"application/x-shockwave-flash\" swLiveConnect=\"true\" pluginspage=\"http://www.macromedia.com/shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash\"></embed>";
    result = result + "</object>";
  } else {  // flash is too old or we can't detect the plugin
    result = result + "<table width='" + width + "' height='" + height + "' border='0' bgcolor='"+bgcolor+"'>";
    result = result + "<tr><td align='center' valign='middle'>";
    result = result + "<a href='http://www.adobe.com/go/getflash/' target='_blank'><img src='"+cdnURL+"/viewer/upgrade_flash_player.gif' alt='Get Flash Player' width='314' height='200' border='0'></a>";
    result = result + "</td></tr></table>";
   }
	videodiv.innerHTML = result;
    return flashId;
}