// JavaScript Document

//******************JS TO FLASH*******************
var InternetExplorer = navigator.appName.indexOf("Microsoft") != -1;
//init the time variables
var curTime = '';
var totTime = '';
//timer interval
var timerInterval;
//random id
var randId;
//volume 
var vol;
//default domain
var domain;
//controls
var controls;
//passed params
var passedParams;

function cr4InitIad(params, targetDiv){
	
	//set the domain for the player
	if(location.hostname == 'iad'){
		domain = 'http://iad/';
	}else if(location.hostname == 'testing.iad.netventures.com.au'){
		domain = 'http://testing.iad.netventures.com.au/';
	}else if(location.hostname == 'staging.bigpondvideo.com'){
		domain = 'http://staging.bigpondvideo.com/';
	}else{
		domain = 'http://bigpondvideo.com/';
	}
	
	var url = domain+"index_iad.php";
	
	//get the users screen resolution for fullscreen mode
	params['screenWidth'] = screen.width;
	params['screenHeight'] = screen.height;
	
	//catch domain and url
	params['domain'] = location.hostname;
	params['location'] = encodeURIComponent(location, "UTF-8");;
	
	//define a random id for flash comm
	randId = Math.ceil(Math.random()*1000);
	params['randId'] = randId;
	
	//log fake channelId
	params['channelId'] = location.hostname;
	
	//set the controls for cr4PlayContent
	controls = params['controls'];
	
	//check if debug is on
	params['debug'] = 0;
	var searchUrl = location.search;
	if(searchUrl != ""){
		searchUrl = searchUrl.slice(1);
		param_ar = searchUrl.split("&");
		for(i=0; i<param_ar.length; i++){
			param = param_ar[i].split("=");
			if(param[0] == 'debugNv' && param[1] == '1'){
				params['debug'] = 1;
			}
		}	
	}
	
	//encode urls
	if(params['bClickThrough'] != undefined){
		params['bClickThrough'] = encodeURIComponent(params['bClickThrough'], "UTF-8");
	}
	
	//create the param string
	var paramStr = getParamStr(params);
	url += paramStr;
	
	//define the size of the iframe
	var iFrameWidth = params['width'];
	var iFrameHeight = getHeight(params);
	
	if(targetDiv != undefined){
		//cerate div for swf listener on client side
		document.getElementById(targetDiv).innerHTML = '<div id="flashApiDiv"></div>';
		document.div = eval('document.getElementById("flashApiDiv")');
		document.div.style.position="absolute";
		document.div.style.display = "block";
		document.div.style.width = 100;
		document.div.style.height = 100;
		document.div.style.zIndex = 20001;
	}else{
		//cerate div for swf listener on client side
		document.write('<div id="flashApiDiv"></div>');
		document.div = eval('document.getElementById("flashApiDiv")');
		document.div.style.position="absolute";
		document.div.style.display = "block";
		document.div.style.width = 100;
		document.div.style.height = 100;
		document.div.style.zIndex = 20001;	
	}
	
	var swfWidth = "\"0\"";
	var swfHeight = "\"0\"";
	if(params['debug'] == '1'){
		var swfWidth = "\"100\"";
		var swfHeight = "\"100\"";
		iFrameWidth = 1000;
	}else{
		setVisibility('flashApiDiv', false);	
	}

	//create iframe for video holder
	if(targetDiv != undefined){
		document.getElementById(targetDiv).innerHTML += '<div id="iframe" style="background:#000; width:'+params['width']+'px;"></div>';
	}else{
		document.write('<div id="iframe" style="background:#000; width:'+params['width']+'px;"></div>');
	}
	var iframe = "<iframe name=\"Cr4Player\" id=\"Cr4Player\" src = '"+url+"' scrolling=\"no\" marginheight=\"0\" align= \"center\" marginwidth=\"0\" width=\""+iFrameWidth+"\" height =\""+iFrameHeight+"\"  frameborder=\"0\"  allowTransparency=\"true\"></iframe>";
	document.getElementById('iframe').innerHTML = iframe;
	
	var swfUrl = domain+"App/EmbeddedPlayer/Flash/flash2.swf";
	
	var flashContainer = document.getElementById('flashApiDiv');
	flashContainer.appendChild(createSwf(swfUrl, swfWidth, swfHeight, 'flashObjCr4', "randFlashId="+randId));
	
	if(params['controls'] == 'external' && (params['autoStart'] == '1' || params['autoStart'] == undefined)){
		//start the timer
		initTimer();
	}
	vol = 80;
}

function cr4InitLeaveBehind(params, targetDiv){
	if(targetDiv != undefined){
		document.getElementById(targetDiv).innerHTML = '<div id="leaveBehind" style="clear:both;  width:'+params['width']+'px; height:'+params['height']+'px"></div>';
	}else{
		document.write('<div id="leaveBehind" style="clear:both;  width:'+params['width']+'px; height:'+params['height']+'px"></div>');
	}

	var swfUrl = domain+"App/EmbeddedPlayer/Flash/leaveBehindHolder.swf";
	var flashContainer = document.getElementById('leaveBehind');
	
	flashContainer.appendChild(createSwf(swfUrl, params['width'], params['height'], 'flashLeaveBehind', 'randFlashId='+randId+'&initBanner='+params['initBanner']+'&initUrl='+params['initUrl']));
}

//create the param string
function getParamStr(params){
	var paramStr = "?rand="+randId;
	for(var obj in params){
		param = params[obj];
	 	if(param != ""){
			// if it is a url it needs to be encoded
			if(obj == "url"){
				param = escape(param);
			}
			paramStr += "&" + obj + "=" + param;
		}
	}

	return paramStr;
}


//get the height of iframe based on settings
function getHeight(params){
	var iFrameHeight = 0;
	
	var defaultPlayerWidth = 512;
	var ratio = defaultPlayerWidth / Number(params['width']);
	
	//check if title bar is needed and what size
	var titleHeight = 0;
	if(params['titleBar'] == 1){
		//get the resize ratio of player
		var defaultTitleHeight = 31;
		titleHeight = Math.round(defaultTitleHeight / ratio);
	}
	
	//check if control bar is needed and what size
	var controlHeight = 0;
	if(params['controls'] == 'internal'){
		//get the resize ratio of player
		var defaultControlHeight = 40;
		controlHeight = Math.round(defaultControlHeight / ratio);
	}
	
	
	iFrameHeight = Number(params['height']) + titleHeight + controlHeight;
	
	return iFrameHeight;
}

//start iAd
function cr4PlayContent(params){
	var objFlash = getObject("flashObjCr4");
	try{objFlash.playContent(params);}catch(e){}
	
	initTimer();
}

//call for ad complete
function playCompletedApi(status, url, sendPlay){
	if(status == 'Content'){
		try{cr4ContentCompleted(url);}catch(e){}
	}
	//adCompleted(status);
	if(status == 'Ad'){
		if(sendPlay){
			sendCommand('play');	
		}
		try{cr4AdCompleted(url);}catch(e){}
	}
	//allCompleted(status);
	if(status == 'All'){
		try{cr4AllCompleted(url);}catch(e){}
		killTimer();
	}
}

//call for ad complete
function playStartedApi(status){
	if(status == 'Content'){
		try{cr4ContentStarted();}catch(e){}
	}
	//adCompleted(status);
	if(status == 'Ad'){
		try{cr4AdStarted();}catch(e){}
	}
}

//call for error with content
function setError(){
	try{cr4ErrorOccured();}catch(e){}
	killTimer();
}

//commands send from external control on client side
function sendCommand(status, value){
	var objFlash = getObject("flashObjCr4");
	try{objFlash.sendCommand(status, value);}catch(e){}
	if(status == 'volume'){
		vol = value;
	}
}


function initTimer(){
	if(controls != 'external'){
		return;	
	}
	//set player to playing mode
	setTimeout("startPlayback()", 500);
	//clear the value
	curTime = '';
	totTime = '';
	//clear the interval
	killTimer();
	//get the val from swf
	timerInterval = setInterval(cr4CheckTime, 1000);
}

function startPlayback(){
	var objFlash = getObject("flashObjCr4");
	try{objFlash.startPlayback();}catch(e){}
}

function killTimer(){
	try{clearInterval(timerInterval);}catch(e){}
}


//sends command to flash
function cr4CheckTime(){
	sendCommand('currentTime');
	sendCommand('totalTime');
}


//exposed API element
function cr4GetCurTime(){
	return(curTime);
}

function cr4GetDuration(){
	return(totTime);
}

function cr4GetVolume(){
	return(vol);
}

function cr4Play(){
	sendCommand('play');
}

function cr4Pause(){
	sendCommand('pause');
}

function cr4Stop(){
	sendCommand('stop');
	try{clearInterval(timerInterval);}catch(e){}
}

function cr4FastForward(){
	sendCommand('fastForward');
}

function cr4FastReverse(){
	sendCommand('fastReverse');
}

function cr4SetVolume(value){
	sendCommand('volume', Number(value));
}

function cr4SetCurrentPos(value){
	sendCommand('setCurrentPos', Number(value));
}

function cr4FullScreen(){
	sendCommand('fullScreen');
}



//callback from flash to set current time
function cr4SetCurTime(value){
	curTime = value;
}
//callback from flash to set duration
function cr4SetTotTime(value){
	totTime = value;
}


function createSwf(url, width, height, id, flashVars){

	var em=document.createElement("object");
	em.setAttribute("classid","clsid:D27CDB6E-AE6D-11cf-96B8-444553540000");
	em.setAttribute("codebase","http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,19,0");
	em.setAttribute("width",width);
	em.setAttribute("height",height);
	em.setAttribute("movie",url);
	em.setAttribute("flashVars",flashVars);
	em.setAttribute("allowScriptAccess","always");
	
	if(InternetExplorer){
		em.id=id;	
		em.setAttribute("name",id);
	}
	
	var pr3=document.createElement("param");
	pr3.setAttribute("name","allowScriptAccess");
	pr3.setAttribute("value","always");
	em.appendChild(pr3);
	
	if(!window.ActiveXObject){
		var embed=document.createElement("embed");
		embed.setAttribute("src",url);
		embed.setAttribute("id",id);
		embed.setAttribute("name",id);
		embed.setAttribute("qality","high");
		embed.setAttribute("width",width);
		embed.setAttribute("height",height);
		embed.setAttribute("allowScriptAccess","always");
		embed.setAttribute("wmode","window");
		embed.setAttribute("flashVars",flashVars);
		embed.setAttribute("type","application/x-shockwave-flash");
		em.appendChild(embed);
	}
	
	return em;
}

function clickThrough(url, target, depth, width, height){
	debugThis('url  '+url);
	if(target == "New"){
		//open location in new windows
		leftVal = (screen.width - width) / 2;
		topVal = (screen.height - height) / 2;
		tools = "scrollbars=yes,resizable=yes,width="+width+",height="+height+",left="+leftVal+",top="+topVal;
		debugThis('tools  '+tools);
		newWindow = window.open(url, 'newWin', tools);
		
		//define the focus
		if(depth == 'Front'){
			newWindow.focus();
		}else{
			//alert('self focus');
			self.focus();
		}
		
	}else if(target == "Same"){
		//open location in same window
		location.href=url;
		
	}else{
		
		newWindow = window.open(url, 'newWin', tools);
		newWindow.focus();
		
	}
	debugThis('end click thru  ');
}

//
function getObject(movieName) {
	var obj;
	//obj = document.getElementById(movieName);
	//if(obj == undefined){
		if (InternetExplorer) {
			obj = window[movieName];
		}else {			
			obj = document[movieName];
		}	
	//}
	return obj;
}


//set visibility of various divs (mainly flashOver)
function setVisibility(div, status){
	//alert(div + status);
	if(InternetExplorer){
		document.poppedLayer = eval('document.getElementById("'+div+'")');
		if(status){
			document.poppedLayer.style.marginLeft = defaultMarginLeft;
		}else{
			document.poppedLayer.style.marginLeft = -1500;
			//document.poppedLayer.style.margin = 330;
		}
	}else{
		if(status){
			document.getElementById(div).style.margin = "0px";
		}else{
			document.getElementById(div).style.margin = "-1000px";
			//document.getElementById(div).style.margin = "330px";
		}
	}
}

//prints out parameters of object beinmg passsed back to user
function dump(arr,level) {
	var dumped_text = "";
	if(!level) level = 0;
	 
	//The padding given at the beginning of the line.
	var level_padding = "";
	for(var j=0;j<level+1;j++) level_padding += "    ";
	 
	if(typeof(arr) == 'object') { //Array/Hashes/Objects 
		for(var item in arr) {
			var value = arr[item];
			   
			if(typeof(value) == 'object') { //If it is an array,
				dumped_text += level_padding + "'" + item + "' ...\n";
				dumped_text += dump(value,level+1);
			} else {
				dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
			}
		}
	} else { //Stings/Chars/Numbers etc.
	  	dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
	}
	return dumped_text;
}