var channelData;
var currentSelectedChannel = 0;
var animationInterval = 5; //seconds
var teaserImagesLoadedCache;

//Various timers
var autoplayTimer;
var restartTimer;

//Calculate Users Connection
var loadStartTime;
var connectionSpeed;
var useLoader = false;
var avgImageSize = 30000; //bytes
var TAB_MAX = 5;
var selectedTabs=new Array(0);

//paths
var PATH_TO_CHANNEL_ICON = "http://static.joost.com/rsc/images/content/components/featurebox/channelicons/";
var PATH_TO_PROGRAMME_IMAGE = "http://static.joost.com/rsc/images/content/components/featurebox/teasers/";

/**
* Get the data for the current region (which region to use is stored in the page)
*/
$(document).ready(function(){
    //Load Data
    loadStartTime = new Date().getTime();
    $.get("../js/featureboxchannels_"+region+".js", { baseRevision: escape(baseRevision) }, loadChannels);
});

/*
* Calculates the connection speed and if estimated time taken to load an image is more than 3/4 second 
* we will use the loader image
*/

function setUseLoader(bytes, timeTakenInMilis){
    connectionSpeed =  ((bytes * 8.0) / 1000.0) / ( timeTakenInMilis / 1000.0);
    estimatedTimeToDownloadImage = ((avgImageSize * 8) / 10000.0) / connectionSpeed;
    if (estimatedTimeToDownloadImage > 0.5)
        useLoader=true;
}

/*
* Callback function after data has been loaded at ready
* Initialises the pages bindings
*/
function loadChannels(data){
    
    //Measure how long it took, if it's slow we'll use the loader.gif for image loads
    loadEndTime = new Date().getTime();
    setUseLoader(  data.toString().length,  loadEndTime-loadStartTime );
    
    //Store the data as json object (we didn't getJSON because we wanted to measure its toString.length to use as a baseline to calculate connection speed)
    channelData = eval("(" + data.toString() + ")");
    
    //Keep a track of the images we show to determine if the loader.gif is needed
    teaserImagesLoadedCache= new Array(channelData.channels.length+1);
    teaserImagesLoadedCache[0] = 0;
    
    //Bind up functionality
    $("#channels li").click(function(){
        tabAction(this);
    });
    
    //Set the image to hide the loader when an image is finished loading
    $("#teaserImage").load(function(){
        $("#loader").stop().hide();
        //Show the image
        $("#teaserImage").animate({opacity:0.9999},"normal");
        teaserImagesLoadedCache[currentSelectedChannel] = currentSelectedChannel;
    });
    
	//Choose the tabs to display (we may be selecting from a bigger pool than that which is visible)
	showTabs(channelData);
	
    //Kick off the animation
    autoplay(animationInterval);
    
    //Fix the images png bug in IE6
    if ($.browser.msie)
    	correctPNG();
}

function showTabs(channelData){

	onePositionAwayFromFirstTab = 1;
	availableChannelsPoolIndexes = new Array();
	//Insert indexes of all the tabs in an array for the
	//purposes of keeping track of the ones selected
	for (i=0; i < channelData.channels.length; i++){
		availableChannelsPoolIndexes[i] =  i;
	}
	//Loop selecting indexes until we've grabbed enough to fill the tabs
	selectedTabs[0] = 0;
	while (selectedTabs.length < ($("#channels ul li").length )){
		//Choose a random channel from the pool
		selectedTabIndex = rndInt(availableChannelsPoolIndexes.length - 1) + onePositionAwayFromFirstTab; // shift away from 0 to make the minimum 1
		//Add it to the list of our final selection whilst removing it from those available for selection
		selectedTabs.push(availableChannelsPoolIndexes.splice(selectedTabIndex,1)[0]);
	}
	//sort to convey some semblance of consistency in positioning of channels in the list
	selectedTabs.sort();
	
	//Display the tabs we selected iterating through the list of values generated
	for (i=1; i<selectedTabs.length; i++){
		target = $("#channels ul:nth(0) li:nth("+(i)+")"); //the tab where we will put the content (avoiding the first which doesn't change)
		data = channelData.channels[selectedTabs[i]]; //the data relating to this tab
		setChannelTabContent(target, data); //inject the data
	}
}

function setChannelTabContent(target, data){
	$("img",target).attr('src', PATH_TO_CHANNEL_ICON + data.channelIcon).attr('alt',data.channelTitle);
	$("span",target).text(data.channelTitle);
}

function tabAction(tab){
    timedPauseAutoplay();
    channelIndex = $("#channels li").index( $(tab)[0] );
    if (channelIndex != currentSelectedChannel){
        setSelectedChannel(channelIndex,"normal");
        setSelectedTab();
    } else {
        window.location = channelData.channels[selectedTabs[channelIndex]].link
    }
}

/**
* When a tab is clicked load the new image and show the details of the channel
*/
function setSelectedChannel(channelIndex, speed){
    //set the image, title and description data
    selectedChannelData = channelData.channels[selectedTabs[channelIndex]];
    //opacity bug fix for ff mac (not using fadein as might be expected but animate instead)
    $("#teaserImage").animate({opacity:0},"fast", function(){
        //Display the loader if it's needed
        displayImageLoader(channelIndex);
        //Swap images
        $("a#teaserJoostLink").attr("href",selectedChannelData.link);
        $("a#headerJoostLink").attr("href",selectedChannelData.link);
        $("a#headerJoostLink").attr("href",selectedChannelData.link);
        $("#teaserImage").attr("src",programmeImagePath(selectedChannelData.channelImage)).attr("alt",selectedChannelData.channelTitle);
    });
    //update which the current selected channel is
    currentSelectedChannel = channelIndex;
}

/*
* Return a localized  path to a programmme image
*/
function programmeImagePath(imagename){
	return PATH_TO_PROGRAMME_IMAGE + "/" + imagename;
}

/**
* Display image loader if the image has not previously been loaded and return the result
*/
function displayImageLoader(channelindex){
    if (useLoader && teaserImagesLoadedCache[channelindex] == undefined) {
        $("#loader").show();
        usingLoader = true;
    }
}

/*
* Start Autoplaying the tabs
*/

function autoplay(){
    autoplayTimer = window.setInterval( function(){
        channelIndex = currentSelectedChannel+1;
        //reset when we've reached the end
        if (channelIndex == selectedTabs.length) channelIndex =0;
        setSelectedChannel(channelIndex,800);
        //update the selected tab
        setSelectedTab();
    }, animationInterval * 1000);
}

function stopAutoplay(){
    window.clearInterval(autoplayTimer);
}

function timedPauseAutoplay(){
    //remove any previous scheduled restart timers
    if (restartTimer!=null)
        clearInterval(restartTimer);
    //remove any autoplay timers currently in use
    if (autoplayTimer!=null)
        stopAutoplay();
    //Create a new restart timer to start autoplay again in x seconds
    restartTimer = window.setInterval(  function(){ autoplay();clearInterval(restartTimer)},11000);
}

function setSelectedTab(){
    //remove the previous selected tab
    $("#channels li.selected").removeClass("selected");
    //add the selected class to the current tab
    $("#channels li:nth("+currentSelectedChannel+")").addClass("selected");
}