//Current Video Id
var videoId     = -1;

//The currently playing item (filename)
var currentItem ='';

//How often the database should be polled to get the slides (in seconds)
var poll        = 10;

//Meta data variables
var meta        = '';
var metaCount   = 0;

//The player object
var player      =  null;

//The playlist object
var playlist    =  null;

//Id of the player object
var playerID    ='playerFLV';

//Location of the swf of the player
var swf_url     ='../../js/eventplayer.swf';

//Current slide image object
var currentImg = '';

//Current playhead time
var currentTime = -1;

//Whether slides are to be shown or not
var showSlides  = true;

//html object that houses the slides
var htmlId = 'slideContainer';

//----------------------------------------------------------
//Set the current video id
function setVideoId(id) {
    if (id && isNumeric(id)) { 
        videoId = id; 
    }
}

function setShowSlides(value) {
    showSlides = value;
    
    if (showSlides == true) {
        var sc = document.getElementById(htmlId);
        
        if (sc) { sc.style.display = 'none'; }
    }
    else {
        var sc = document.getElementById(htmlId);
        
        if (sc) { sc.style.display = 'block'; }
    }
}

function toggleSlides() {
    if (showSlides == true) {
        showSlides = false;
    }
    else {
        showSlides = true;
    }
}

//----------------------------------------------------------

//Create the video player
function createOnDemandPlayer(container, w, h, url, volume, stream, auto, live, hidecontrols ) {

	//Clear the container that the player will be written to
	if (document.getElementById(container)) { 

        document.getElementById(container).innerHTML=''; 
	    //Set the current item to url
	    currentItem = url;
        if (live) { swf_url = '../../flvplayer.swf' }
        
	    //Set the player's characteristics
	    window[playerID] = new Object();
	    var so = new SWFObject(swf_url,playerID,w,h,'9');
	    so.addParam('wmode','opaque');
	    so.addParam('allowscriptaccess','always');
  	    so.addParam('allowfullscreen','true');	
	    so.addVariable('javascriptid','playerFLV');
	    so.addVariable('enablejs','true');
  	    so.addVariable('backcolor','000000');	
  	    so.addVariable('frontcolor','FFFFFF');
	    so.addVariable('fullscreen','true');
	    so.addVariable('autostart', auto);
	    so.addVariable('volume', volume);

        //Hide the player's controls
	    if (hidecontrols) { so.addVariable('controlbar', 'none'); }

	    //If the file is a live stream, from a streaming server or a progressive download
	    if (live) {
		    so.addVariable('file', url);
		    so.addVariable('streamer','rtmpt://telecomtv.fc.llnwd.net/telecomtv/');	
		    so.addVariable('subscribe', 'true');
		    so.addVariable('type', 'video');
	    }
	    else if (stream) {
		    so.addVariable('file', 'eventsplatform/'+ url +'.flv');
		    so.addVariable('streamer','rtmpt://telecomtv.fcod.llnwd.net/a1411/o16');	
	    }
	    else {
		    so.addVariable('file','http://video.telecomtv.com/web2/ugc/flv/eventsplatform/'+ url +'.flv');	
	    }		

	    //Write the object to the container
	    so.write(container);
    	
	    //Apply IE patch to the player
	   // SWFFormFix(playerID);
	}
};

//------------------PLAYER SPECIFIC FUNCTIONS---------------------

    function playerReady(obj)
    {
      	player = gid(obj.id);
	  	//Initialise the image object
		currentImage = new Image();
		//Add the event listeners
      	if (showSlides == true && videoId != -1) { addListeners(); }
    };

	
	function addListeners()  {
		//Initialise the playlist
      	playlist = player.getPlaylist();

      	if ((playlist !== null) && (playlist.length > 0)) {
			//player.addControllerListener('PLAY', 'showHolding');
        	    //player.addControllerListener('STOP', 'showHolding');

                player.addModelListener("STATE", "stateMonitor");

                //Meta data event
			    //player.addModelListener('META', 'metaMonitor');
			
			    //Time event (playhead)
			    player.addModelListener('TIME', 'timeMonitor');

      	}
      	else {
			//Try adding again; player not ready.
        	setTimeout("addListeners();", 100);
      	}
    };
    
    function gid(name)
    {
      return document.getElementById(name);
    };   
    
//----------------------EVENT HANDLERS---------------------
    
    //For a time event (playhead)
    function timeMonitor(obj)  {
      for(var j in obj)
      {
      	if (j == 'position') {
      	    //document.getElementById('timedata').innerHTML = obj[j];
      	    
      	    //The position of the playhead
      	    var time = parseFloat(obj[j]);
      	    currentTime = time;
 
  	        //See if it's time to poll
  	        var mod = Math.floor(time) % poll;

            //If current time is divisible by poll
  	        if (mod == '0') {
		        //Ajax lookup to show slides (time in milliseconds)
		        lookupSlide(time * 1000);
  	        }
		}
      }
    };
    
    //For a meta data event
    function metaMonitor(obj)
    {
      for(var j in obj)
      {
	    if (obj[j] == 'cuepoint') {
			meta += '\n' + j + ': ' + obj[j];
			showSlide(obj['name']);
			metaCount += 1;
			//document.getElementById('metadata').innerHTML += 'META Data: ('+ metaCount +')' + meta +'<br/>';
			meta = '';			
		}
      }
    };
    
    function stateListener(obj) { //IDLE, BUFFERING, PLAYING, PAUSED, COMPLETED
	    currentState = obj.newstate; 
	    previousState = obj.oldstate; 

	    if ((currentState == "COMPLETED")&&(previousState == "PLAYING")) {
		    currentTime = -1;
	    }
    }

//--------------------------------------------------------------
	
	//Ajax call to the find the url of the next slide
	function lookupSlide(timeIndex) {
        if (isNumeric(timeIndex) && videoId != -1) {

            //Parameters for the call
            var p = 'TimeIndex='+ timeIndex +'&VideoId='+ videoId;

            var options = {
                    method : 'get',
                    parameters : p,
                    onComplete : function(request) {
                        //Load the image
                        showSlide(request.responseText);
                    },
                    onFailure:function(t) {
                        //Something went wrong
                    }
            };
            
            new Ajax.Request('/OnDemandLookup.ashx?action=dbLookup', options);   
        }
    }
    
	//Ajax call to the find the url of the next slide
	function setSlideStart(id, pbID) {
	    var setTime = currentTime * 1000;
        toggleStatus(id);
        if (player) { player.sendEvent("PLAY"); }

        if (currentTime > -1 && isNumeric(id)) {

            //Parameters for the call
            var p = 'TimeIndex='+ setTime +'&SlideId='+ id;

            var options = {
                    method : 'get',
                    parameters : p,
                    onComplete : function(request) {
                        //Load the image
                        //performPostBack(pbID);
                        __doPostBack(pbID,'');
                        toggleStatus(id);
                        player.sendEvent("PLAY","True");
                    },
                    onFailure:function(t) {
                        toggleStatus(id);
                    }
            };
            
            new Ajax.Request('../../OnDemandLookup.ashx?action=SetSlideStart', options);   
        }
    } 
    
         function performPostBack(hiddenFieldID) {
            var hiddenField = $get(hiddenFieldID);
            if (hiddenField) {
                hiddenField.value = (new Date()).getTime();
                __doPostBack(hiddenFieldID,'');
            }
         } 
    
    function toggleStatus(id) {
        var sb = document.getElementById('SetStatus'+ id);
	    
	    if (sb) { 
	        if (sb.style.display != 'none') {
	            sb.style.display = 'none';
	        }
	        else {
	            sb.style.display = 'block';
	        }
	   }
    }

    //Fill the html container with the slide image
    function showSlide(url) {
        var sc = document.getElementById(htmlId);	
        
		if (sc && url != '') { 
		    //If the slides have changed
		    if (currentImg != url) {
		        //currentImage = new Image();
		        sc.innerHTML = '<img src="'+ url +'" />';
		        currentImg = url
		    }
		}
	}
	
	//Show a holding slide
	function showHolding(obj) {
      for(var j in obj) {
      	//if (j == 'newstate') {
      	    //alert(j +' '+ obj[j]);
      	    //}
      }
	}

//----------------------------------------------------------

//Function to check if a given value is numeric or not
function isNumeric(sText) {
   var ValidChars = "0123456789.";
   var IsNumber=true;
   var Char;
 
   for (i = 0; i < sText.length && IsNumber == true; i++) 
      { 
      Char = sText.charAt(i); 
      if (ValidChars.indexOf(Char) == -1) 
         {
         IsNumber = false;
         }
      }
   return IsNumber;
   
}

//----------------------------------------------------------

//Video player Javascript update functions
function sendEvent(swf,typ,prm) { 
  thisMovie(swf).sendEvent(typ,prm); 
};

//function getUpdate(typ,pr1,pr2,swf) {

//		if(typ == "time") {
//			currentPosition = pr1;
//			duration = parseInt(pr1) + parseInt(pr2); 
//			//&& document.forms[0].inTOout.checked
//			
//			var pl=getLength('playerFLV')
//			pl--;			
//			
//			if (currentPosition == end && parseInt(currentItem) != parseInt(pl)) {
//				sendEvent('next'); 
//			}
//		}
//		else if(typ == "item") { 
//			//currentItem = pr1;  
//			
//  		}		
//		else if(typ == "state") { 
//			state = pr1;      
//			
//			//If the video is playing send data to Google Analytics
//			if (state == "2" && gaSent==false) { 
//				//alert(state +'Calling Google: pageTracker._trackPageview("/videos/'+ currentItem +'.flv);"');
//				//pageTracker._trackPageview('/videos/'+ currentItem +'.flv');
//				
//				//Set the flag to tell the page that tracking has been done
//				gaSent=true;
//			}
//		}
//		else if(typ == "load") { 
//			buffer = pr1;      
//		}    
//		else if(typ == "volume") { currentVolume = pr1; }  

//};

function thisMovie(movieName)
{
if (navigator.appName.indexOf('Microsoft') != -1)
{
return window[movieName];
}
else
{
return document[movieName];
}
};

