// -----------------------------------------------------------------------------
// --   JavaScript to/from Actionscript Management for the ?????????
// -----------------------------------------------------------------------------

// Globals
// ------- Private vars -------
var jsReady = false;
var swfReady = false;
var fandangoNextVideoIndex = 0;
var fandangoPlaylistCount = 0;
var playlistStartIndex = -1;
var empty_playlist_msg = "SORRY! Your playlist is empty. Please, try your selection again."
var companionAd_id = "VideoPlayerContent_sideAdUnit_Size300x250";

// ------- functions called by ActionScript -------

/** 
 * the flash object calls this method from a timer loop to determine when the containing 
 * html document has completed loading and its javascript is ready
 */
function isReady() {
	return jsReady;
}

/**
 * This function is called by the SWF object. It sets the swfReady global to true 
 */
function setFlashReady(){
	swfReady = true;
}

/**
 * This function gets the version of the flash player if it is supported
 */
function getVersion(){
	if (swfReady){
		return getSWF('fandangoplayerv2').version();
	}else {
		return "Flash application object not ready."
	}
}

/**
 * This function returns the url for the page containing the video player
 */
function pageURL(){
	//alert(location.href);
	return location.href;
}

/**
 * Resizes the Flash Player movie
 * 
 * @param flag	a boolean value 1=> expand, 0=>shrink
 */
function resizeVideoPlayer(flag){
	var div = document.getElementById('videoplayer')
	if ($("#videoplayer").hasClass("large")) {
		$("#videoplayer").toggleClass("large");
		$("#flashvideo").toggleClass("large");
		$("#videoplayer").children('#actions').hide();  			
		$("#videoplayerplaylist_container").show();
	} else {  			
		$("#videoplayer").toggleClass("large");
		$("#videoplayerplaylist_container").hide();
		$("#flashvideo").toggleClass("large");
		toggleVideoPlayerActions("#videoplayer");				
	}

}

/**
 * This function toggles the size of the video controls bar
 */
function toggleVideoControlsBarSize()
{
	if (swfReady){
		getSWF('fandangoplayerv2').toggleVideoControlsSize();
	}
}

/**
 * This function passes the index of the next video object to play in the video player to the Player.swf
 * 
 * @param {Number} i 	video index
 */
function playVideo(i)
{		

	if (fandangoPlaylistCount == 0)
	{
		// this condition is true usually for the 1st playVideo() call, which happens before the playlist array
		// is complete
		playlistStartIndex = i;
		return;
	}
	
	if (i > fandangoPlaylistCount - 1){
		i = 0;
	}
	
	if (swfReady){
		getSWF('fandangoplayerv2').nextVideo(com.fandango.playlist.videos[i]);
		fandangoNextVideoIndex = Number(i) + 1;
		doWSSReporting('VID_Playlist', 'VID_PL_Name'); // fix for TT6371
	}
	
	return false;
}

/**
 * Called by SWF when video is played (including the first video)
 * Parameters are passed to _hbPageView() for tracking.
 *
 */
function onVideoPlayed(p1, p2) {
	//alert("called onVideoPlayed()");
	_hbPageView(p1, p2);
	
    // Record in Offermatica
    doOffermaticaReporting('onVideoPlayed=1');
}

/**
 * Report interesting events to Offermatica.
 *  param:  the parameter to pass to the current Offermatica tracking mbox
 *
 */
function doOffermaticaReporting(param) {
    // "offermaticaTrack()" is a function inserted into the DOM via Offermatica mbox.  It 
    // may or may not exist depending if we are currently running a test or not.
    var haveOffermaticaTrackFunc = typeof offermaticaTrack == 'function';
    
    if (haveOffermaticaTrackFunc) {
        offermaticaTrack(param);
    }
}

function fandangoErrorHandler(msg, url, line)
{
	var errmsg = "fandangoErrorHandler:\r\n";
	errmsg += 'msg: ' + msg + '\r\n';
	errmsg += 'url: ' + url + '\r\n';
	errmsg += 'line: ' + line;
	
	alert(errmsg);
}

function getNextVideo(){
	if (fandangoPlaylistCount == 0)
	{
		//throw Error("The playlist is empty!");
		return;
	}

	if (playlistStartIndex != -1) {
		fandangoNextVideoIndex = playlistStartIndex;
		// reset the playlistStartIndex
		playlistStartIndex = -1;
	}
	else {
		// if the next video index is greater than the size of the playlist array
		// then reset the video index to 0
		if (fandangoNextVideoIndex >= fandangoPlaylistCount) {
			fandangoNextVideoIndex = 0;
			closeAllHeaders();
		}
		
		if (fandangoNextVideoIndex == -1) // starting with a new playlist
		{
			fandangoNextVideoIndex = 0;
		}
		else 
			if (fandangoNextVideoIndex == 0) {
			
				itemFocus($('div#scrollable > div.header:eq(0)'));
				
			}
			else {
				// the next video index was set by the last call to getNextVideo;
				// so the next call just adjust the playlist display to match
				loadNextVideo();
			}
	}
	var obj = com.fandango.playlist.videos[fandangoNextVideoIndex];
	
	// Set up the next video to play
	fandangoNextVideoIndex++;	// bump up to next video index
	return obj;
}

function toggleAdPlaying()
{
	toggleAdvertisement();
	loadSelectedHeader();
}

function toggleAdFinished()
{
	toggleAdvertisement();
	loadNextVideo();
}

function doWSSReporting(lid, lpos)
{
	// calling predefined function found in hbx.js
	_hbLink(lid, lpos);

	// Track in Offermatica as well
	doOffermaticaReporting('playerAction=' + lpos);
}

function getDartObj()
{
	return com.fandango.playlist.dart;
}

function getGoogleObj()
{
	return com.fandango.playlist.google;
}

function getLightningcastObj()
{
	return com.fandango.playlist.lightningcast;
}

function isFirefox()
{
	var userAgent = navigator.userAgent;
	if (userAgent.indexOf('Firefox') != -1)return true;
	return false;
}

function setTitleAndLinks(videotitle, email, buy)
{
	var title = document.getElementById('current_videoTitle');
	title.innerText = videotitle;
	
	var emailLink = document.getElementById('link_eMail');
	emailLink.setAttribute('href', email);
	
	var ticketsLink = document.getElementById('link_tickets');
	ticketsLink.setAttribute('href', buy);
	
}
// ------- event handling -------
/**
 * This function is the page's onload eventhandler. It will simply set the jsReady variable to
 * true once the page has loaded.
 */
function pageInit() {
	jsReady = true;
}

// ------- utility functions -------

/**
 * Gets a reference to the specified SWF file by checking which browser is
 * being used and using the appropriate JavaScript.
 * Unfortunately, newer approaches such as using getElementByID() don't
 * work well with Flash Player/ExternalInterface.
 * 
 * @param (Object) movieName	a string that matches the value of the id and name attributes on the object and embed tags.
 */
function getSWF(movieName) {
	if (navigator.appName.indexOf("Microsoft") != -1) {
		//debugWindow();
		return window[movieName];
	} else {
		return document[movieName];
	}
}

function debugWindow()
{
	var newline = "\r\n";
	var debugStr = "window properties:";
	for(var prop in window)
	{
		if (prop == "document")
		{
			debugStr += newline + prop + ":";
			for(var aux in window.document)
			{
				if (aux == 'objects' || aux == 'Player')
					debugStr += newline + "    " + aux + ",";
			}
		}
	}
	
	alert(debugStr);
}
// ------- Functions to handle the DART RoabBlock (Companion ad) --------
/**
 * This function is called from the DartAdHolder_AS3 component (compiled into the Fandango video player).
 * It is effectively stripping the size of the ad from a string called the adTag.
 * 
 * @param {Object} adTag
 */
function syncRoadBlock(adTag){
	a = adTag.split(';');
	if (a.length>0)
	{
            for (x=0; x <= a.length - 1; x++)
			{
				if (a[x].indexOf('sz=') == 0)
				{
					size = a[x].substring(3);
                    dims = size.split('x');
                    width = dims[0];
                    height = dims[1];
					loadRBs(companionAd_id,width,height,adTag); // <- hard-coded <div id ...> for companion ad
                }
            }
	}
}

function loadDefaultCompanionAd(url)
{
	loadRBs(companionAd_id, 300, 250, url);
}

function loadRBs(s,w,h,adTag){
    document.getElementById(s).innerHTML = '<iframe src="' + adTag + '" id="ifr_companion" width="'+w+'" height="'+h+'" marginwidth=0 marginheight=0 hspace=0 vspace=0 frameborder=0 scrolling=no>' + '</iframe>';
}

function loadImageCompanionAd(url, clickThru)
{
	document.getElementById(companionAd_id).innerHTML = '<a href="' + clickThru + '" target="_new"><img src="' + url + '" width="300" height="250" /></a>';
}

