var _appPath,_epgVersion,_playerVersion,_playerServicePath,_playerPath,_detachedPlayer;
var _defaultPlayerWidth,_defaultPlayerHeight,_defaultPlayerWidth_wide,_defaultPlayerHeight_wide;

/*** UTILITIES ***/

var MSIEversion=0;
if (navigator.appVersion.indexOf("MSIE")!=-1){
    var temp=navigator.appVersion.split("MSIE");
    MSIEversion=parseFloat(temp[1]);
}

/* addon array for IE5 */
if(typeof Array.prototype.push != "function"){
    Array.prototype.push = ArrayPush;
    function ArrayPush(value){
        this[this.length] = value;
    }
}


function addLoadEvent(func) {
    
	var oldhandlers = window.onload;
	if (typeof window.onload != 'function') {
		window.onload = func;
	} else {
		window.onload = function() {
			oldhandlers();
			func();
		}
	}
}

function addBeforeUnloadEvent(func) {
	var oldhandlers = window.onload;
	if (typeof window.onbeforeunload != 'function') {
		window.onbeforeunload = func;
	} else {
		window.onbeforeunload = function() {
			oldhandlers();
			func();
		}
	}
}

/* use addEvent(object, eventType, function) to add an event to a given element */
/* From http://ejohn.org/projects/flexible-javascript-events/ */

function addEvent( obj, type, fn ) {
    //Event.observe(obj, type, fn, true);
    //return;
	if ( obj.attachEvent ) {
		obj['e'+type+fn] = fn;
		obj[type+fn] = function(){obj['e'+type+fn]( window.event );}
		obj.attachEvent( 'on'+type, obj[type+fn] );
	} else
		obj.addEventListener( type, fn, false );
}

/* use removeEvent(object, eventType, function) to remove an existing event from a given element */
/* From http://ejohn.org/projects/flexible-javascript-events/ */

function removeEvent( obj, type, fn ) {
    //Event.stopObserving(obj, type, fn, true);
    //return;
	if ( obj.detachEvent ) {
		obj.detachEvent( 'on'+type, obj[type+fn] );
		obj[type+fn] = null;
	} else
		obj.removeEventListener( type, fn, false );
}


/*** NAVIGATION DROPDOWNS - NOT CURRENTLY USED ***/
/* Suckerfish dropdowns from A List Apart http://alistapart.com/articles/dropdowns/ */
startList = function() {
	if (document.all || document.getElementById) {
		navRoot = document.getElementById("nav-main-list");
		for (i=0; i<navRoot.childNodes.length; i++) {
			node = navRoot.childNodes[i];
			if (node.nodeName=="LI") {
				node.onmouseover=function() {
					this.className+=" over";
  				}
				node.onmouseout=function() {
  					this.className=this.className.replace(" over", "");
  					
   				}
   			}
  		}
 	}
}

function Logger(){}

Logger.prototype.log = function(message){

	if (this.active)  {
		if (this.useConsole)
			console.log(message);
		else 
		{
			//this.messageContainer.innerHTML += "<br />"+message;
			//alert(message);
		}
	}

	
}

Logger.prototype.error = function(message,error){
	
	if (this.active) {
		if (this.useConsole)
			console.log("***ERROR*** %s<br />%s", message, error.message);
		else
        {
            //this.messageContainer.innerHTML += "<br /><b>ERROR:</b> " + message + "<br />" + error.message + ", " + error.lineNumber + ", " + error.constructor + ", " + error.description + ", " + error.fileName + ", " + error.lineNumber + ", " + error.name + ", " + error.number + ", " + error.prototype + ", " + error.stack;
            //alert(message, error);
        }
	}
	
}

function initLogger(){

	logger = new Logger();
	logger.useConsole = true;
	logger.active = (document.location.href.indexOf('logger=on') > -1);
	if (typeof(console) == "undefined") {
	    logger.useConsole = false;
	    
	    // Disabled in non-mozilla browzers
	    /*	    
	    logger.messageContainer = document.createElement('div');
	    if ($('browser'))
	    {   
		    $('browser').parentNode.appendChild(logger.messageContainer);
	    }
	    */
	}
	
}

addLoadEvent(initLogger);

function initPlayer(contentId, height, isWidescreen){

    //JDrawEmbeddedPlayer(contentId, width, height, false, "flash-inner-container");
        
    JEmbedPlayer(contentId, height, isWidescreen, false, "#000000", "flash-inner-container","avennPlayer",true);

	$("avennPlayer").onfocus = function() {
	    var prefix = avenn.ui.documentTitlePrefix;
        if (prefix != null) {
            document.title = prefix + " - " + $("currently-playing-info").innerHTML.replace(/\n/g," ").replace(/\t/g,"");
        }
	}	    
}

var jPlayerCount = 0;

/*function JDrawEmbeddedPlayer(contentId, width, height, useShadow, elementId, playerId) {
	
	if (!playerId) {
		playerId = "avennPlayer";
		if (jPlayerCount > 0) // Use ID to allow for multiple players on the one page.
			playerId += jPlayerCount;
	}
	
    if (!elementId ) { // Create wrapper element if not specified.
		elementId = "jPlayerTag_" + jPlayerCount++; // Increment ID to allow for multiple players on the one page.
		document.write('<div id="' + elementId + '"></div>');
	}
	
	var so = new SWFObject(_playerPath, playerId, width, height, "9.0.28", "#000000");
	so.addVariable("videoContentId", contentId);
	so.addVariable("domain1", _playerServicePath);
	if (useShadow) {
	    so.addVariable("margin", true);
	 }
	so.addParam("allowFullScreen", "true");
	so.addParam("allowScriptAccess", "always");
	so.useExpressInstall(_playerPath.toLowerCase().replace(/player.swf/,"") + 'playerProductInstall.swf');
	so.write(elementId);
	
	for (var i=0; i < document.forms.length; i++) { // Fix for External Interface / form bug with Flash Player
		if (document.forms[i][playerId]) {
			window[playerId] = document.forms[i][playerId];
			break;
		}
	}
}*/

 function initPopup() {
    if(window.parent != self){
        redirect404();
    } 
    else {
        var params = {}
        var url = document.location.href.split('?');
        if (url.length > 1) {
            var paramArr = url[1].split('&');
            
            for (var i = 0; i < paramArr.length; i++){
                var temp = paramArr[i].split('=');
                params[temp[0]] = temp[1];
            }
            
            if (!params.contentId || params.contentId == "") {
                redirect404();
            }
            else {
                /* GET BEST FIT ASPECT RATIO
                
                var isWidescreen = false;
                if (params.isWidescreen == "true")
                {
                    isWidescreen = true;
                }
                var originalWidth = document.body.offsetWidth;
                var originalHeight = document.body.offsetHeight;
                var width,height;
                width = (isWidescreen === true) ? originalHeight*(16/9) : originalHeight*(4/3);
                if (width > originalWidth) {
                    width = originalWidth;
                    height = isWidescreen ? originalWidth/(16/9) : originalWidth/(4/3);
                }
                else {
                    height = originalHeight;
                } 
                */
                
                var isWidescreen = (document.body.offsetWidth / document.body.offsetHeight > 1.5);
                JEmbedPlayer(params.contentId, "100%", isWidescreen, false, "#000000", "flash-inner-container");
                //JDrawEmbeddedPlayer(params.contentId, "100%", "100%",false,'flash-inner-container');   
            }
        }
        else{
            redirect404();
        }
    }
}    
            
function redirect404() {
    window.location.href = _appPath + "/PageNotFound.aspx";
}    


function launchPopup(url,width,height,name){
    if (width == null) width = 790;
    if (height == null) height = 570;
    if (name == null) name = 'avenn';
    var newwin = window.open(url,name,'width=' + width + ',height=' + height + ',scrollbars=yes,status=no,resizable=yes');
    if (e.preventDefault) e.preventDefault();
    e.returnValue = false;
    newwin.focus();
    return false;
}

function launchNewWindow(url){
    var newwin = window.open(url,'avenn',',scrollbars=yes,status=yes, location=yes,toolbar=yes,resizable=yes,menubar=yes');
    if (e.preventDefault) e.preventDefault();
    e.returnValue = false;
    newwin.focus();
    return false;
}

/* initPageLayout is run on any event which changes page layout - showing/hiding the player, navigating to a new page & resizing the browser */

function showMessageBox(html)
{
	$('messageBoxHTML').innerHTML = html;
	
	var offsetX = (window.pageXOffset
                || document.documentElement.scrollLeft
                || document.body.scrollLeft
                || 0);
	var offsetY = (window.pageYOffset
                || document.documentElement.scrollTop
                || document.body.scrollTop
                || 0);
    
    var winX = document.body.clientWidth || window.innerWidth;
    var winY = document.body.clientHeight || window.innerHeight;
    
    $('messageBox').style.top = (((winY / 2) - 75) + offsetY) + "px";
    $('messageBox').style.left = (((winX / 2) - 150) + offsetX) + "px";
        
    $('messageBox').style.display = 'block';
    $('messageBoxOK').focus();
    
}

function hideMessageBox()
{
	$('messageBox').style.display = 'none';
}

// CSS Browser Selector   v0.2.5
// Documentation:         http://rafael.adm.br/css_browser_selector
// License:               http://creativecommons.org/licenses/by/2.5/
// Author:                Rafael Lima (http://rafael.adm.br)
// Contributors:          http://rafael.adm.br/css_browser_selector#contributors
var css_browser_selector = function() {
	var 
		ua=navigator.userAgent.toLowerCase(),
		is=function(t){ return ua.indexOf(t) != -1; },
		h=document.getElementsByTagName('html')[0],
		b=(!(/opera|webtv/i.test(ua))&&/msie (\d)/.test(ua))?('ie ie'+RegExp.$1):is('gecko/')? 'gecko':is('opera/9')?'opera opera9':/opera (\d)/.test(ua)?'opera opera'+RegExp.$1:is('konqueror')?'konqueror':is('applewebkit/')?'webkit safari':is('mozilla/')?'gecko':'',
		os=(is('x11')||is('linux'))?' linux':is('mac')?' mac':is('win')?' win':'';
	var c=b+os+' js';
	h.className += h.className?' '+c:c;
}();


var viewport = {
  getWinWidth: function (scrolling) {
    if (typeof(scrolling)!="boolean")scrolling=true;
    var scrollWidth = scrolling?18:0;
    this.width = 0;
    if (window.innerWidth) this.width = window.innerWidth - scrollWidth;
    else if (document.documentElement && document.documentElement.clientWidth) 
  		this.width = document.documentElement.clientWidth;
    else if (document.body && document.body.clientWidth) 
  		this.width = document.body.clientWidth;
  },
  
  getWinHeight: function (scrolling) {
    if (typeof(scrolling)!="boolean")scrolling=true;
    var scrollWidth = scrolling?18:0;
    this.height = 0;
    if (window.innerHeight) this.height = window.innerHeight - scrollWidth;
  	else if (document.documentElement && document.documentElement.clientHeight) 
  		this.height = document.documentElement.clientHeight;
  	else if (document.body && document.body.clientHeight) 
  		this.height = document.body.clientHeight;
  },
  
  getScrollX: function () {
    this.scrollX = 0;
  	if (typeof window.pageXOffset == "number") this.scrollX = window.pageXOffset;
  	else if (document.documentElement && document.documentElement.scrollLeft)
  		this.scrollX = document.documentElement.scrollLeft;
  	else if (document.body && document.body.scrollLeft) 
  		this.scrollX = document.body.scrollLeft; 
  	else if (window.scrollX) this.scrollX = window.scrollX;
  },
  
  getScrollY: function () {
    this.scrollY = 0;    
    if (typeof window.pageYOffset == "number") this.scrollY = window.pageYOffset;
    else if (document.documentElement && document.documentElement.scrollTop)
  		this.scrollY = document.documentElement.scrollTop;
  	else if (document.body && document.body.scrollTop) 
  		this.scrollY = document.body.scrollTop; 
  	else if (window.scrollY) this.scrollY = window.scrollY;
  },
  
  getAll: function () {
    this.getWinWidth(); this.getWinHeight();
    this.getScrollX();  this.getScrollY();
  }
  
}

function findParentUL(element) {
    while(element.parentNode) {
        element = element.parentNode;
        if (element.tagName.toUpperCase() == "UL") {
            return element;
        }
    }
    return null;
}
