// utilities
var dgComponentFlag=false;
// turn off on prod
var dgWriteStatusFlag=false;



var hr =  document.location.href; if ( hr.indexOf("matt.")>0 || hr.indexOf("192.168.0.1")>0 ) {
	dgComponentFlag=true;
	dgWriteStatusFlag=true;
	}


// Scripts to source in
var publishedMetadataScripts = [ com.cisco.dms.vp.ui.videoPortalConfigurationMetadata.configuration.resources.clientInterfaceMetadata ];

var _bn=navigator.userAgent;

var isIE = navigator.appName.indexOf("Explorer") >= 0;
var isMOZ = navigator.appName.indexOf("Netscape") >= 0;

var isMac = _bn.indexOf("Mac")>0;
var isSafari = _bn.indexOf("Safari")>0;
var isDOMSupport = ( !isSafari && ( isIE || isMOZ ) );

var sw=screen.availWidth; var sh=screen.availHeight;
var statusBarHeight = 25;
    
var isFullScreen = false;

loadSupportScripts();

// ================================

// triggered after page Loads
function onClientInterfaceMetadataLoaded() {

var _orgY = com.cisco.dms.vp.ui.videoPortalConfigurationMetadata.interface.dimension.template.height;


	_orgY += (isIE ) ? 0 : 0;
	_orgY += (isIE ) ? statusBarHeight : 0;

	_orgY += isMOZ ? statusBarHeight : 0;

	if ( isSafari ) { _orgY -= 15 }

// set value back

com.cisco.dms.vp.ui.videoPortalConfigurationMetadata.interface.dimension.template.height = _orgY;

// extra padding
if ( isIE ) {
	com.cisco.dms.vp.ui.videoPortalConfigurationMetadata.interface.dimension.template.width += 6;
}

}



// **********************

function getPageWH(xPart){  
          if( typeof window.innerWidth  == 'number' ) {
            pageW = window.innerWidth;
            pageH = window.innerHeight;
          } 
          else if(document.documentElement && document.documentElement.clientWidth ) {
            pageW = document.documentElement.clientWidth;
            pageH = document.documentElement.clientHeight;
          } 
          else{
            pageW = document.body.clientWidth;
            pageH = document.body.clientHeight;
          }
          if(xPart=="w")return pageW;
          else return pageH
        }
 
 
        function verifySize(){

var minW = com.cisco.dms.vp.ui.videoPortalConfigurationMetadata.interface.dimension.template.width;
var minH = com.cisco.dms.vp.ui.videoPortalConfigurationMetadata.interface.dimension.template.height;

          var resizeMe = false;
          var winW = parseInt(getPageWH("w"));
          var winH = parseInt(getPageWH("h"));
          if(minW>winW){winW=minW;resizeMe=true;}
          if(minH>winH){winH=minH;resizeMe=true;}
 
          if(resizeMe){
            window.resizeTo(winW,winH);
            var winW2 = winW - parseInt(getPageWH("w"));
            var winH2 = winH - parseInt(getPageWH("h"));
            window.resizeTo(winW + winW2,winH + winH2);
          }
 
        }




function sizeTo(width, height) {


// Flash UI dimension
var UIPanelWidth = com.cisco.dms.vp.ui.videoPortalConfigurationMetadata.interface.dimension.template.width;
var UIPanelHeight= com.cisco.dms.vp.ui.videoPortalConfigurationMetadata.interface.dimension.template.height;


	if (self.innerHeight) {	// not IE
		current_xsize = self.innerWidth;
		current_ysize = self.innerHeight;

		if ((current_xsize != UIPanelWidth && current_ysize != UIPanelHeight) || isFullScreen) {
			window.resizeTo(width, height)
			current_xsize = self.innerWidth;
			current_ysize = self.innerHeight;
			xsize = width + (width - current_xsize);
			ysize = height + (height - current_ysize) + 50;
			window.resizeTo(xsize, ysize);
			centerScreen();
		}

		//ie
	} else if (document.body) {


		current_xsize = document.body.clientWidth;
		current_ysize = document.body.clientHeight;

		if ((current_xsize != UIPanelWidth && current_ysize != UIPanelHeight) || isFullScreen) {
			try {

			self.resizeTo(width, height + 50);



			current_xsize = document.body.clientWidth;
			current_ysize = document.body.clientHeight;
			xsize = width + (width - current_xsize);
			ysize = height + (height - current_ysize);

			

			window.resizeTo(xsize, (ysize + 120 ));
			// access denied on patched Windows
			} catch ( e ) { }

			centerScreen();
		}

	} else {


		window.innerWidth = width;
		window.innerHeight = height;

		var flashDOM = getDOM("flashLayer");
		var fs = flashDOM.style;

		if (!isFullScreen) {
			fs.width = width;
			fs.height = height - 5;

		} else {

			fs.width = "100%";
			fs.height = "100%";

		}

		current_xsize = window.outerWidth;
		current_ysize = window.outerHeight;
		centerScreen();
	}

}

// ticker call only : make taller if ticker
function changeWindowHeight() {
	with ( com.cisco.dms.vp.ui.videoPortalConfigurationMetadata.interface.dimension.template ) {
		sizeTo( width, height);
	}
}

// fully expand 
function makeFullScreen()
{
	isFullScreen = true;


	with ( com.cisco.dms.vp.ui.videoPortalConfigurationMetadata.interface.dimension.video.window ) {
		var videoDimensionRatio  =  width / height;
	}

	turnOffTicker();
	var screenWidth = sw; var screenHeight = sh; var leftPosition = 0;

	if ( isIE ) {

		leftPosition  -= 4; // win border

		screenHeight -= 80;
			window.detachEvent("onresize", _MSPatched_resizer); 

		sw = videoDimensionRatio * sh;

			// FLV impl
			if ( ASImplementationVersion == 2 ) {
			//getFlashComponent().style.width = "100%";
			//getFlashComponent().style.height = "100%";

				getFlashComponent().style.width = sw;

			//getFlashComponent().setVariable("Stage.scaleMode", "noscale") ;
			/*
			exactfit
			showall
			noborder
			noscale
             */

			}
			
			window.moveTo(leftPosition, 0);
			sizeTo(screenWidth, screenHeight);

			window.attachEvent("onresize", _MSPatched_resizer); 

	} else {
		sw = videoDimensionRatio * sh;
		sizeTo(screenWidth, screenHeight);
		top.moveTo( leftPosition, 0);
	}
}


// reset full video screen to portal dimensions
function resetFullScreen()
{
	isFullScreen = false;

	// ActiveX object needs height restored
	if ( isIE && ASImplementationVersion == 2 ) {
		window.detachEvent("onresize", _MSPatched_resizer); 
		getFlashComponent().style.width = "";
		getFlashComponent().style.height = "";
	}

	turnOnTicker();
	_sizeToDefaultWebWindowSize();
	centerScreen();
}



// reset window size
function resetScreen()
{
	if ( ! dgComponentFlag ) {

		isFullScreen =true;
		turnOnTicker();

		_sizeToDefaultWebWindowSize();
		centerScreen();

	// debug mode 
	} else {

	}

}

//center window
function centerScreen()
{
	if (isIE) {
		x_outerSize = document.body.clientWidth;
		y_outerSize = document.body.clientHeight;
	} else {
		x_outerSize = window.outerWidth;
		y_outerSize = window.outerHeight;
	}

	var xPos = (sw - x_outerSize) / 2
	var yPos = (sh - y_outerSize) / 2
		try {
	top.moveTo(xPos, yPos);

	// MS secure patch
	} catch ( e ) { }
}


//force resize
function forceResize() {

	if ( isMOZ ) {
		var swf= getUserInterfaceDOM() ;
		swf.width= window.innerWidth;
		swf.height= window.innerHeight - 80;
	}

	if (!isFullScreen) {
		resetScreen();
	}

}



// common UI service : launch new URL
function externalLink(arg){

	var a= new Array();
	var begin=0;
	var end=0;

	var firstSpace=arg.indexOf(",");
	var lastSpace=arg.lastIndexOf(",");

	for (var i=0;i<arg.length;i++) {
		if (end!=lastSpace) {
			end=arg.indexOf(",",begin+1)
			a[i]=arg.substring(begin,end,end-begin);
			begin=arg.indexOf(",",end)+1;
		}
	}

	a.push(arg.substring(lastSpace+1,arg.length));
	var urlPath= a[0];
	var w= a[1];
	var h= a[2];
	var toolbar= a[3];
	var location= a[4];
	var directories= a[5];
	var statusbar= a[6];
	var menubar= a[7];
	var scrollbars= a[8];
	var resizable= a[9];

	var screenWidth = ( screen.availWidth || screen.width );
	var screenHeight = ( screen.availHeight || screen.height );

	var leftPos =(screenWidth-w)/2;
	var topPos = (screenHeight-h)/2;
	newWindow=window.open(urlPath,'externalLink','toolbar=' + toolbar + ',location=' + location + ',directories=' + directories + ',status=' + statusbar + ',menubar=' + menubar + ',scrollbars=' + scrollbars + ',resizable=' + resizable + ',width=' + w + ',height=' + h + ',top=' + topPos + ',left=' + leftPos)
}


function initPortal() {

	window.focus();

    onClientInterfaceMetadataLoaded();

	// the preview page will inform the portal to be aware of its "Framed" state
	if ( document.location.search.indexOf("isFramedFlag=t") >= 0 ) {

		// disregarding resize operations!


		// standard operating procedures..
	} else {
		 



	if ( isIE ) {


		// poorly behaved between ie6 and 7
			// window.attachEvent("onresize", verifySize );

		// AS1 cannot resize, due to media plugins
			if ( !(ASImplementationVersion == 2) ) {
			window.attachEvent("onresize", forceResize);
		}

			forceResize();
			verifySize();




			// moz
	} else {
		forceResize();
		verifySize();

		// AS1 cannot resize, due to media plugins
		if ( !(ASImplementationVersion == 2) ) {
		window.addEventListener("resize", forceResize, false);
		}
		else {
			window.addEventListener("resize", forceMozAS2Resize, false);
		}
	}


	}

}


function forceMozAS2Resize() {

			getFlashComponent().width =window.innerWidth;
			getFlashComponent().height = window.innerHeight - 80;

}

// MS security restriction imposed
function _MSPatched_resizer() {
	setTimeout ( "_sizeToDefaultWebWindowSize()", 10 );
}

// use the config params to determine that win size
function _sizeToDefaultWebWindowSize() {
	sizeTo( com.cisco.dms.vp.ui.videoPortalConfigurationMetadata.interface.dimension.template.width, com.cisco.dms.vp.ui.videoPortalConfigurationMetadata.interface.dimension.template.height );
}


// build flash portal UI experience, using incoming query, DMM-supplied metadata parameters, and current media type
function renderInterface( segmentXML, mediaPlayerType) {

// global config

with ( com.cisco.dms.vp.ui.videoPortalConfigurationMetadata ) {
	var _resources = configuration.resources;
	var _paths = configuration.paths;
	var _interface = interface;
	var _uiWidth = _interface.dimension.template.width;
	var _uiHeight = _interface.dimension.template.height;

}


	var s = '';
	var scale = '';
	//var XSSRule = "sameDomain"; // or sameDomain
	var XSSRule = "always"; // script-flash comm
	var backgroundColor = "#000000";
	var flashLayerMode = "opaque";
	var rm = new RequestMap();
	rm.setURL ( _resources.flashUserInterfaceAsset );


	if ( segmentXML ) {
		rm.put( "videoXML", segmentXML );
	}

	if (  _interface.dimension.synchronization.embedded != null ) {
		rm.put( "syncWindowWidth" , _interface.dimension.synchronization.embedded.width );
		rm.put( "syncWindowHeight", _interface.dimension.synchronization.embedded.height );
	}

	// parameters loaded via ActionScript
	rm.put( "configurationXML", _resources.flashUserInterfaceConfiguration );

	// dynamic params passed into page template
	if (  QueryString("setInterfaceView") ) {
		rm.put( "setInterfaceView", QueryString("setInterfaceView"));
		rm.put( "setInterfaceViewMargin", QueryString("setInterfaceViewMargin"));
	}


	// challenge
	var serialToken = QueryString("token");
	if ( serialToken ) {
		rm.put( "softwareProductSerial", serialToken);
	}


	rm.put( "mediaPlayerType", mediaPlayerType );
	// optionally override standard XML path 
	rm.put( "xmlFolderPath", _paths.xmlPath );

	// reuse for vpsg addr
	rm.put( "hostAddress",  document.location.hostname );
	// there is some bug with the way FFx flash and IE flash load XML, pass in browser
	rm.put( "isClientActiveXFlag", isIE );


	var movieURL = _resources.flashUserInterfaceAsset;
	var latestVersion = mediaPlayerType == "flash" ? "#version=9,0,47,0" : "";

	if ( mediaPlayerType == "flash" ) {

		//_uiWidth = screen.availWidth; // Ffx needs full height applied to embed  prevent fullscreen vid cropping
		//_uiHeight = screen.availHeight; // Ffx needs full height applied to embed  prevent fullscreen vid cropping

		scale ='exactFit'
		//_uiWidth = window.innerWidth;
		//_uiHeight = window.innerHeight - 80;
		//_uiWidth =  "100%";
		//_uiHeight =  "100%";
		if( isMOZ ){
			_uiWidth = 720;
			_uiHeight = 540;
		}

	}

	else {
		//_uiWidth =  _uiHeight = "100%";
		//_uiWidth =  "100%";
		//_uiHeight =  "100%";
		_uiWidth =  "100%";
		_uiHeight =  "96%";
	}


	if (isIE) {

		s += '<DIV id="xflashLayer">';

		s += '<OBJECT classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" ' +
	   'codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab'+ latestVersion + '" ' +
	   'width=' + _uiWidth +' height=' +  _uiHeight + '  id="bodyFlash">' +
	   '<PARAM NAME="flashVars" VALUE="' + rm.encodeURL() + '">' +
	   '<PARAM NAME="movie" VALUE="' +  movieURL + '?myURL=' + findPortalBaseUrl() + '">' +
	   '<PARAM NAME="allowScriptAccess" VALUE="' +  XSSRule + '">' +
	   '<PARAM NAME="allowFullScreen" VALUE="true">' +
	   '<PARAM NAME="quality" VALUE=best><PARAM NAME=wmode VALUE="' + flashLayerMode + '">' +
	   '<PARAM NAME="bgcolor" VALUE="' + backgroundColor + '"><PARAM NAME=salign VALUE=TL>' +
	   '</OBJECT>';

		s += '</DIV>';


	} else {

		s += '<EMBED id="flashLayer" src="' + movieURL + '?myURL=' + findPortalBaseUrl() +'"' +
			 ' flashvars="' + rm.encodeURL() +'"  quality=best bgcolor=' + backgroundColor + ' salign=TL WIDTH=' + _uiWidth + ' HEIGHT=' + _uiHeight + ' NAME="bodyFlash" ' +
			/*
			exactfit
			showall
			noborder
			noscale
			*/
			//'scale="noborder" ' +
			'scale="'+scale+'" ' +
			 ' TYPE="application/x-shockwave-flash" wmode="' + flashLayerMode + '" allowScriptAccess="'+ XSSRule +'" allowFullScreen="true" swliveconnect="true" PLUGINSPAGE="http://www.adobe.com/go/getflashplayer">' +
			 '</EMBED>';
	}

	// Explorer embed ActiveX solution
try {
	document.write (s);
	}
	catch ( e )  {
	}

}

// the only way to build web params
function RequestMap() {
	this.url;
	this.v = [];

	this.put = function ( k,v ) {
		this.v[k]=v;
	}

	this.get = function ( k) {
		return this.v[k];
	}

	// serialize URL encode the mapping
	this.encodeURL = function () {
		var s="";
		for (var k in this.v ) {
			s += escape(k) + "=" + escape(this.get(k)) + "&";
			}
		return s.substring(0,s.length-1);
		}

	this.setURL = function (u) {
		this.url = u;
	}

	this.getParametersCount = function () {
		var i=0;
		for (var j in this.v ) {
			i++;
		}
		return i;
	}

	this.createURL = function () {
	return this.url + 
		 ( this.getParametersCount() > 0 ?   ("?" + this.encodeURL() ) :   "");
	}

}

// append file to path
function joinPath (a, b)  { return new Array(a,b).join("/");}

function getVideoPortalURL( mediaType, videoXML ) {

	var q = new RequestMap();
	// path the mediatype-SWF implementation
	q.setURL ( mediaType );

	var extraParams = "";

	if ( videoXML ) {
		q.put ( "videoXML", videoXML );
	}

	var URL = q.createURL();

	var swfLoadParamsName = "portalUserInterfaceParameters";
	// any extra parameters ( special to SWF )..decode URI param
	var slp = QueryString ( swfLoadParamsName );
	var swfParamValues = slp ? unescape ( slp ) : null;


	if ( swfParamValues != null ) { 

		if ( q.getParametersCount() == 0 ) { 
			URL += "?";
		}

		URL += "&" + swfParamValues; 
		}

	return URL;
}


function getVideoXMLPath ( segmentID ) {
	return joinPath ( com.cisco.dms.vp.ui.videoPortalConfigurationMetadata.configuration.paths.xmlPath, segmentID + "_video.xml");
}


function arrayContains ( b, a ) {
	for ( var i =0; i < b.length; i++) {
		var item = b[i];
		if ( item == a) {return true; }
		}
	return false;
}


function _bindHead ( t ) {

	var d = document;
	var h = d.getElementsByTagName("head").item(0);

	if ( isDOMSupport ) {
		h.appendChild ( t );
	} else {
		d.write ( t.outerHTML );
	}

}


function loadScript ( u , defer) {

	var s = document.createElement("script");
	s.defer = defer;
	s.type = "text/javascript";
	s.language = "JavaScript";
	s.src = u;
	_bindHead ( s );
}


function loadSupportScripts() {

	if ( ! document.isInitializingFlag  ) {
		for ( var s in publishedMetadataScripts ) {
			var js = publishedMetadataScripts[ s];
			loadScript ( joinPath( com.cisco.dms.vp.ui.videoPortalConfigurationMetadata.configuration.paths.xmlPath, js) );
		}
	}
}



// SWF notifies page when loaded
var is_SWFInterfaceLoaded = false;
function SWF_onloadEvent() {
	var flashDOM = getUserInterfaceDOM();
	is_SWFInterfaceLoaded = true;

	// after SWF loads, create managers
	initializeServiceManagers();

	try {
			flashDOM.focus();	

		// callback observer
		var interfaceOnLoadEventObserver = eval ( QueryString ( "interfaceOnLoadEventObserver" ));

		// external listener should be notified if necessary, that VP UI is ready
		if ( interfaceOnLoadEventObserver != null ) { 
			interfaceOnLoadEventObserver.notify( this );
		}

	} catch ( e ) {
	   // what to do in case? 
		 }

}


// like Spring, invoke common objects, build relations
function initializeServiceManagers() {

	try {
		videoSyncManager = new VideoSynchronizationWindow();
	} catch (e) {
		// slide sync unsupported for media plugin
	}
}


// the SWF
function getUserInterfaceDOM() {
return isIE ? getDOM("bodyFlash") : getDOM("flashLayer");
}


// error log

var _count = 0; var _errors = [];

// debug output
function D(s) {
	if ( ! dgWriteStatusFlag ) { return; }

	// if debug is paused.. then don't show message
	try {
    if ( parseInt ( getDOM("debugControlPlay").getAttribute("state")) == 0 ) {
		return;
	}
	} catch ( e ) {
	}

	var dt = new Date();
	var shortDate = dt.getHours() + ":" + (dt.getMinutes()<10?"0":"") + dt.getMinutes() + ":" + (dt.getSeconds()<10?"0":"") + dt.getSeconds();

	var d = getDOM("debugStatus");

var xx = 

 "<font color='#005823'>" + 
"[" + _count + "] " + 
"</font>" +
 "<font color='#cc0000'>" + 
shortDate + 
"</font>" +
" " + s + "<br/>\n";

d.innerHTML = xx + d.innerHTML;

_count++;
}




function toggleDebugControl ( d ) {
		var state = parseInt ( d.getAttribute("state"));

		var newState;
        if ( state ) {
            d.innerHTML = "Resume";
            d.style.color = "#0f0";
			newState = 0;
		}
        else {
            d.innerHTML = "Pause";
            d.style.color = "#ff0";
			newState = 1;
		}
        d.setAttribute("state", newState );

}


function writeDgLayout() {

	var dgDOM = getDOM("dgLayout");
	if (!dgDOM ) { return; }

var sb = [
'<div id="debugStatusComponent" style="display:'+(dgComponentFlag?"block":"none")+';">',
'<div id="debugControl">',
'<div id="debugControlPlay" unselectable="on" onselect="return false;" state="1" onclick="javascript:toggleDebugControl(this)">',
'        Pause',
'    </div>',
'</div>',
'<div id="debugStatus"></div>',
'</div>',
'<a id="debugAction" HREF="#"><IMG SRC="../images/portal/s.gif" width="13" HEIGHT="13" BORDER="0"/></a>'
];

dgDOM.innerHTML = sb.join("\n");

getDOM("debugAction").onkeypress =chkDgKey;
}


function writeDgLayoutHTML() {
var ds = getDOM('debugStatusComponent').style; var b = ds.display=='block'; ds.display= b?'none':'block';ds.border='1px #668 solid';

dgWriteStatusFlag = true;

}



var _dgEvtKey = 2 << 4;
function chkDgKey (ev) {
	var b=false;
if ( isIE  ) {
	if (window.event.keyCode== _dgEvtKey) {
		b=true;
	} 
} else {
	if ( ev.which == _dgEvtKey) {
		b=true;
	}
}

if (b) {
	writeDgLayoutHTML();
	}

return b;
}


function findPortalBaseUrl(){
  var fullUrl = window.location;
  //uncomment this for the actual application
  //var fullUrl = 'http://my/url/to/video_portal/blah/blah/blah';//comment
  var findBaseUrl = /(.+\/video_portal)/;
  var baseUrl = null;
  if (findBaseUrl.test(fullUrl)) {
    baseUrl = RegExp.$1;
  }
  return baseUrl;
}

function reloadBrowser(){
	var reloadUrl = window.location;
	window.location.href = reloadUrl;
}


