sl.VideoPlayer = function() 
{
};

sl.VideoPlayer.prototype =
{
	handleError: function(plugIn, userContext, rootElement){
		//alert('xaml error');
	},
	
	handleLoad: function(plugIn, userContext, rootElement) 
	{
		
		plugIn = plugIn;
		root = rootElement;
		host = rootElement.getHost();

		slWidth = videoWidth;
		slHeight = videoHeight;
		
		this.plugIn = plugIn;
		
		//create an overlay class instance
		overlay = new sl.Overlay(plugIn, rootElement);
		
		controls = new sl.Controls(plugIn, rootElement);
		controls.scaleControls(videoWidth, videoHeight, false);
				
		slPlayer = root.findName('slPlayer');
		slPlayer.AddEventListener("CurrentStateChanged", Silverlight.createDelegate(this, this.media_state_changed));
		slPlayer.AddEventListener("MediaOpened", Silverlight.createDelegate(this, this.media_opened));
		slPlayer.AddEventListener("MediaEnded", Silverlight.createDelegate(this, this.media_ended));
		slPlayer.AddEventListener("MediaFailed", Silverlight.createDelegate(this, this.media_error));
		slPlayer.AddEventListener("BufferingProgressChanged", Silverlight.createDelegate(this, this.bufferingChange));
		slPlayer.AddEventListener("DownloadProgressChanged", Silverlight.createDelegate(this, this.downloadChange));
		
		slPlayerOptin = root.findName('slPlayerOptin');
		
		plugIn.content.onFullScreenChange = this.onFullScreenChanged;

		fullBtn = rootElement.findName('fullscreenBtnVideo');
		buffer = rootElement.findName('BufferHolder');
		videoArea = rootElement.findName('videoArea');
		hitAreaVideo = rootElement.findName('hitAreaVideo');
		hitAreaVideo.cursor = 'Arrow';
		
		this.fullToken = fullBtn.addEventListener("MouseLeftButtonUp", Silverlight.createDelegate(this, this.maximizeSl));
		hitAreaVideo.addEventListener("MouseEnter", Silverlight.createDelegate(this, this.videoHitEnter));
		hitAreaVideo.addEventListener("MouseLeave", Silverlight.createDelegate(this, this.videoHitLeave));
		hitAreaVideo.addEventListener("MouseLeftButtonUp", Silverlight.createDelegate(this, this.videoHitUp));
		
		
		this.controlsTimer = rootElement.findName('controlsTimer');
		this.controlsTimer.addEventListener("completed", Silverlight.createDelegate(this, this.checkHideTime));
		this.controlShown = false;
		this.controlHideTime = 3000;
		
		//init fullscreen interact if allowFullScreen
		debugThis('allowFullScreen'+allowFullScreen);
		if(allowFullScreen == '1' && controlsType == 'external'){
			debugThis('show fullsacreen '+hitAreaVideo);
			fullBtn.addEventListener("MouseEnter", Silverlight.createDelegate(this, this.videoHitEnter));
			fullBtn.addEventListener("MouseLeave", Silverlight.createDelegate(this, this.videoHitLeave));
			fullBtn.cursor = 'Hand';
			fullBtn.Visibility = 'Visible';
			this.showFullscreen = true;
		}else{
			fullBtn.Visibility = 'Collapsed';
			this.showFullscreen = false;
		}
		
		//hide controls if external is used
		if(controlsType == 'external'){
			controls.showControls(false);
		}

	
		//hide the buffer animation
		buffer.Visibility = 'Collapsed';
		
		//adjust all interface items to video player size
		this.adjustItems();
		videoArea['Canvas.ZIndex'] = 0;
		videoArea['Canvas.Top'] = 0;
		
		this.setHitMc(false, -1);
	}, 
	
	maximizeSl: function(){
		debugThis('maximizeSl ---- ');
		
		//make pos tween
        this.plugIn.content.fullScreen = !this.plugIn.content.fullScreen;
		
		if(this.plugIn.content.fullScreen){
			var objFlash = getObject("objFlashPlayer");
			objFlash.logToOmnitureTrack({'trackEvent':'BP-Bigpond TV-Fullscreen'});
		}
	},  
	
	minimizeSl: function(){
		//make pos tween
        this.plugIn.content.fullScreen = false;
	},   
	
	getFullscreenSl: function(){
		debugThis('getFullscreenSl ---- '+this.plugIn.content.fullScreen);
		//make pos tween
       return this.plugIn.content.fullScreen;
	}, 
	
	onFullScreenChanged: function(){
		debugThis('onFullScreenChanged ---- ');
		
		debugThis('CurrentState ---- '+slPlayer.CurrentState);
		var isPaused = false;
		if(slPlayer.CurrentState == "Paused"){
			slPlayer.play();
			isPaused = true;
		}
		
		if(host.content.FullScreen){
			if(optinActive){
				overlay.optinHolder['Canvas.Top'] = 0;
			}else{
				overlay.optinHolder['Canvas.Top'] = host.content.ActualHeight;
			}
			
			slPlayer.Width = slPlayerOptin.Width = host.content.ActualWidth;
			slPlayer.Height = slPlayerOptin.Height = host.content.ActualHeight;
			hitAreaVideo.Visibility = 'Collapsed';
			
			overlay.setFullscreen(true);
			overlay.adjustOverlay();
			overlay.adjustOptin();
			overlay.adjustiVideo((slPlayer.Width / root.width), slPlayer.Height);
			
			videoPlayer.adjustBuffer();
			
			controls.scaleControls(host.content.ActualWidth, host.content.ActualHeight, true);
			videoPlayer.updateToken = root.addEventListener("MouseMove", videoPlayer.updateHideTime);
			videoPlayer.showControls(true);
			
			var objFlash = getObject("objFlashPlayer");
			objFlash.setIsFullscreen('fullScreen');
		}else{
			if(optinActive){
				overlay.optinHolder['Canvas.Top'] = 0;
			}else{
				overlay.optinHolder['Canvas.Top'] = videoHeight;
			}
			
			slPlayer.Width = slPlayerOptin.Width = videoWidth;
			slPlayer.Height = slPlayerOptin.Height = videoHeight;
			hitAreaVideo.Visibility = 'Visible';
			
			overlay.setFullscreen(false);
			overlay.adjustOverlay();
			overlay.adjustOptin();
			overlay.adjustiVideo((videoWidth / root.width), videoHeight);
			videoPlayer.adjustBuffer();
			
			this.hideTime = 0;
			this.controlShown = false;
			
			controls.scaleControls(videoWidth, videoHeight, false);
			root.removeEventListener("MouseMove", videoPlayer.updateToken);
			controls.showControls(true);
			
			var objFlash = getObject("objFlashPlayer");
			objFlash.setIsFullscreen('normal');
		}
		
		if(isPaused)
			slPlayer.pause();
	},  
	
	showControls: function(status){
		debugThis('showControls '+status);
		if(status){
			controls.showControls(true);
			this.controlsTimer.begin();
			debugThis('controlsTimer.begin();'); 
		
			var d = new Date();
			this.hideTime = Math.round(d.getTime()) + this.controlHideTime;
		}else{
			controls.showControls(false);
			this.hideTime = 0;
		}
		this.controlShown = status;
		
		debugThis('showControls  done '+status);
	},
	
	checkHideTime: function(){
		debugThis('checkHideTime ');
		if(!host.content.FullScreen)
			return;
		
		var d = new Date();
		debugThis('checkHideTime '+ this.hideTime+' / '+Math.round(d.getTime()));
		
		if(Math.round(d.getTime()) > this.hideTime){
			videoPlayer.showControls(false);
		}else{
			videoPlayer.controlsTimer.begin();
		}
	},
	
	updateHideTime: function(){
		debugThis('updateHideTime'); 
		var d = new Date();
		this.hideTime = Math.round(d.getTime()) + this.controlHideTime;
		if(!this.controlShown){
			videoPlayer.showControls(true);
		}
		debugThis('updateHideTime done'); 
	}, 
	
	adjustItems: function(){
		
		this.adjustBuffer();
		
		this.adjustVideoHitArea();
		
		this.posFullscreenBtn();
		
	},
	
	adjustBuffer: function(){
		var dimension = overlay.getDimension();
		slWidth = dimension['width'];
		slHeight = dimension['height'];
		
		buffer.findName('BufferBg').Width = slWidth;
		buffer.findName('BufferBg').Height = slHeight+1;
		buffer.findName('Buffer')['Canvas.Left'] = (slWidth-buffer.findName('Buffer').width)/2;
		buffer.findName('Buffer')['Canvas.Top'] = (slHeight-buffer.findName('Buffer').height)/2 - 10;
	},
	
	adjustVideoHitArea: function(){
		var dimension = overlay.getDimension();
		slWidth = dimension['width'];
		slHeight = dimension['height'];
		
		hitAreaVideo.findName('hitAreaVideoRect').Width = slWidth;
		hitAreaVideo.findName('hitAreaVideoRect').Height = slHeight;
	},
	
	posFullscreenBtn: function(){
		fullBtn['Canvas.Left'] = videoWidth - fullBtn.width - 5;
		fullBtn['Canvas.Top'] = 5;
	},
	
	videoHitEnter: function(){
		objFlash = getObject("objFlashPlayer");
		objFlash.loadedSwfAction('rollOver', curAdId);
	},
	
	videoHitUp: function(){
		debugThis('mouse hit video up '+curAdId);

		objFlash = getObject("objFlashPlayer");
		objFlash.loadedSwfAction('release', curAdId);	
	},
	
	setHitMc: function(status, adId, clickThroughObj){
		debugThis('setHitMc '+status+' adId '+adId+' clickThroughObj '+clickThroughObj);
		curAdId = adId;
		if(clickThroughObj != null)
			clickThroughData = clickThroughObj;
			
		if(status){
			hitAreaVideo.cursor = 'Hand';
			hitAreaVideo.Visibility = 'Visible';
		}else{
			hitAreaVideo.cursor = 'Arrow';
			hitAreaVideo.Visibility = 'Collapsed';
		}
	},

	
	loadSL: function(url, width, height){

		if(url.substring(0,5) == "media" ){
			url = domain + url;
		}
		
		debugThis("loadSL "+url);
		
		mediaOpen = false;
		slPlayer.width = width;
		slPlayer.height = height;
		slPlayer.source = url;
		bufferingStatus = 3;
		
		//set default volume
		controls.setVolume();
		//this.setVolumeSL(0, true);
	},	
	
	loadSLOptin: function(url, width, height){
	
		mediaOpen = false;
	
		if(host.content.FullScreen){
			slPlayerOptin.Width = host.content.ActualWidth;
			slPlayerOptin.Height = host.content.ActualHeight;
		}else{
			slPlayerOptin.width = width;
			slPlayerOptin.height = height;	
		}
		slPlayerOptin.source = url;
		slPlayerOptin.AutoPlay = false;
		
		debugThis('slPlayerOptin.source '+slPlayerOptin.source)
	},
	
	getVideoTimeSL: function(){
		//debugThis('getVideoTimeSL '+slPlayer.Position.seconds)
		var videoTime = 0;
		if(!optinActive){
			videoTime = slPlayer.Position.seconds;
		}else{
			videoTime = slPlayerOptin.Position.seconds;
		}
		return videoTime;
	},
	
	getTotalTimeSL: function(){
		
		var totalTime = 0;
		if(!optinActive){
			totalTime = slPlayer.NaturalDuration.seconds;
		}else{
			totalTime = slPlayerOptin.NaturalDuration.seconds;
		}
		return totalTime;
	},
	
	setVolumeSL: function(vol, fromControls){
		debugThis(' setVolumeSL '+vol);
		if(vol == 0 && !fromControls){
			return;	
		}
		if(!optinActive){
			slPlayer.Volume = vol/100;
		}else{
			slPlayerOptin.Volume = vol/100;
		}
	},
	
	setMuteSL: function(status){
		debugThis(' setMuteSL '+status); 
		if(!optinActive){
			slPlayer.IsMuted  = status;
		}else{
			slPlayerOptin.IsMuted  = status;
		}
	},
	
	//set controls for wmp
	sendControlSL: function(contolState) {
		debugThis(' sendControlSL '+contolState+' optinActive:'+optinActive);
		if(!optinActive){
			switch(contolState) {
				case 1: // Stop
					slPlayer.stop();
					slPlayer.source = '';
					break;
				case 2: // Pause
					slPlayer.pause();
					break;
				case 3: // Play
					slPlayer.play();
					setVisibility('silverlightPlayer', true);
					setStatus('playing');
					break;
				case 4: // Previous
					//
					break;
				case 5: // Next
					//
					break;
			}
		}else{
			switch(contolState) {
				case 1: // Stop
					
					break;
				case 2: // Pause
					slPlayerOptin.pause();
					break;
				case 3: // Play
					slPlayerOptin.Visibility = 'Visible';
					slPlayerOptin.play();
					break;
				case 4: // Previous
					//
					break;
				case 5: // Next
					//
					break;
			}
		}
	},
	
	stopSLOptin: function(){
		slPlayerOptin.stop();
		slPlayerOptin.source = '';
	},
	
	//set the pos of player
	setPlayPosSL: function(pos){
		debugThis('setPlayPosSL '+pos);
		var playPos = String(dateFormat(pos, 3600));
		debugThis('playPos '+playPos);
		slPlayer.Position = playPos;
	},
	
	media_state_changed: function(){
		var state = slPlayer.CurrentState;
		switch(state){
			case 'Buffering':
				this.showBuffer(true);
				bufferingStatus = 1;
				break;
			case 'Stopped':
				this.showBuffer(false);
				resetPlayer = true;
				playStatus = 'stopped';
				break;
			case 'Paused':
				//
				break;
			case 'Playing':
				//if(slPlayer.BufferingProgress != 0)
				this.showBuffer(false);
				resetPlayer = false;
				bufferingStatus = 2;
				setStatus('playing');	
				break;
			case 'Opening':
				this.showBuffer(true);
				break;
			case 'Closed':
				bufferingStatus = 3;
				break;
		}
		debugThis(' media_state_changed '+state);
	},
	
	media_opened: function(){
		if(mediaOpen){
			bufferingStatus = 3;
			var objFlash = getObject("objFlashPlayer");
			objFlash.playNextWmv();
			debugThis("send play next media ");
			
			setStatus('waiting');	
		}
		mediaOpen = true;
		debugThis(' media_opened ');
	},
	
	media_ended: function(){
		if(!resetPlayer){
			bufferingStatus = 3;
	
			var objFlash = getObject("objFlashPlayer");
			objFlash.playNextWmv();
			debugThis("send play next media ");
			
			setStatus('waiting');	
		}
		slPlayer.source = '';
		debugThis(' media_ended ');
	}, 
	
	media_error: function(sender, args){
		debugThis("ERROR WITH CONTENT");
		var obj = {'errorGroup':'Silverlight', 'errorCode':'-1'};
		
		var objFlash = getObject("objFlashPlayer");
		objFlash.errorWmv(obj, curIndexId);
		
		objFlash.stopCheckBuffer("WMV", curIndexId);
	},
	
	getBufferSl: function(){
		debugThis("getBufferSl ");
		var bufferValue;
		if(bufferingStatus == 1 || bufferingStatus == 3){
			bufferValue = true;
			bufferDone = false;
		}else if(bufferingStatus == 2 && slPlayer.BufferingProgress != 0){
			bufferValue = false;
			bufferDone = true;
		}else{
			bufferValue = true;
			bufferDone = false;
		}
		return bufferValue;
	},
	
	bufferingChange: function(){
		//debugThis(slPlayer.BufferingProgress);
		//debugThis(' buffering ');
	},
	
	downloadChange: function(){
		//debugThis("downloadChange "+slPlayer.DownloadProgress);
	},
	
	getSlDownloadProgress: function(){
		//debugThis(' getSlDownloadProgress '+slPlayer.DownloadProgress);
		return Math.round(slPlayer.DownloadProgress * 100);
	},

	showBuffer: function(status){
		buffer = root.findName('BufferHolder');
		slBuffer = status;
		if(status){
			buffer.Visibility = 'Visible';
			buffer.findName('spinIAd').addEventListener('completed', Silverlight.createDelegate(this, this.restartSpin));
			buffer.findName('spinIAd').Begin();
		}else{
			buffer.Visibility = 'Collapsed';
		}
	},
	
	restartSpin: function(){
		if(!slBuffer){
			return;
		}
		buffer.findName('spinIAd').Stop();
		buffer.findName('spinIAd').Begin();
		debugThis('buffering .....'+slPlayer.BufferingProgress);	
	}, 
	
	
	setVisibility: function(status){
		debugThis('setVisibility videoPLayer .....');
		if(controls)
			controls.setVisibility(status);
	}, 
	
	resetPlayer: function(){
		debugThis('resetPlayer silverlight');
		this.showBuffer(false);
	}
};


//timeout function -  can defined duration, obj and funct to call after
sl.TimeOut = function(time, obj, initFunct)
//function TimeOut(time, obj, initFunct)
{
	var timeOut = time;
	var object = obj;
	var funct = initFunct;
	
	function timoutFunc(){
		object[funct]();
	}
	
    this.initTimeOut = function(){
		setTimeout(timoutFunc, timeOut);
	};
};




function checkSlPlugin(){
	var timeOut = setTimeout("checkSlPlugin()", 100);
	
	var hasPlugin = false;
	debugThis('SilverlightPlugIn '+document.getElementById('SilverlightPlugIn'));
	debugThis('Silverlight.isInstalled '+Silverlight.isInstalled('3.0'));
	
	if(document.getElementById('SilverlightPlugIn') != null){	
		hasPlugin = true;
	}
	debugThis('checkSlPlugin '+hasPlugin);
	var objFlash = getObject("objFlashPlayer");
	objFlash.returnPlugInCheck(hasPlugin);
	
	clearInterval(timeOut);
	//add 1 item for xaml so site doesnt redirect
	if(!hasPlugin)
		itemLoaded();
}



//present user with get silverlight plugin screen
function getPlugIn(){
	debugThis('getPlugIn');
	setVisibility('flashOverlayTrans', false);
	//setVisibility('flashOverlay', false);
	setVisibility('silverlightPlayer', true);
	
	setVisibilityVideo(false, 'flashOverlay');
	var objFlash = getObject("objFlashPlayer");
	if(objFlash)
		objFlash.setVisibilityVideo(false);
}












/****************************************  OVERLAY ************************************/

var maxOverlayWidth = 500;
var overlayActive = false;

sl.Overlay = function(plugIn, rootElement) 
{	
	this.plugIn = plugIn;
	this.rootElement = rootElement;
	
	var ratioW = videoWidth / this.rootElement.width;
	var ratioH = videoHeight / this.rootElement.height;
	this.startRatio = ratioW;
	if(ratioW > ratioH){
		this.startRatio = ratioH;
	}
	
	debugThis('this.startRatio:'+this.startRatio);
	
	this.optinHolder = rootElement.findName('optinHolder');
	this.optinHolder['Canvas.Top'] = videoHeight;
	this.overlay = rootElement.findName('overlay');
	this.iVideoOverlay = rootElement.findName('iVideoOverlay');
	this.bg = this.overlay.findName('overlayBg');
	this.imageHolder = this.overlay.findName('imageHolder');
	this.hitArea = this.overlay.findName('overlayHitArea');
	this.closeBtn = this.optinHolder.findName('closeMc');
	this.iVideoText = this.iVideoOverlay.findName('iVideoText');
	
	this.adjustOptin();
	this.adjustiVideo(ratioW, videoHeight);
	
	this.overlay.Visibility = 'Collapsed';
	this.iVideoOverlay.Visibility = 'Collapsed';
	
	this.timer = rootElement.findName("timer");
	this.timer.addEventListener("completed", Silverlight.createDelegate(this, this.animateOpacity));
	this.closeBtn.addEventListener("MouseLeftButtonUp", Silverlight.createDelegate(this, this.closeOptin));
	this.closeBtn.addEventListener("MouseEnter", Silverlight.createDelegate(this, this.closeEnter));
	this.closeBtn.addEventListener("MouseLeave", Silverlight.createDelegate(this, this.closeLeave));
	this.hitArea.addEventListener("MouseLeftButtonUp", Silverlight.createDelegate(this, this.startOptIn));
	this.showiVideoOverlay = rootElement.findName("showiVideoOverlay");
	this.hideiVideoOverlay = rootElement.findName("hideiVideoOverlay");
	
	this.isFullscreen = false;
	this.isIVideo = false;
	
	this.showB = "On";
	this.tweenCase = "PosTween";
};

sl.Overlay.prototype =
{
	loadOverlay: function(url, metaData, adId, tweenC, showB){
		debugThis('loadOverlay: url:'+url+' tweenC:'+tweenC+' showB:'+showB);
		if(tweenC != undefined)
			this.tweenCase = tweenC;

		if(showB != undefined)
			this.showB = showB;
		
		if(metaData){
			if(typeof(metaData['inputString']) == 'string'){
				this.isIVideo = true;
				this.startiVideoOverlay(metaData);
			}else{
				this.isIVideo = false;	
				this.startOverlay(url, metaData, adId);
			}	
		}else{
			this.isIVideo = false;	
			this.startOverlay(url, metaData, adId);
		}
		
	}, 
	
	
	startOverlay: function(url, metaData, adId){
		if(this.showBg == 'On'){
			this.showB = true;
		}else{
			this.showB = false;
		}

		//cerate a new xmal image
		var xamlFragment = '<Image Name="image" RenderTransformOrigin="0.5,0.5" Stretch="None" Canvas.ZIndex="0"/>';
		this.image = this.plugIn.content.createFromXaml(xamlFragment, false);
		this.imageHolder.children.add(this.image);
		this.imageHolder.Opacity = 0;
		
		var downloader = videoPlayer.plugIn.createObject("downloader");
        //add an event listener to print dots
        downloader.addEventListener("completed", Silverlight.createDelegate(this, this.overlayLoaded));
		
		//for silverlight 1 file needs to come from same domain (cross domain policy)
		//url = url.replace("http://staging.bigpondvideo.com/", "http://iad/");
		url = "http://testing.iad.netventures.com.au/temp/sample.png";
		debugThis('loadOverlay: '+url);
		
        downloader.open("GET", url);
        //start the download
        downloader.send();
	},
	
	
	startiVideoOverlay: function(metaData){
		this.iVideoOverlay.Visibility = 'Visible';
		this.showiVideoOverlay.begin();	
		this.iVideoText.Text = metaData['inputString'];
		this.logoImage = this.iVideoOverlay.findName("iVideoLogo");
		
		this.iVideoText['Canvas.Left'] = (this.rootElement.width - this.iVideoText.ActualWidth)/2;
		
		debugThis('slWidth: '+slWidth);
		debugThis('this.iVideoText.ActualWidth: '+this.iVideoText.ActualWidth);
		debugThis("this.iVideoText['Canvas.Left']: "+this.iVideoText['Canvas.Left']);
		debugThis('(videoWidth / this.rootElement.width): '+(videoWidth / this.rootElement.width));
		
		var downloader = videoPlayer.plugIn.createObject("downloader");
		downloader.addEventListener("completed", Silverlight.createDelegate(this, this.logoLoaded));
		var url = domain + "/App/EmbeddedPlayer1_2/Images/aflLogo.png";
		debugThis('loadOverlay: '+url);
		
        downloader.open("GET", url);
        //start the download
        downloader.send();
	},
	
	overlayLoaded: function(sender){
		debugThis('overlayLoaded '+this.image);
		
		//show the image once its downloaded
        this.image.setSource(sender, "");
		this.overlay.Visibility = 'Visible';
		this.bg.Opacity = 0;
		
		controls.enableFullscreen(false);
		overlayActive = true;
		
		this.getImageDimension();
	}, 
	
	logoLoaded: function(sender){
		debugThis('logoLoaded '+this.logoImage);
		
		//show the image once its downloaded
        this.logoImage.setSource(sender, "");
	}, 
	
	setFullscreen: function(status){
		this.isFullscreen = status;
		
		if(status){
			slWidth = host.content.ActualWidth;
			slHeight = host.content.ActualHeight;
		}else{
			slWidth = videoWidth;
			slHeight = 	videoHeight;
		}
	},
	
	getImageDimension: function(){
		debugThis('getImageDimension '+this.image.width);
		if(this.image.width == 0){
			var obj  = new sl.TimeOut(100, this, 'getImageDimension');
        	obj.initTimeOut();
			return;
		}
		
		debugThis('slWidth '+slWidth);
		debugThis('slHeight '+slHeight);
		
		var ratio = 1;
		if(this.isFullscreen){
			ratio = this.scaleImg();
		}
		this.posImg(ratio);
		
		this.imageHolder.Visibility = 'Collapsed';
		
		this.initBg();
	},
	
	clearOverlay: function(){
		debugThis('clearOverlay sl isIVideo'+this.isIVideo);
		
		if(this.isIVideo){
			this.hideiVideoOverlay.begin();	
		}else{
			if(this.image)
				this.imageHolder.children.remove(this.image);
			this.overlay.Visibility = 'Collapsed';
			overlayActive = false;	
		}
	}, 
	
	initBg: function(){
		if(this.showB){
			var ratio = this.scaleBg();
			this.posBg(ratio);
			
			this.scaleHitArea(ratio, ratio);
			this.posHitArea(ratio, ratio);
			
			this.timerTarget = 'bg';
			this.animateOpacity();	
		}else{
			this.initImg();
		}
	},
	
	adjustOverlay: function(){
		
		if(!overlayActive)
			return;
		
		if(this.showB){
			if(this.isFullscreen){
				var ratio = this.scaleImg();
				this.posImg(ratio);
				var ratioW = this.image.width*ratio / this.hitArea.width;
				var ratioH = this.image.height*ratio / this.hitArea.height;
			}else{
				var ratio = this.scaleImg(1);
				this.posImg(ratio);
				var ratioW = this.image.width / this.hitArea.width;
				var ratioH = this.image.height / this.hitArea.height;
			}
			
			var ratio = this.scaleBg();
			this.posBg(ratio);
			
			this.scaleHitArea(ratio, ratio);
			this.posHitArea(ratio, ratio);
		}else{
			if(this.isFullscreen){
				var ratio = this.scaleImg();
				this.posImg(ratio);
				var ratioW = this.image.width*ratio / this.hitArea.width;
				var ratioH = this.image.height*ratio / this.hitArea.height;
			}else{
				var ratio = this.scaleImg(1);
				this.posImg(ratio);
				var ratioW = this.image.width / this.hitArea.width;
				var ratioH = this.image.height / this.hitArea.height;
			}
			
			this.scaleHitArea(ratioW, ratioH);
			this.posHitArea(ratioW, ratioH);
		}
	},
	
	scaleBg: function(){
		debugThis('scaleBg '+this.image.width);
		var bgWidth = this.bg.width;
		if(this.isFullscreen){
			var newWidth = maxOverlayWidth / 0.8;
		}else{
			var newWidth = this.image.width / 0.8;
		}
		var ratio = newWidth / bgWidth;
	
		//scale bg
		var transformGroup = this.bg.renderTransform;
		var scaleTransform = transformGroup.children.getItem( 0 );
		scaleTransform.ScaleX = ratio;
		scaleTransform.ScaleY = ratio;
		
		debugThis('scaleBg '+ratio);
		return ratio;
	},
	
	
	posBg: function(ratio){
		debugThis('posBg ');
		
		//resize bg
		this.bg['Canvas.Left'] = (slWidth - this.bg.width)/2;
		if(!this.isFullscreen){
			this.bg['Canvas.Top'] = slHeight - this.bg.height*ratio + (this.bg.height * ratio - this.bg.height)/2 - 5;
		}else{
			this.bg['Canvas.Top'] = slHeight - this.bg.height*ratio + (this.bg.height * ratio - this.bg.height)/2 - 55;
		}
	},
	
	scaleHitArea: function(ratioW, ratioH){
		debugThis('scaleHitArea this.showB:'+this.showB);
		
		//scale hitarea
		var transformGroup = this.hitArea.renderTransform;
		var scaleTransform = transformGroup.children.getItem( 0 );
		scaleTransform.ScaleX = ratioW;
		scaleTransform.ScaleY = ratioH;
	},
	
	resizeHitArea: function(width, height){
		debugThis('resizeHitArea width '+width+' height '+height);

		this.hitArea.findName('hitRect').width = this.hitArea.width = width;
		this.hitArea.findName('hitRect').height = this.hitArea.height = height;
	},
	
	
	posHitArea: function(ratioW, ratioH){
		debugThis('posHitArea '+this.hitArea.width);
		
		//resize bg
		this.hitArea['Canvas.Left'] = (slWidth - this.hitArea.width)/2;
		if(!this.isFullscreen){
			this.hitArea['Canvas.Top'] = slHeight - this.hitArea.height*ratioH + (this.hitArea.height * ratioH - this.hitArea.height)/2 - 5;
		}else{
			this.hitArea['Canvas.Top'] = slHeight - this.hitArea.height*ratioH + (this.hitArea.height * ratioH - this.hitArea.height)/2 - 55;
		}
		
	},
		
	scaleImg: function(setRatio){
		debugThis('scaleImg '+setRatio);
		
		if(setRatio == undefined){
			var ratio = maxOverlayWidth / this.image.width;
		}else{
			var ratio = setRatio;
		}
		
		//scale bg
		var transformGroup = this.imageHolder.renderTransform;
		var scaleTransform = transformGroup.children.getItem( 0 );
		scaleTransform.ScaleX = ratio;
		scaleTransform.ScaleY = ratio;
		
		debugThis('scaleImg '+ratio);
		
		return ratio;
	},
	
	posImg: function(ratio){
		debugThis('posImg');
		this.imageHolder.width = this.image.width;
		this.imageHolder.height = this.image.height;
		this.imageHolder['Canvas.Left'] = (slWidth - this.imageHolder.width) / 2;
		if(!this.isFullscreen){
			this.imageHolder['Canvas.Top'] = slHeight - this.imageHolder.height - 5;
		}else{
			this.imageHolder['Canvas.Top'] = slHeight - this.imageHolder.height*ratio + (this.imageHolder.height*ratio - this.imageHolder.height)/2 - 55;
		}
		debugThis('posImg');
	},
	
	
	adjustOptin: function(){
		var dimension = this.getDimension();
		slWidth = dimension['width'];
		slHeight = dimension['height'];
		
		this.optinHolder.findName('topBar')['Canvas.Left'] = 0;
		this.optinHolder.findName('topBar')['Canvas.Top'] = 0;
		this.optinHolder.findName('topBar').width = slWidth;
		
		this.optinHolder.findName('rightBar')['Canvas.Left'] = slWidth - this.optinHolder.findName('rightBar').width;
		this.optinHolder.findName('rightBar')['Canvas.Top'] = 0;
		this.optinHolder.findName('rightBar').height = slHeight;
		
		this.optinHolder.findName('bottomBar')['Canvas.Left'] = 0;
		this.optinHolder.findName('bottomBar')['Canvas.Top'] = slHeight - this.optinHolder.findName('bottomBar').height;
		this.optinHolder.findName('bottomBar').width = slWidth;
		
		this.optinHolder.findName('leftBar')['Canvas.Left'] = 0;
		this.optinHolder.findName('leftBar')['Canvas.Top'] = 0;
		this.optinHolder.findName('leftBar').height = slHeight;
	
		this.optinHolder.findName('closeMc')['Canvas.Left'] = slWidth - this.optinHolder.findName('closeMc').width - 5;
		


		this.optinHolder.findName('buffer').width = slWidth;
		this.optinHolder.findName('buffer').height = slHeight;
	},
	
	adjustiVideo: function(ratioW, height){
		debugThis('adjustiVideo ratioW:'+ratioW+ ' height:'+height);
		//resize iVideo overlay 
		var transformGroup = this.iVideoOverlay.renderTransform;
		var scaleTransform = transformGroup.children.getItem( 0 );
		scaleTransform.ScaleX = ratioW;
		scaleTransform.ScaleY = ratioW;
		
		//repos ivideo overlay
		this.iVideoOverlay['Canvas.Top'] = 	height - this.iVideoOverlay.height * ratioW;	
		
		//set font size
		if(videoWidth < 400){
			this.iVideoText.FontSize = '20';
		}else if(videoWidth < 500){
			this.iVideoText.FontSize = '18';
		}
		debugThis('this.iVideoText.FontSize:'+this.iVideoText.FontSize);
	},

	getRatio: function(width, height){
		var ratioW = width / this.rootElement.width;
		var ratioH = height / this.rootElement.height;
		
		var ratio = ratioW;
		if(ratioW > ratioH){
			ratio = ratioH;
		}
		
		return ratio;
	},
	
	getDimension: function(){
		var dimension = {};
		dimension['width'] = videoWidth;
		dimension['height'] = videoHeight;
		if(this.plugIn.content.FullScreen){
			dimension['width'] = host.content.ActualWidth;
			dimension['height'] = host.content.ActualHeight;
		}
		
		return dimension;
	},

	
	startOptIn:function(){
		//debugThis('startOptIn');
		var objFlash = getObject("objFlashPlayer");
		if(typeof(objFlash.startOptIn) == 'function'){
			objFlash.startOptIn();	
		}
		
		//disable fullscreen btn
		controls.enableFullscreen(false);
	},
	
	closeOptin: function(){
		var objFlash = getObject("objFlashPlayer");
		if(typeof(objFlash.startOptIn) == 'function'){
			objFlash.finishOptIn('cancelled');
		}
		
		//disable fullscreen btn
		controls.enableFullscreen(false);
	},
	
	closeEnter: function(sender){
		sender.Opacity = 1;
	},
	
	closeLeave: function(sender){
		sender.Opacity = 0.7;
	},
	
	showOptIn: function(){
		JSTweener.addTween(this.optinHolder, {
            "Canvas.Top": 0,
            time: 0.8,
            transition: "easeOutBack",
			onComplete:this.optInPlay
        })
	},
	
	hideOptIn: function(){
		slPlayerOptin.Visibility = 'Collapsed';
		if(host.content.FullScreen){
			targetTop = host.content.ActualHeight;
		}else{
			targetTop = videoHeight;
		}

		JSTweener.addTween(this.optinHolder, {
            "Canvas.Top": targetTop,
            time: 0.4,
            transition: "easeInQuad",
			onComplete:this.optInDone
        })
	},
	
	optInPlay: function(){
		var objFlash = getObject("objFlashPlayer");
		if(typeof(objFlash.sendStartOptIn) == 'function'){
			objFlash.sendStartOptIn();	
		}
		
		//disable fullscreen btn
		controls.enableFullscreen(true);
	},
	
	optInDone: function(){
		//disable fullscreen btn
		controls.enableFullscreen(true);
	},
	
	showOptinBg: function(status){
		if(status){
			this.optinHolder.findName('buffer').Visibility = 'Visible';
		}else{
			this.optinHolder.findName('buffer').Visibility = 'Collapsed';
		}
	},
	
	animateOpacity: function(sender, args) {
		if(this.timerTarget == 'bg'){
			this.bg.Opacity += 0.1;
			if(this.bg.Opacity < 1){
				this.timer.begin();	
			}else{
				this.timerTarget = '';
				this.initImg();	
			}	
		}else if(this.timerTarget == 'img'){
			this.imageHolder.Opacity += 0.05;
			if(this.imageHolder.Opacity < 1){
				this.timer.begin();	
			}else{
				this.timerTarget = '';
			}
		}
	},
	
	initImg: function(){
		debugThis('initImg ');
		
		this.imageHolder.Visibility = 'Visible';
		this.imageHolder.Opacity = 0;
		
		if(!this.showB){
			if(this.isFullscreen){
				var ratio = this.scaleImg();
				var ratioW = this.image.width*ratio / this.hitArea.width;
				var ratioH = this.image.height*ratio / this.hitArea.height;
			}else{
				var ratioW = this.image.width / this.hitArea.width;
				var ratioH = this.image.height / this.hitArea.height;
			}
			
			this.scaleHitArea(ratioW, ratioH);
			this.posHitArea(ratioW, ratioH);
		}
		
		this.startTween();
		
		controls.enableFullscreen(true);
	},
	
	startTween: function(){
		debugThis('startTween ');
		switch(this.tweenCase){
			case 'PosTween':
				funct = 'posTween';
				break;
			
			case 'ScaleTween':
				funct = 'scaleTween';
				break;
			
			case 'AlphaTween':
				this.timerTarget = 'img';
				funct = 'alphaTween';
				break;
		}
		this[funct]();
	},
	
	alphaTween: function(){
		//debugThis('alphaTween '+this.image.width);
		this.animateOpacity();
	}, 
	
	scaleTween: function(){
		//debugThis('scaleTween');
		this.imageHolder.Opacity = 1;
		var transformGroup = this.imageHolder.renderTransform;
		var scaleTransform = transformGroup.children.getItem( 0 );
		var targetScale = scaleTransform.ScaleX;
		scaleTransform.ScaleX = 0;
		scaleTransform.ScaleY = 0;
		
     	JSTweener.addTween(scaleTransform, {
			scaleX: targetScale,
            scaleY: targetScale,
            time: 0.4,
            transition: 'easeOutBack'
        });
	}, 
	
	posTween: function(){
		//debugThis('posTween');
		this.imageHolder.Opacity = 1;
		var targetTop = this.imageHolder['Canvas.Top'];
		
		var dimension = this.getDimension();
		slWidth = dimension['width'];
		slHeight = dimension['height'];
		
		this.imageHolder['Canvas.Top'] = slHeight;
		JSTweener.addTween(this.imageHolder, {
            "Canvas.Top": targetTop,
            time: 0.4,
            transition: "easeOutBack"
        });
	}
};