// ==================================================================== 
// ! MediaSilo Reel Display Component
//	 Version 1.2, February 2nd, 2010   
// ==================================================================== 

var lineupurl = '';
var currentclip = 0;
var currentLineup;
var channels;
var data = [];
var channelurl;
var channel;
var player;
myCarousel = null;


// ========================================= 
// ! Displays the lineups in the popup box   
// ========================================= 

function processChannel(feed){
	channels = feed;
	$.each(feed.lineups, function(i) {
		$('#lineupcontent').append("<li id='channellink' rel='"+i+"'>"+feed.lineups[i].name+"</li>");
	});
	//Load the first channel by default
	$('#channellink:first').click();
	};

//Player Logic
function playerReady(obj) {
	player = gid(obj.id);
	player.addModelListener('STATE', 'stateMonitor');
};

function stateMonitor(obj)
  {
    if(obj.newstate == 'COMPLETED')
    {
      playNextVideo();
    }
  };

function playNextVideo(){
	currentclip = parseInt(currentclip)+1;
	player.sendEvent('LOAD',currentLineup[currentclip].MEDIA_URL);
	$("#mycarousel li").each(function() {
		$(this).removeClass("clipselected");
	});
	$('#mycarousel li:eq('+currentclip+')').addClass("clipselected");
	
}	


function gid(name) {
	return document.getElementById(name);
};

$(document).ready(function(){

// ============================== 
// ! Get the channel id to load   
// ============================== 

if ($.getUrlVar('channel')) {
	var channel = $.getUrlVar('channel');
	var channelurl = "http://players.mediasilo.com/" + $.getUrlVar('channel');
} else {
	var channelurl = "http://players.mediasilo.com/channel-96FF89CE-B1C7-C974-AF8D16EBEAB31DEA.json";
}

// =========================== 
// ! Initialize the carousel   
// =========================== 
	  function prepareData(data){
		for (var i=0; i < data.length; i++){
        myCarousel.add(i+1, mycarousel_getItemHTML(data[i],i));
    	myCarousel.size(data.length);
    	}

    } 
	
	function onInitCarousel(carousel, state) {
	    if (state == 'init') {
	        myCarousel = carousel;
	    }
	}; 
	
	function mycarousel_getItemHTML(data,index)
	{
		return '<img src="' + data.PREVIEW_URL + '" imgid="' + index + '" width="120" height="90" alt="" />';
	};

	$('#mycarousel').jcarousel({
        size: data.length,
        initCallback: onInitCarousel,
        itemLoadCallback: {onBeforeAnimation:prepareData}
    });
	
	function resetData() {
    	myCarousel.reset();
    } 

	// END CAROUSEL CODE
	
	
	// ============================================== 
	// ! Play selected clip and highlight thumbnail   
	// ============================================== 

	$("#mycarousel li img").live("click", function(){
		currentclip = $(this).attr('imgid');
		document.getElementById('mediasiloplayer').sendEvent('LOAD',currentLineup[currentclip].MEDIA_URL);
		document.getElementById('mediasiloplayer').sendEvent('PLAY');
		$("#mycarousel li").each(function() {
			$(this).removeClass("clipselected");
		});
		$(this).parent().addClass("clipselected");
	})
	
	
	$("#mycarousel li img").live("mouseover", function(){
		$("#lineups").html("<p>" + currentLineup[$(this).attr('imgid')].TITLE + " : " + currentLineup[$(this).attr('imgid')].DESCRIPTION + " (" + formatSecToTimecode(currentLineup[$(this).attr('imgid')].MEDIA_DURATION) + ")</p>");
	});
	
	// ============================================= 
	// ! Load the Channel JSON file from MediaSilo   
	// ============================================= 
	
	function loadChannel(url) {
		var headID = document.getElementsByTagName("head")[0];         
		var newScript = document.createElement('script');
		newScript.type = 'text/javascript';
		newScript.src = url;
		headID.appendChild(newScript);
	}
	
	// ================================ 
	// ! Select Lineup from the panel   
	// ================================ 
	
	$('#channellink').live("click", function() {
		currentlocation = $(this).attr('rel');
		$('#lineupcontent').children("li").removeClass("selected");
		$(this).addClass("selected"); // highlight selection
		getLineup(channels.lineups[currentlocation].url, currentlocation);
	});
 
		
	
	
	
	// ============================================================================ 
	// ! Parse the incoming Lineup through MediaSilo's external RSS to JSON parer   
	// ============================================================================ 

	function getLineup(url,displaylocation){
	$.getJSON('http://silo1.mediasilo.com/rssparser.cfc?method=parse&url='+url+'&callback=?', function(data, textStatus){
		currentLineup = data;
		showAssets(data);
		resetData();
		prepareData(data);
		
		})
	}
	
	// ===================================================== 
	// ! Populate the carousel with new assets from lineup   
	// ===================================================== 
	function showAssets(assets){
		$('#mycarousel').jcarousel();
  	}
  
 	// =========================================================================================== 
	// ! Formats incocoming timecode from miliseconds into a human readable format   
	// =========================================================================================== 
	
	function formatSecToTimecode(sec) {
	    var hours = Math.floor(sec / 3600);
	    var minutes = Math.floor((sec-(hours*3600)) / 60);
	    var seconds = Math.round(sec - ((hours*3600)+(minutes*60)));
	    var returnString = "";
	    
	    if(hours.toString().length == 1) {
	        hours = "0"+hours;
	    }
	    if(minutes.toString().length == 1) {
	        minutes = "0"+minutes;
	    }
	    if(seconds.toString().length == 1) {
	        seconds = "0"+seconds;
	    }
		
		if(sec < 60) {
			returnString = "00:"+seconds;
		} else if(sec < 3600) {
			returnString = minutes+":"+seconds;
		} else {
			returnString = hours+":"+minutes+":"+seconds;
		}
	
	    return returnString;
	}

// =========================== 
// ! Initialize channel load   
// =========================== 

  	loadChannel(channelurl);



  });