/** 
 * @class Represents a video player with complete UI/controls. Behaviour is adopted to the TV 2 Sumo requirements.
 * @constructor
 * @param {int} index A number matching the HTML nodes' ID endings. For example, if the Media Player object has 'video123' as ID, index should be 123
 * @param {boolean} miniOnly Optional parameter. When set to true, the player behaviour will be modified for use as thumbnail/secondary player only
 * @param {boolean} delayedAttach Will not attach to HTML DOM element before "use", i.e. video start
 * @param {object} callbacks An optional object whose properties are pointers to callback functions. Zero or more of these callbacks can be attached: onSwitchClick, onSelectorClick, onMouseOver, onMouseOut, onVideoEnd, onHide
 * @author Tor Erik Alrĉk, Thomas Aalén
 * @version 3.0 
 */












function flashPlayer (index,miniOnly,delayedAttach,callbacks) {
	// callbacks = {
	// 		onSwitchClick, - when user presses the switch button (if any)
	// 		onSelectorClick, - when user presses the select button (if any)
	// 		onMouseOver, - when user mouses over the video area
	// 		onMouseOut,
	// 		onVideoEnd, - when video stops by itself (program finished or live stream ended)
	// 		onHide, - when the hide method is called
	// 		onItemChange, - when video position is moving 
	// 		onError, - when user clicks for error details
	// 		onQualityClick, - when user clicks for quality details settings
	// 		onReplay, - when users presses play again after having stopped the stream (live only)
	// 		playerContainer, - html target element for reloading the player when onReplay event fires
	// 		onMuteChange, - when user presses the mute button
	// 		onPlayerClick - when user clicks in the video area
	//    getStartAd
	//    getEndAd
	//    getAds
	//		useLiveMenu
	//		allowFallback
	
	
	//		*** flyttet til start() onShowExternalAd - when an ad outside the player is going to be shown
	//  }
	// CONSTRUCTOR
  if (index == null) index = 0;
 	
 	var ie = navigator.userAgent.indexOf("MSIE")>=0 && navigator.userAgent.indexOf("Opera")<0 && navigator.userAgent.indexOf("Mac")<0;
  // Gecko also includes Safari
  var geckoWin = navigator.userAgent.indexOf("Gecko")>=0 && navigator.userAgent.indexOf("Opera")<0 && navigator.userAgent.indexOf("Win")>0;
  
  this.ie = ie;	
  var live;
  var items;
  
  var currentItem;
  var currentProgId;
  
  var mutedFromButton;
  var elementId = 'video' + index;
  var panelId = 'videoPanel' + index;	
  var loaded = false;
  var sp;
  var installCheckInterval;
  	
  if (!callbacks) callbacks = new Object();
	
  var me = this;

	var log = new Object();
	try {
		log.debug = logDebug;
		log.error = logError;
	} catch(e) {
		log.error = function(source,e) {
			if (location.href.indexOf('debug=true')>0) alert(source + ': ' + e.message);	
		}	
		log.debug = function(source,message) {
			if (location.href.indexOf('debug=true')>0 && $('debugList')) {
				$('debugList').innerHTML = $('debugList').innerHTML + '<li>' + source + ': ' + message + '</li>';	
			}
		}
	}

	// Method required in constructor
	this.attach = function() {
	  try {

	  } catch (e) {
	  	log.error('FlashPalyer.attach',e);
	  }
	}

	// Constructor continues  
  if (!delayedAttach) {
  	me.attach();
  }


	function SlCallbacks() {
    this.onCloseClick = function () {setTimeout(me.hide,10);}; // IE crashes when calling a function in the SL object from JS, when this function is called from SL itself
    this.onSwitchClick = function () { alert('Ikke implementert')};
    this.onVideoClick = function () { if (callbacks.onPlayerClick) {callbacks.onPlayerClick(); return true}};
    this.onErrorClick = function () {
			if (callbacks.onError) {
				callbacks.onError("Flash error message","x",currentProgId);
				return true;
			}
    };
    this.onSettingsClick = function () { if (callbacks.onQualityClick) {callbacks.onQualityClick(); return true}};
    this.onMuteChanged = function (muted) { 
    	mutedFromButton = muted;
			if (callbacks.onMuteChange) {
				callbacks.onMuteChange(index,muted);
				return true;
			}
    };
    this.onItemChange = function () {};
    this.onVideoEnd = function () {
    	if (callbacks.onVideoEnd) {
				var itemId;
				if (currentItem != null) itemId = currentItem.id;
				callbacks.onVideoEnd(index,currentProgId,itemId);
			}
    	if (!miniOnly) setTimeout(me.hide,10);
    };
    this.onLoaded = function () { 
      loaded = true;
      sp = $('video' + index).Content.playerPage;
    };
    this.getItemList = function() {
			return items;
    }
	}
	
	var slCallbacks = new SlCallbacks();
	
	
	
	
	

	// PUBLIC METHODS



/**
 * Starts video with ads before/after, if exists
 * @param {object} props details of the media being started, and for ads. The startVideo parameters are equivalent to the members of props, but there are three additions
 */

	this.start = function(props) {
		// metaUrl,progId,hostProgId,live,timeBegin,startPos,adCategory,startAdPos,endAdPos,bannerAdPos,bannerAdElement,programTitle,items,bufferFlash,bufferContent,isDrm,licensingServer,muted
		items = props.items;				
		me.startVideo(props.metaUrl,props.progId,props.hostProgId,props.live,props.timeBegin,props.timeEnd,props.startPos,props.programTitle,props.paused,props.widescreen,props.muted,props.isDrm,props.licensingServer,props.matchId);
	}

/**
 * Starts video playback immediately, without ads
 * @param {string} metaUrl The url pointing to the media file, to be used by Windows Media Player. If omitted, parameters from start method are used instead.
 * @param {int} progId the video program's id, used for identifying current stream, or to get correct stream in live programs
 * @param {int} hostProgId optional, as props.progId, but used for sub programs having a real host program
 * @param {boolean} live indicates that stream is live if included, and set to true
 * @param {int} timeBegin not used
 * @param {int} startPos when starting playback, jumps playing position to the number of seconds from the start. startPos is optional.
 * @param {string} programTitle the title of the program, to be showed in the status area.
 */


	 this.startVideo = function(metaUrl,progId,hostProgId,pLive,timeBegin,timeEnd,startPos,pProgramTitle,paused,pWidescreen,muted,pIsDrm,pLicensingServer,pMatchId) {

		 metaUrl = metaUrl+'&sl=true';
		 currentProgId = progId;
		
		 var so = new SWFObject("/multimedia/fp/tv4video.swf", "video1", "681","424","8","#ffffff");
		 so.addParam("allowfullScreen","true");
		 so.addParam("allowFullScreen","true");
		 so.addParam("allowScriptAccess","always");
		 so.addVariable("metaUrl",escape(metaUrl));
		 so.addVariable("player1",escape(metaUrl));
		 so.addParam("base","/multimedia/fp/");
		 so.addVariable("startPos",startPos);
		 so.write("flashcontent");
	

	}

  this.show = function(videoOnly) {
	  $('videoPanel' + index).style.display = 'block';
  }

/**
 * Hides the video player
 * @param {boolean} videoOnly if the optional parameter is set to true, only the video area will be hidden, leaving the controls and panels visible.
 * @see #show
 */
  this.hide = function(videoOnly) {
  	try {

			if (sp) sp.stop();
		
			$('videoPanel' + index).style.display = 'none';

			if (callbacks && callbacks.onHide) {				
				callbacks.onHide();
			}
		} catch(e) {
			log.error('FlashPlayer.hide',e);
		}
  }

/**
 * Gets the playing state of the video player.
 * @return state, set to true when video is playing, otherwise false 
 * @type boolean
 */
  this.isPlaying = function() {
  	try {
  		if (sp)
  			return sp.isPlaying();
  		else
  			return false;
  	} catch(e) {
  		return false;
  	}
  }

/**
 * Gets the playing state of the video player.
 * @return state, set to true when video is playing, otherwise false 
 * @type boolean
 */
  this.isLive = function() {
  	return live;
  }


/**
 * Gets the mute state of the video player.
 * @return mute setting, set to true when video is muted, otherwise false 
 * @type boolean
 */
  this.isMuted = function(fromButton) {
  	try {
  		if (fromButton) {
 				return mutedFromButton; 				
  		} else
	  		return sp.isMuted();
  	} catch(e) {
  		return false;
  	}
  }

/**
 * Sets the sound volume of the video player.
 * @param {int} level a number between 0 and 100
 */
  this.setVolume = function(level) {
		if (sp)
			sp.setVolume(level/100);
  }

/**
 * Gets the sound volume of the video player.
 * @return a number between 0 and 100
 * @type int
 */
  this.getVolume = function() {
		if (sp)
			return Math.round(sp.getVolume() * 100);
  }

/**
 * Mutes the video player.
 */
  this.mute = function() {
		if (sp) return sp.mute();	
	}

/**
 * Unmutes the video player.
 */
  this.unmute = function() {
		if (sp) return sp.unmute();
  }

/**
 * Go to fullscreen mode
 */
  this.gotoFullscreen = function() {
		if (sp) sp.gotoFullscreen();
  }

/**
 * Moves playback to the specified position
 * @param {int} pos number of seconds from the beginning of the program
 *  */
  this.gotoPos = function(pos) {
		if (sp && !live) sp.gotoPos(pos);
  }

/**
 * Gets the playback position (time)
 * @return pos number of seconds from the beginning of the program
 * @type int
 **/
  this.getPos = function() {
		if (sp) return sp.getPos();
  }

/**
 * Gets the ID of the currently opened program
 * @return progId
 * @type int
 */
  this.getProgId = function() {
  	return currentProgId;
  }


/**
 * Gets the ID of the currently playing item
 * @return itemId
 * @type int
 */
  this.getCurrentItemId = function() {
  	if (currentItem && currentItem.id !=0) {
  		return currentItem.id;  		
  	}
  }



/**
 * To be called when ad is finished
 */
	this.adEnded = function() { 
		
  }

 	this.getItemByIndex = function(index){
 	return items.getItemByIndex(index);
 
 }

}



   function onItemChange( currentProgId, currentItemId ){ 
    var indexItem = 0;
     if(currentItemId > -1 ){
   		indexItem = mainPlayer.getItemByIndex(currentItemId).id;
   	 }	
   	
   	 userNav.getProgramMetaContent(mainPlayer.getProgId(),indexItem);  
     
   } 

    function onHide(){
        mainPlayer.hide();
    }
    function onVideoEnd(){
        mainPlayer.hide();
    }
    
