function Verbose(msg)
{
	// Placeholder
}

// ************************************************************************************************
// *** Utility class to read and write cookies
// ************************************************************************************************

var cookieValue;

// This object manages cookies
function CookieManager(cookieName, expirationDate, domain) {
	// ************************************************************************************************
	// *** Interface
	// ************************************************************************************************	

	// Fields
	// ******
	this.cookieName = cookieName;
	this.expirationDate = expirationDate;
	this.domain = domain;
	
	// Methods
	// *******
	this.getValue = cm_getValue;
	this.setValue = cm_setValue;
	
	// ************************************************************************************************
	// *** Methods
	// ************************************************************************************************	
	
	// Return a cookie value (null if key is not found in the cookie)
	function cm_getValue(key) {
		var i;
		var result;

		result = document.cookie.match(key + '=([^;&]*)'); // value will be in the position 1 (first group)

		return (result != null) ? result[1] : null;
	}
	
	// Set a cookie value (create the key/value pair if it is not found in the cookie)
	function cm_setValue(key, val)
	{
		var result = '';
		var expiration = this.expirationDate == null ? '' : 'expires=' + this.expirationDate.toGMTString() + ';';

		// Read all cookie string (the cookie value will be at array postition 1)
		result = document.cookie.match(this.cookieName + '=([^;]*)');
		if(result == null)
			result = "";
		else
			result = result[1];			

		// if key already exists in the cookie, replace its value
		if(result.indexOf(key) > -1)
			result = result.replace(new RegExp(key + '=[^&]*'), key + '=' + val);
		else // If key does not exist int the cookie, put it
			result += ((result != '') ? '&' : '') + key + '=' + val;
			
		// write the cookie
		document.cookie = this.cookieName + '=' + result + ';domain=' + this.domain + ';path=/;' + expiration;
	}
	
	
}	

// Set a cookie value (create the key/value pair if it is not found in the cookie)
function CookieSave(name, key, val, domain, expiration, method)
{

	// Set for method in Web.Config	
	if ( method == null ) 
		method = ckModeWrite;
	
	expirationToString = expiration.toDateString();
			
	if ( method == 1 ) {
		new CookieManager(name, expiration, domain).setValue(key, val);
	} 
	else if ( method == 2 ) 
	{
		cookieService(name, key, val, domain, null, expirationToString, false);
	} 
	else
	{	
		
		var iframeCookie = document.getElementById('dvIFrameCookie');
		if(!iframeCookie) return;
				
		var cHtml = '<form name="formCookie" target="cookieFrame" action="Cookies.aspx">';
		cHtml += '<input type=hidden name="name" value="' + name + '" />';
		cHtml += '<input type=hidden name="writekey" value="' + key + '" />';
		cHtml += '<input type=hidden name="writevalue" value="' + val + '" />';
		cHtml += '<input type=hidden name="writedomain" value="' + domain + '" />';
		cHtml += '<input type=hidden name="writeexpiration" value="' + expirationToString + '" />';
		cHtml += '<input type=hidden name="method" value="SAVE"/>';
		cHtml += '</form>';

		iframeCookie.innerHTML = cHtml;
		
		document.formCookie.submit();
	}
	
}

function CookieRestore(name, key)
{	
	cookieValue = new CookieManager(name, "", "").getValue(key);	
	return cookieValue;
}

// D'ont use this function 
// used in function from AjaxManager
function AjaxCookieSave()
{
	if(this.httpRequest.status == 200)
	{
		cookieValue = this.httpRequest.responseText;
	}
}
/******************************************************************************
* Global state control 
*******************************************************************************/
var channelID;
var Highlighs;
var pendenceList = new Array();
var backWide;
var total;
var firstSearch = true;
var drawLiveEvents = false;

/****************************************************************************
* Cookies
****************************************************************************/
var expirationDate = new Date((new Date()).getTime() + cookieParamMonth*24*60*60*1000); // 30 Days

var cookieManager = new CookieManager("mediacenter_session", null, ckDomain);
var cookieManagerSettings = new CookieManager("mediacenter_settings", expirationDate, ckDomain);
var cookieSession = "mediacenter_session";
var cookieSettings = "mediacenter_settings";
/****************************************************************************
* Related Box
****************************************************************************/
function showBox(id)
{
	var box = document.getElementById("videoBox" + id);
	var header = document.getElementById("videoBoxHeader" + id);
	box.style.display = "";
	header.style.display = "none";
}
function hideBox(id)
{
	var box = document.getElementById("videoBox" + id);
	var header = document.getElementById("videoBoxHeader" + id);
	box.style.display = "none";
	header.style.display = "";
}
/**************************************************************************
* Browsing functions
**************************************************************************/
function UpdateState()
{
	//alert(channelID);
}

function FormatTime(timeString, printHour)
{
	var hour = parseInt(timeString / 3600).toString();
	timeString = timeString % 3600;
	var min = parseInt(timeString / 60).toString();
	timeString = timeString % 60;
	var sec = parseInt(timeString).toString();
	
	if(hour < 10)
	{
		hour = '0' + hour;
	}
	if(min < 10)
	{
		min = '0' + min;
	}
	if(sec < 10)
	{
		sec = '0' + sec;
	}
	
	if(printHour)
	{
		return hour + ":" + min + ":" + sec;
	}
	else
	{
		if(parseInt(hour) > 0)
		{
			return hour + ":" + min + ":" + sec;
		}
		else
		{
			return min + ":" + sec;
		}
	}
}

/****************************************************************************
* Comments
****************************************************************************/
function SaveComment(currentContent)
{
	if(logged)
	{
		var commentInput = document.getElementById("txtCommentBody");
		if(commentInput)
		{
			// Checks if the search is within the min/max specified
			var cleanInput = InputCleanup(commentInput.value);
		
			if(inputMin>0 && cleanInput.length<searchMin)
			{
				alert(Translate("INVALID_INPUT"));
				return;
			}

			if(inputMax>0 && cleanInput.length>inputMax)
			{
				alert(Translate("INVALID_INPUT"));
				return;
			}

			var currentContent = 0;
			var currentMedia = playerTerra.getCurrentMedia();
			if(currentMedia) currentContent = currentMedia.id;

			ajaxManager.Add("/templates/Ajax/genericAjax.aspx?AjaxSource=TerraMediaCenter.CommentManager&page=Ajax&p1=SaveComment&p2=" + currentContent + "," + escape(cleanInput), ParseSaveComment, CreateLoading, DestroyLoading, DestroyLoading)
		}
	}
	else
	{
		RunLogged(SaveComment);
	}
}
function ParseSaveComment()
{
	if(this.httpRequest.status == 200)
	{
		alert(this.httpRequest.responseText);
		ShowVideoDetails();
		//playlistTerra.drawTab(0);
	}
}

/****************************************************************************
* Send Video
****************************************************************************/
SendVideofromPopup = false;
function SendVideo(fromPopup, contentId)
{
	SendVideofromPopup = fromPopup;
	var nameInput = document.getElementById("your_name");
	var emailInput = document.getElementById("your_email");
	var fiendInput = document.getElementById("friend_name");
	var fiendMailInput = document.getElementById("friend_email");
	var commentInput = document.getElementById("comment");

	if(nameInput && emailInput && fiendInput && fiendMailInput && commentInput)
	{
		var currentContent = 0;
		
		if(!fromPopup)
		{
			var currentMedia = playerTerra.getCurrentMedia();
			if(currentMedia) currentContent = currentMedia.id;
		}else{
			currentContent = contentId;
		}

		if(currentContent>0)
		{
			var your_name = nameInput.value;
			var your_email = emailInput.value;
			var friend_name = fiendInput.value;
			var friend_email = fiendMailInput.value;
			var comment = commentInput.value;
			
			// Fix to isseu where content after commas was getting "lost" in the post
			comment = new String(comment);
			comment = comment.replace(/,/g,'#comma#');
			comment = escape(comment);
			
			ajaxManager.Add('/templates/Ajax/genericAjax.aspx?AjaxSource=TerraMediaCenter.UserManager&page=ASP.genericAjax_aspx&p1=SendVideoToFriend&p2=' + currentContent + ','+your_name+','+your_email+','+friend_name+','+friend_email+','+comment,ParseSendVideo,null,null,null,null,null); return false
		}
	}
}

function ParseSendVideo()
{
	if(this.httpRequest.status == 200)
	{
		alert(this.httpRequest.responseText);
		/*if(!SendVideofromPopup)
		{
			playlistTerra.drawTab(0);
		}*/
		ShowVideoDetails();
	}
}

/****************************************************************************
* Video Area Rendering
****************************************************************************/
function ShowVideoDetails()
{
	if (drawLiveEvents == true)
	{
		getAjaxContentNoCache('playlistHolder','/templates/Ajax/genericAjax.aspx?AjaxSource=TerraMediaCenter.PlayerBoxLiveEventsView&page=genericAjax_aspx&p1=' + currentContent + '&p2=' + currentRelatedsFrom + '&p3=true', true, null);
	}
	else
	{
		getAjaxContentNoCache('playlistHolder','/templates/Ajax/genericAjax.aspx?AjaxSource=TerraMediaCenter.PlayerBoxDetailsView&page=genericAjax_aspx&p1=' + currentContent + '&p2=' + currentRelatedsFrom + '&p3=false', true, null);
	}
}
function ShowVideoRelateds()
{
	if (drawLiveEvents == true)
	{
		getAjaxContentNoCache('playlistHolder','/templates/Ajax/genericAjax.aspx?AjaxSource=TerraMediaCenter.PlayerBoxLiveEventsView&page=genericAjax_aspx&p1=' + currentContent + '&p2=' + currentRelatedsFrom + '&p3=true', true, null);
	}
	else
	{
		getAjaxContentNoCache('playlistHolder','/templates/Ajax/genericAjax.aspx?AjaxSource=TerraMediaCenter.PlayerBoxDetailsView&page=genericAjax_aspx&p1=' + currentContent + '&p2=' + currentRelatedsFrom + '&p3=false', true, null);
	}
	var objTab = document.getElementById('playlistTab1');
	changeTabs(objTab,1);
}

/***************************************************************************
* Access denied video
***************************************************************************/
function AccessDeniedVideo(video)
{
// TODO: Fix this, originalID does not exist anymore
	// Always use originalid for error messages
	ReloadMyServicesBox(video.originalid);
	//LoadMyServicesAjax("ajax", video.originalid);
}

function ReloadMyServicesBox(contentID)
{
	ajaxManager.Add("/templates/Ajax/genericAjax.aspx?AjaxSource=TerraMediaCenter.MyServicesBoxInternalView&page=Ajax&p1=" + contentID, ParseMyServicesBox, CreateLoading, DestroyLoading, DestroyLoading);	
}
function ParseMyServicesBox()
{
	var msBox = document.getElementById("myServicesBox");

	if(this.httpRequest.status == 200 && msBox)
	{
		msBox.innerHTML = this.httpRequest.responseText;
	}
	ShowMyServicesBox();
}
/****************************************************/
/* Function for locating the current mouse position */
/* Must receive an event to work in Mozilla         */
/****************************************************/
var currentMouseX;
var currentMouseY;
function GetMousePosition(e)
{
	var nn6 = document.getElementById && !document.all;
		
	var clientX = document.all ? event.clientX : e.clientX;
	var clientY = document.all ? event.clientY : e.clientY;

	var scrollLeft = nn6 ? window.pageXOffset : document.documentElement.scrollLeft;
	var scrollTop = nn6 ? window.pageYOffset : document.documentElement.scrollTop;

	currentMouseX = clientX + scrollLeft;
	currentMouseY = clientY + scrollTop;
}

/****************************************************
/* Banner Intermediate Function
/***************************************************/
function getAds(adchannel, adtype, adadvertiser, adaction)
{
	if(adchannel && adtype && adadvertiser && adaction)
	{
		if(adchannel!='' && adtype!='' && adadvertiser!='' && adaction!='')
		{
			getAdvertisment(adchannel, adtype, adadvertiser, adaction);
		}
	}
}

/****************************************************
/* Search box
/***************************************************/
function SearchBoxSubmit()
{
	var searchBox = document.getElementById("buscaCampo");
	
	if(searchBox)
	{
		if(searchBox.value != Translate("SEARCH_FOR_VIDEOS"))
		{
			// Checks if the search is within the min/max specified
			var cleanSearch = SearchCleanup(searchBox.value);
		
			if(searchMin>0 && cleanSearch.length<searchMin)
			{
				alert(Translate("INVALID_SEARCH"));
				return(false);
			}

			if(searchMax>0 && cleanSearch.length>searchMax)
			{
				alert(Translate("INVALID_SEARCH"));
				return(false);
			}
			search_check = true;
			// Sends the user to the search page
			top.location.href = "/templates/searchResult.aspx?keyword=" + escape(cleanSearch);
		}
	}
	return(false);
}
function SearchBoxEnter()
{
	var searchBox = document.getElementById("buscaCampo");
	if(searchBox)
	{
		var searchPhrase = Translate("SEARCH_FOR_VIDEOS");
		if(firstSearch)
		{
			searchBox.value = searchPhrase;
		}else{
			if(searchBox.value.indexOf(searchPhrase) >= 0)
			{
				searchBox.value = searchBox.value.replace(searchPhrase, '');
			}
		}
		firstSearch = false;	
	}
}
function SearchBoxExit()
{
	var searchBox = document.getElementById("buscaCampo");
	if(searchBox)
	{
		if(searchBox.value=='')
		{
			searchBox.value = Translate("SEARCH_FOR_VIDEOS");
		}
	}
}
function SearchBoxKeyDown()
{
	var searchBox = document.getElementById("buscaCampo");
	if(searchBox)
	{
		var searchPhrase = Translate("SEARCH_FOR_VIDEOS");
		if(searchBox.value.indexOf(searchPhrase) >= 0)
		{
			searchBox.value = searchBox.value.replace(searchPhrase, '');
		}
	}
}
/****************************************************
/* Search count
/***************************************************/
function UpdateSearchCount(expression)
{
	var searchCount = document.getElementById('searchCount');
	if(searchCount)
	{
		searchCount.innerHTML = expression;
	}
}

function SeachInPendenceList(obj)
{
	for(i = 0; i < pendenceList.length; i++) if(pendenceList[i].toString() == obj.toString()) return true;
	return false;
}

var dictionary = new Array();
function TranslationItem(_key, _value)
{
	this.key = _key;
	this.value = _value;
}
function Translate(key)
{
	for(var i = 0; i < dictionary.length; i++)
	{
		if(key == dictionary[i].key)
		{
			return dictionary[i].value;
		}
	}
	return "";
}

var menuChannels = new Array();
var menuLinks = new Array();
var menuCurrent = 0;
var menuTimer = -1;
var menuDelay = 350;

// Type
// 1 - Channel
// 2 - Link
function showMenu(id,type)
{
	window.clearTimeout(menuTimer);
	menuTimer = window.setTimeout('showMenuTimer(' + id + ',' + type + ')',menuDelay);
}

function showMenuTimer(id,type)
{
	for(var i=0;i<menuChannels.length;i++)
	{
		var menu = document.getElementById('menu_channel_' + menuChannels[i]);
		var sub = document.getElementById('sub_channel_' + menuChannels[i]);
		
		if(menu)
		{
			if(menuChannels[i]==id && type==1)
			{
				menu.className = 'selected';
			}
			else
			{
				menu.className = '';
			}
		}
		
		if(sub)
		{
			if(menuChannels[i]==id && type==1)
			{
				sub.style.visibility = 'visible';
			}
			else
			{
				sub.style.visibility = 'hidden';
			}
		}
	}
	
	for(var i=0;i<menuLinks.length;i++)
	{
		var menu = document.getElementById('menu_link_' + menuLinks[i]);
		if(menu)
		{
			if(menuLinks[i]==id && type==2)
			{
				menu.className = 'selected';
			}
			else
			{
				menu.className = '';
			}
		}
	}
}

function showMenuDefault()
{
	showMenu(menuCurrent,1);
}

function showHidden(channel)
{
	var listMenu = document.getElementById("sub_channel_" + channel);
	if(listMenu)
	{
		for(var i = 0; i < listMenu.childNodes.length; i++)
		{
			var child = listMenu.childNodes[i];
			if(child.innerHTML)
			{
				if(child.className.indexOf('itemSelected')<0 && child.className.indexOf('switcher')<0)
				{
					// Swaps items with sub_hidden and items without
					var pos = child.className.indexOf('sub_hidden');
					if(pos>=0)
					{
						var regex = new RegExp("\\bsub_hidden\\b","ig")
						child.className = child.className.replace(regex,'');
					}
					else
					{
						child.className = 'sub_hidden ' + child.className;
					}
				}
			}
		}
	}
}

function showBoxSubMenu(id, obj)
{
	var sub = document.getElementById('browsebox_channel_' + id);
	if (sub != null)
	{
		if (sub.className=="none")
		{
			sub.className = "";
			obj.className = "subMenuOn";
		}
		else
		{
			sub.className = "none";
			obj.className = "subMenu";
		}
	}
}

function showHideBoxSubmenu(obj)
{
	var li = obj.parentNode;
	
	for (var i=0;i<li.childNodes.length;i++)
	{
		if (li.childNodes[i].nodeName == "UL")
		{
			var ul = li.childNodes[i];
			if (ul.className == "none")
			{
				ul.className = "block";
			}
			else
			{
				ul.className = "none";
			}
		}
		if (li.childNodes[i].className == "subMenu" || li.childNodes[i].className == "subMenuOn")
		{
			var a = li.childNodes[i];
			if (a.className == "subMenu")
			{
				a.className = "subMenuOn";
			}
			else
			{
				a.className = "subMenu";
			}
		}
	}
}

function updatePage(newTitle,channelId, obj)
{
	var oldTitle = document.getElementById('changeTitle');
	if(oldTitle)
	{
		oldTitle.innerHTML = newTitle;
	}

	cleanChecked();
	
	obj.className = "selected";
	
	checkBrowseBox(obj);
}

function checkBrowseBox(obj)
{
	var a = obj;
	
	var parentN = a.parentNode.parentNode.parentNode;
	
	if (parentN.className != "browsebox_subMenu")
	{
		for (var i =0; i < parentN.childNodes.length; i++)
		{
			if (parentN.childNodes[i].nodeName == "A" && parentN.childNodes[i].className != "subMenuOn")
			{
				parentN.childNodes[i].className = "selected";
			}
		}
	}
}

function cleanChecked()
{	
	//This function is used to check the first level then call the
	//cleanSubChannels to clean the rest of the levels
	var obj = document.getElementById("browseBox");

	for (var i =0; i < obj.childNodes.length; i++)
	{
		if (obj.childNodes[i].className == "browsebox_subMenu" && obj.childNodes[i].nodeName == "LI")
		{
			var sonObj = obj.childNodes[i];
			
			for (var j = 0; j < sonObj.childNodes.length; j++)
			{
				if (sonObj.childNodes[j].nodeName == "UL")
				{
					var ul = sonObj.childNodes[j];
					cleanSubChannels(ul);
				}
			}
		}	
	}
}

function cleanSubChannels(obj)
{
	for (var i =0; i < obj.childNodes.length; i++)
	{
		if (obj.childNodes[i].nodeName == "LI")
		{
			var sonObj = obj.childNodes[i];
			
			for (var j = 0; j < sonObj.childNodes.length; j++)
			{
				if (sonObj.childNodes[j].nodeName == "A" && sonObj.childNodes[j].className != "subMenuOn" && sonObj.childNodes[j].className != "subMenu")
				{
					sonObj.childNodes[j].className = "";
				}
				if (sonObj.childNodes[j].nodeName == "UL")
				{
					var ul = sonObj.childNodes[j];
					cleanSubChannels(ul);
				}
			}
		}
	}
}

function changeTabs(obj,indexTab)
{	
	var ul = obj.parentNode.parentNode;
	for(var i = 0; i < ul.childNodes.length;i++){
		ul.childNodes[i].className = "";
	}
	obj.parentNode.className = "selected";	
	
	var contenVideoInfo = document.getElementById('contenVideoInfo');	
	var contentRelated = document.getElementById('contentRelated');
	var contentLiveEvents = document.getElementById('contentLiveEventsInfo');	
	
	if (indexTab == 2)
	{
		if(contenVideoInfo)
		{
			contenVideoInfo.style.display = "none";	
			if(contentRelated)contentRelated.style.display = 'none';
			if(contentLiveEvents)contentLiveEvents.style.display='block';
		}else{
			ShowLiveEvents();
		}
	}
	else if (indexTab == 1)
	{
		if(contenVideoInfo)
		{
			contenVideoInfo.style.display = "none";	
			if(contentRelated)contentRelated.style.display = 'block';
			if(contentLiveEvents)contentLiveEvents.style.display='none';
		}else{
			ShowVideoRelateds();
		}
	}
	else if (indexTab == 0)
	{	
		if(contenVideoInfo)
		{
			contenVideoInfo.style.display = "block";	
			if(contentRelated)contentRelated.style.display = 'none';
			if(contentLiveEvents)contentLiveEvents.style.display = 'none';
		}else{
			ShowVideoDetails();
		}
	}
	
}

function hideTab()
{	
	alert();
	var contentRelated = document.getElementById('contentRelated');		
	if (contentRelated)
	contentRelated.style.display = 'none';

}
 
CheckInitializeEnvents();
function CheckInitializeEnvents()
{
	try
	{
		if(document.body)
		{
			InitializeEvents();
			return;
		}
	}
	catch(e){}
	
	setTimeout("CheckInitializeEnvents()", 500);
}

var defaultPageLoadExecuted = false;
function DefaultPageLoad()
{
	playerTester = new PlayerTester(); // Initialize bandwidth from currentBandwidth test
	 
	// Makes sure this is never run more than once
	if(defaultPageLoadExecuted)
	{
		return;
	}
	else
	{
		defaultPageLoadExecuted = true;
	}

	var searchBox = document.getElementById("buscaCampo");
	if(searchBox)
	{
		searchBox.focus();
	}

	// Loads the default banner
	DefaultBannerLoad()
	
	metricsFlash = new MetricsFlash('metricsFlash','playerHtml');
}

function DefaultBannerLoad()
{
	var bannerDiv = document.getElementById("publicidade");
	if(bannerDiv)
	{
		if(bannerScript)
		{
			eval(bannerScript);
		}
	}
	else
	{
		window.setTimeout('DefaultBannerLoad()',100);
	}
}
/******************************************************************************
* Login
*******************************************************************************/
var clearPendences = false;
var isPrivateContent = false;
var contentToRedirect = 0;
var channelToRedirect = 0;

function ProcessLogin()
{
	logged = true;
	HideLoginBox();
	LoadMyServicesAjax("ajax", 0);
	SendPendences();
	CallPendencesMethods();
	LoadMenuInst("ajax", false);
}
function Logout()
{	
	ProcessLogout();
}
function ProcessLogout()
{
	var logoutUrl = homeUrl + '&logout=1';
	if(homeUrl.indexOf('templates') >= 0)
	{
		top.location.href = logoutUrl;
	}else{
		top.location.href = '/templates/'+logoutUrl;
	}
}
function CallPendencesMethods()
{
	for(var i = 0; i < pendenceList.length; i++)
	{
		pendenceList[i]();
	}
}
function SendPendences()
{
	clearPendences = true;
}
function ShowLoginBox()
{	
	var loginBox = document.getElementById("loginBox");
	var loginboxFake = document.getElementById("loginBoxFake");
	
	if(loginBox)
	{
		if(loginboxFake)
		{
			loginboxFake.style.display="block";
		}

		if(playerTerra && playerTerra.getCurrentInternalMedia() && playerTerra.getCurrentInternalMedia().isWide && BrowserDetect.browser == "Explorer")
		{
			loginBox.className = "log wideLog";
		}
		else
		{
			loginBox.className = "log";
		}

		loginBox.style.visibility = "visible";
		window.scroll(0,0);
		
		var user = document.getElementById("user");
		if(user)
		{
			user.focus();
		}
	}
	ResizeBanner();
}

function UserHideLoginBox()
{
	//privateList = new Array();
	HideLoginBox();
}
function HideLoginBox()
{
	var loginBox = document.getElementById("loginBox");
	
	var loginboxFake = document.getElementById("loginBoxFake");
	
	if(loginboxFake)
	{
	loginboxFake.style.display="none";
	}	
	
	if(loginBox)
	{
		loginBox.style.visibility = "hidden";
	}
	
	if (isPrivateContent && logged)
	{	  
		top.location.href = '/templates/channelContents.aspx?contentid=' + contentToRedirect + '&channel=' + channelToRedirect;
	}
}
function ShowLogoutBox()
{	
	var logoutBox = document.getElementById("logoutBox");
	//var loginButton = document.getElementById("loginButton");
	
	if(logoutBox)
	{
		if(playerTerra && playerTerra.getCurrentInternalMedia() && playerTerra.getCurrentInternalMedia().isWide && BrowserDetect.browser == "Explorer")
		{
			logoutBox.className = "log out wideLog";
		}
		else
		{
			logoutBox.className = "log out";
		}

		logoutBox.style.visibility = "visible";
		window.scroll(0,0);
	}
	ResizeBanner();
}
function HideLogoutBox()
{
	var logoutBox = document.getElementById("logoutBox");

	if(logoutBox)
	{
		logoutBox.style.visibility = "hidden";
	}
}
function ClearMyServicesBox()
{
	var myServicesBox = document.getElementById("myServicesBox");
	
	if(myServicesBox)
	{
		myServicesBox.innerHTML = '';
	}
}
function ShowMyServicesBox()
{	
	var myServicesBox = document.getElementById("myServicesBox");
	var myServicesButton = document.getElementById("myServicesButton");
	
	if(myServicesBox)
	{
		if(playerTerra && playerTerra.getCurrentInternalMedia() && playerTerra.getCurrentInternalMedia().isWide)
		{
			myServicesBox.className = "log servicos wideLog";
		}
		else
		{
			myServicesBox.className = "log servicos";
		}
	
		myServicesBox.style.visibility = "visible";
		if(myServicesButton)
		{
			myServicesButton.className = "select";
		}
	}
	ResizeBanner();
}
function HideMyServicesBox()
{
	var myServicesBox = document.getElementById("myServicesBox");
	var myServicesButton = document.getElementById("myServicesButton");
	
	if(myServicesBox)
	{
		myServicesBox.style.visibility = "hidden";
		
		if(myServicesButton)
		{
			myServicesButton.className = "";
		}
	}
	CheckWide();
}
function CheckWide()
{
	if(playerTerra && backWide)
	{
		playerTerra.set169();
	}
}
function RunLogged(func)
{
	if(logged)
	{
		func();
	}
	else
	{
		if(!SeachInPendenceList(func))
		{
			pendenceList.push(func);
		}
		ShowLoginBox();
	}
}
function PostLogin()
{
	var user = document.getElementById("user");
	var pw = document.getElementById("password");
	
	if(user && pw)
	{
		PostLoginAjax("ajax", 2, user.value + "," + pw.value);
	}
}
function ParseLogin()
{
	if(this.httpRequest.status == 200)
	{
		if(this.httpRequest.responseText == "true")
		{
			ProcessLogin();
		}
		else
		{
			if(this.httpRequest.responseText == "false")
			{
				alert(Translate("INVALID_LOGIN"));
			}
			else
			{
				alert(Translate("LOGIN_MAX_RETRIES_FAIL"));
			}
		}
	}
}
/****************************************************************************
* General
*****************************************************************************/
var currentPlaylist = 0;
var currentPlaylistName = "";

function ResetPlaylist()
{
	cookieManager.setValue("playlist", "");
}

/****************************************************************************
* Playlist Tabs
*****************************************************************************/
var playlistTab;
function DrawPlaylistTab(index)
{
	if(document.getElementById("playlistContent"))
	{
		playlistTab = index;
		switch(index)
		{
			case 0:
				playlistTerra.drawTab(2);
				break;
			case 1:
				getAjaxContentNoCache('playlistContent','/templates/Ajax/genericAjax.aspx?AjaxSource=TerraMediaCenter.OtherPlaylistsView&page=genericAjax_aspx',true, null);
				break;
			case 2:
				getAjaxContentNoCache('playlistContent','/templates/Ajax/genericAjax.aspx?AjaxSource=TerraMediaCenter.SendPlaylistsView&page=genericAjax_aspx&p2=' + currentPlaylist ,true, null);
				break;
			case 3:
				getAjaxContentNoCache('playlistContent','/templates/Ajax/genericAjax.aspx?AjaxSource=TerraMediaCenter.SavePlaylistView&page=genericAjax_aspx&p2=' + currentPlaylist ,true, null);
				break;
			case 4:
				break;
		}
	}
}

/****************************************************************************
* Load Playlist
*****************************************************************************/
function LoadPlaylist(id, mediaType, channel, name)
{
	if(!playerTerra)
	{
		setTimeout("LoadPlaylist(" + id + ", " + mediaType + ", " + channel + ", '" + name + "')", 500);
	}
	else
	{
		LoadPlaylistThread(id, mediaType, channel, name);
	}
}
function LoadPlaylistThread(id, mediaType, channel, name)
{	
	startPlayback = -2;
	cookieManager.setValue("playlist", "");
	currentPlaylist = id;
	currentPlaylistName = name;
	playlistTerra.clear();
	playlistTerra.drawTab(2);
	Add(id, mediaType, channel, -2);
}

/****************************************************************************
* Send Playlist
*****************************************************************************/
function SendPlaylist(id)
{
	var name = document.getElementById("txtTo").value;
	var email = document.getElementById("txtEmail").value;
	var comment = document.getElementById("txtComment").value;
	
	if(name != "")
	{
		if(email != "")
		{
			if(currentPlaylist > 0)
			{
				ajaxManager.Add("/templates/Ajax/genericAjax.aspx?AjaxSource=TerraMediaCenter.UserPlaylistManager&page=Home_aspx&p1=Send&p2=" + id + "," + name + "," + email + "," + comment, ParseSend, CreateLoading, DestroyLoading, DestroyLoading)
			}
		}
		else
		{
			alert("Preencha o campo \"" + document.getElementById("lblEmail").innerHTML + "\" ");
		}
	}
	else
	{
		alert("Preencha o campo \"" + document.getElementById("lblTo").innerHTML + "\" ");
	}
}
function ParseSend()
{
	if(this.httpRequest.status == 200)
	{
		alert(this.httpRequest.responseText);
		
		if(this.httpRequest.responseText == Translate("PLAYLIST_SEND_SUCESSES"))
		{
			DrawPlaylistTab(0);
		}
	}
}
/****************************************************************************
* Edit Playlist
*****************************************************************************/
function EditPlaylist(id, name)
{
	currentPlaylist = id;
	DrawPlaylistTab(3);
}

/****************************************************************************
* Delete Playlist
*****************************************************************************/
function DeletePlaylist(id)
{
	if(confirm(Translate("CONFIRM_PLAYLIST_DELETE")))
	{
		ajaxManager.Add("/templates/Ajax/genericAjax.aspx?AjaxSource=TerraMediaCenter.UserPlaylistManager&page=Home_aspx&p1=Delete&p2=" + id, ParseDelete, CreateLoading, DestroyLoading, DestroyLoading)
	}
}
function ParseDelete()
{
	if(this.httpRequest.status == 200)
	{
		if(this.httpRequest.responseText == "success")
		{
			alert(Translate("PLAYLIST_DELETE_SUCESSES"));
		}
		else
		{
			alert(Translate("PLAYLIST_DELETE_ERROR"));
		}
		DrawPlaylistTab(1);
	}
}
/****************************************************************************
* Save Playlist
*****************************************************************************/
function SavePlaylist(id)
{
	var name = document.getElementById("txtName").value;
	var duration = playlistTerra.getDuration();
	var items = cookieManager.getValue("playlist").replace(/,/g, '@');
	
	if(name.length > 0 && (items.length > 0 || id > 0))
	{
		ajaxManager.Add("/templates/Ajax/genericAjax.aspx?AjaxSource=TerraMediaCenter.UserPlaylistManager&page=Home_aspx&p1=Save&p2=" + name + "," + duration + "," + items + "," + id, ParseSave, CreateLoading, DestroyLoading, DestroyLoading)
	}
	else
	{
		alert("Não é possível salvar uma playlist vazia");
	}
}
function ParseSave()
{
	if(this.httpRequest.status == 200)
	{
		var pl = parseInt(this.httpRequest.responseText, 10);
		if(this.httpRequest.responseText != "error" && pl > 0)
		{
			alert(Translate("PLAYLIST_SAVE_SUCESSES"));
			currentPlaylist = pl;
		}
		else
		{
			alert(Translate("PLAYLIST_SAVE_ERROR"));
		}
		DrawPlaylistTab(1);
	}
}
/****************************************************************************
* Clear Playlist
*****************************************************************************/
function ClearPlaylist()
{
	playerTerra.stop();
	playlistTerra.clear();
	playlistTerra.syncCookie();
	DrawPlaylist();
}

/***************************************************************************
* Shuffle
***************************************************************************/
function Shuffle()
{
	playerTerra.setShuffle(!playerTerra.getShuffle());
	
	var btnShuffle = document.getElementById("btnShuffle");
	if(btnShuffle)
	{
		btnShuffle.className = playerTerra.getShuffle() ?  "active" : "";
	}
}
/***************************************************************************
* Repeat
***************************************************************************/
function Repeat()
{
	playerTerra.setRepeat(!playerTerra.getRepeat());
	
	var btnRepeat = document.getElementById("btnRepeat");
	if(btnRepeat)
	{
		btnRepeat.className = playerTerra.getRepeat() ?  "active" : "";
	}
}

/***************************************************************************
* Notifier
***************************************************************************/
function DrawNotifier()
{
	var notifierText = document.getElementById("notifierText");
	var notifier = document.getElementById("notifier");
	
	if(notifier && notifierText)
	{
		if(notifierText)
		{
			notifierText.innerHTML = Translate("PLAYLIST") + " (" + playlistTerra.getCount() + ")";
		}
		notifier.className = playlistTerra.getCount() > 0 ? "" : "empty";
	}
}
function PlayFromNotifier()
{
	if(playlistTerra.getCount() > 0)
	{
		var playerArea = document.getElementById("playerContent");
		
		if(playerArea && playerArea.className.lenght > 0)
		{
			playerTerra.playItem(0);
		}
		else
		{
			document.location.href = "/templates/channelContents.aspx?play=-1&channel=" + playlistTerra.getItem(0).channel;			
		}
	}
}
// ************************************************************************************************
// *** Drag & Drop (slider component)
// ************************************************************************************************

var ddItems = new Array();
var dragObj;
var ddX, ddY;
var nn6 = document.getElementById && !document.all;

// Must be called in "document.onmousedown"
function dd_InitDrag(e) {
	var obj = nn6 ? e.target : event.srcElement;
	var i;
	// Check if the target element is registered for drag & drop
	for(i = 0; i < ddItems.length; i++) {
		if(ddItems[i].obj.id == obj.id) {
			dragObj = ddItems[i];
			dragObj.isDragging = true;
			iniWidth = parseInt(dragObj.resizeObj.style.width);
			iniHeight = parseInt(dragObj.resizeObj.style.height);
			ddX = nn6 ? e.clientX : event.clientX;
			ddY = nn6 ? e.clientY : event.clientY;
			document.onmousemove = dd_MouseMove;
			
			break;
		}
	}
}

// Called in "document.onmousemove"
function dd_MouseMove(e) {
	var dragDirection = new DragDirection();
	var newPos;
	
		
	if(dragObj != null && dragObj.isDragging) {
		if(document.all)
			document.selection.empty();
		
		// Horizontal
		if((dragDirection.horizontal & dragObj.dragDirection) != 0) 
		{			
			newPos = iniWidth + ((nn6 ? e.clientX : event.clientX) - ddX);
			
			if(newPos > dragObj.min && newPos <= dragObj.max)
				dragObj.resizeObj.style.width = newPos + 'px';
				
		}
			
		// Vertical
		if((dragDirection.vertical & dragObj.dragDirection) != 0) {
			newPos = iniHeight + ((nn6 ? e.clientY : event.clientY) - ddY);
			
			if(newPos > dragObj.min && newPos <= dragObj.max)
				dragObj.resizeObj.style.height = newPos + 'px';
		}
		
		// Tell to drag item that it is being dragged
		dragObj.dragged();
	}

	return(false);
}

// Called in "document.onmouseup"
function dd_FinishDrag(e) {
	document.onmousemove = null;	
	
	// Alert the drag item that its dragging is finished
	if(dragObj != null) {
		dragObj.isDragging = false;
		dragObj.dragFinished();
	}
		
	dragObj = null;
}

document.onmousedown = dd_InitDrag;
document.onmouseup = dd_FinishDrag;
// ************************************************************************************************
// *** Represents a drag item
// ************************************************************************************************

// Constructor
function DragItem(obj, resizeObj, min, max, direction) {
	// ************************************************************************************************
	// *** Interface
	// ************************************************************************************************

	// Fields
	// ******
	this.min = min;
	this.max = max;
	this.obj = obj;
	this.resizeObj = resizeObj;
	this.dragDirection = direction;
	this.isDragging = false;
	
	// Methods
	// *******
	this.dragged = di_Dragged;
	this.dragFinished = di_DragFinished;
	this.getValue = di_getValue;
	this.setValue = di_setValue;
	
	// Events
	// ******
	this.onDrag = new EventManager();
	this.onDragFinish = new EventManager();
	
	// ************************************************************************************************
	// *** Implementation
	// ************************************************************************************************
	
	// Called when the item is being dragged
	function di_Dragged() {
		this.onDrag.exec();
	}
	
	// Called when the drag finishes
	function di_DragFinished() {
		this.onDragFinish.exec();
	}
	
	// Returns a value between 0 and 1 that represents the position of the drag & drop item
	function di_getValue()
	{
		if(this.resizeObj)
		{
			return parseInt(this.resizeObj.style.width) / this.max;
		}
		return 0;
	}
	
	// Receive a value between 0 and 1 that represents the position of the drag & drop item
	function di_setValue(val)
	{
		if(this.resizeObj)
		{
			this.resizeObj.style.width = (parseInt(val * this.max)) + 'px';
		}
	}
}

// Drag direction constants
function DragDirection() {
	this.vertical = 1;
	this.horizontal = 2;
}
// ************************************************************
// Helpers for Ajax Creation/
// ************************************************************
function AjaxTools()
{
	this.CreateXmlHttpRequest = ajaxTools_CreateXmlHttpRequest;
	this.CreateXmlDocument = ajaxTools_CreateXmlDocument;
	this.CreateXmlDocumentFromUrl = ajaxTools_CreateXmlDocumentFromUrl;
	this.CreateXmlDocumentFromContent = ajaxTools_CreateXmlDocumentFromContent;
	this.ApplyTransform = ajaxTools_ApplyTransform;
	this.GetNodeValue2 = ajaxTools_GetNodeValue2;
	this.SetNodeValue2 = ajaxTools_SetNodeValue2;
	this.SelectNodes2 = ajaxTools_SelectNodes2;
	this.SelectSingleNode2 = ajaxTools_SelectSingleNode2;

	// Required for mozilla
	this.NsResolver = ajaxTools_NsResolver;

	// Backwards-compatibility methods
	this.GetNodeValue = ajaxTools_GetNodeValue;
	this.SetNodeValue = ajaxTools_SetNodeValue;
	this.GetFirstNode = ajaxTools_GetFirstNode;
	this.SelectNodes = ajaxTools_SelectNodes;
	this.SelectSingleNode = ajaxTools_SelectSingleNode;

	this.isMozilla = (typeof document.implementation != 'undefined') && 
	                (typeof document.implementation.createDocument != 'undefined');

	// Checks if a context node was specified,
	// if not used the document itself as a context node
	function GetContextNode(doc, node)
	{
		if(node) return(node);
		return(doc);
	}

	// Creation of HTTP Request 
	function ajaxTools_CreateXmlHttpRequest() 
	{
		if(this.isMozilla)
		{
			return(new XMLHttpRequest());
		}
		else
		{
			return(new ActiveXObject("Msxml2.XMLHTTP"));
		}
	}
	
	// Creation of XML Document
	function ajaxTools_CreateXmlDocument()
	{
		if(this.isMozilla)
		{
			return(document.implementation.createDocument("", "doc", null));	
		}
		else
		{
			return(new ActiveXObject("Msxml2.DomDocument"));	
		}	
	}
	
	// Creation of XML Document from a specified URL
	function ajaxTools_CreateXmlDocumentFromUrl(url)
	{
		var xmlDoc = this.CreateXmlDocument();
		xmlDoc.async = false;
		xmlDoc.load(url);
		return(xmlDoc);
	}
	
	// Creation of XML Document from a specified URL
	function ajaxTools_CreateXmlDocumentFromContent(content)
	{
		var xmlDoc = this.CreateXmlDocument();
		
		if(this.isMozilla)
		{
			var parser = new DOMParser();
			var xmlDoc = parser.parseFromString(content, 'application/xml');
			return(xmlDoc);
		}
		else
		{
			var xmlDoc = new ActiveXObject("Msxml2.DomDocument");
			xmlDoc.loadXML(content);
			return(xmlDoc);
		}
	}
	
	// Apply a XSLT transformation to a page and retrieves the processed text context
	function ajaxTools_ApplyTransform(doc, transform)
	{
		if(this.isMozilla)
		{
			var processor = new XSLTProcessor();
			processor.importStylesheet(transform);
			
			var transformedDoc = processor.transformToDocument(doc);
			
			var serializer = new XMLSerializer();
			return(serializer.serializeToString(transformedDoc));
		}
		else
		{
			return(doc.transformNode(transform));	
		}
	}	
	
	// Required for the mozilla "evaluate" method	
	function ajaxTools_NsResolver(prefix) 
	{
		if(prefix == 'xsl') 
		{
			return 'http://www.w3.org/1999/XSL/Transform';
		}
		return null;
	}
	
	// Gets the value of the xml node
	function ajaxTools_GetNodeValue2(doc, path, node)
	{
		var node = this.SelectSingleNode2(doc,path,node);
		if(node)
		{
			if(node.nodeValue)
			{
				return(node.nodeValue);
			}		
		}
		return('');
	}

	// Sets the value of a xml node
	function ajaxTools_SetNodeValue2(doc, path, value, node)
	{
		this.SelectSingleNode2(doc,path,node).nodeValue = value;
	}
	
	// Retrieves a single of xml node
	function ajaxTools_SelectSingleNode2(doc, path, node)
	{
		if(this.isMozilla)
		{
			return(doc.evaluate(path, GetContextNode(doc,node), this.NsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue);
		}
		else
		{
			return(GetContextNode(doc,node).selectSingleNode(path));
		}
	}
	
	// Retrieves a collection fo xml nodes
	function ajaxTools_SelectNodes2(doc, path, node)
	{
		var ret = new Array();
		if(this.isMozilla)
		{
			var nodeList = doc.evaluate(path, GetContextNode(doc,node), this.NsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
			for(var i=0; i < nodeList.snapshotLength; i++)
			{ 
				ret[i] = nodeList.snapshotItem(i);
			}
			return(ret);
		}
		else
		{
			var obj = GetContextNode(doc,node).selectNodes(path);
			for(var i=0;i<obj.length;i++)
			{
				ret[i] = obj(i);
			}
			return(ret);
		}
	}

	// ************************************************************
	// Backwards-compatibility methods
	// ************************************************************	

	// Gets the value of the xml node
	function ajaxTools_GetNodeValue(node)
	{
		if(node)
		{
			if(node.firstChild)
			{
				return(node.firstChild.nodeValue);
			}
		}
		return('');
	}
	
	// Sets the value of the xml node
	function ajaxTools_SetNodeValue(node, value)
	{
		if(node)
		{
			if(node.firstChild)
			{
				node.firstChild.nodeValue = value;
			}
		}
	}
	
	// Gets the first node from a xml
	function ajaxTools_GetFirstNode(node, path)
	{
		var nodeList = node.getElementsByTagName(path);
		
		if(nodeList.length > 0)
		{
			return(nodeList[0]);
		}
		
		return(null);
	}

	// Gets a list of nodes with the required tag name (only searches direcly below the current node)
	function ajaxTools_SelectNodes(node, tagname)
	{
		var ret = new Array();
		if(node!=null)
		{
			if(node.childNodes!=null)
			{
				for(var i=0;i<node.childNodes.length;i++)
				{
					if(node.childNodes[i].tagName==tagname) ret[ret.length] = node.childNodes[i];
				}
			}
		}
		return(ret);
	}

	// Gets the first node with the required tag name (only searches direcly below the current node)
	function ajaxTools_SelectSingleNode(node, tagname)
	{
		if(node!=null)
		{
			if(node.childNodes!=null)
			{
				for(var i=0;i<node.childNodes.length;i++)
				{
					if(node.childNodes[i].tagName==tagname) return(node.childNodes[i]);
				}
			}
		}
		return(null);
	}
}
// ************************************************************
// Individual Ajax Item 
// ************************************************************
function AjaxItem(parentName, position, url, parseMethod, requestBegin, requestEnd, requestError, parameters, post)
{
	// Tools for XML parsing
	this.tools = new AjaxTools();
	
	// Properties	
	this.httpRequest = null;
	this.url = url;
	this.parentName = parentName;
	this.position = position;
	this.parameters = parameters;

	// User-created Methods
	this.Parse = parseMethod;
	this.RequestBegin = requestBegin;
	this.RequestEnd = requestEnd;
	this.RequestError = requestError;
	this.PostData = post;

	// Predefined Methods
	this.Load = ajaxItem_Load;
	
	function ajaxItem_Load()
	{
		this.httpRequest = this.tools.CreateXmlHttpRequest();

		if(this.httpRequest)
		{
			try
			{
				if(this.RequestBegin)
				{
					this.RequestBegin();
				}
				
				if(post)
				{
					this.httpRequest.open('POST', this.url, true);
					this.httpRequest.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
					
					this.httpRequest.onreadystatechange = new Function(parentName + '.PreParse(' + this.position + ');');
					this.httpRequest.send(post);
				}
				else
				{
					this.httpRequest.onreadystatechange = new Function(parentName + '.PreParse(' + this.position + ');');
					this.httpRequest.open('GET',this.url);
					this.httpRequest.send(null);
				}
			}
			catch(e)
			{
				if(this.RequestError)
				{
					this.RequestError();
				}
					
				alert('Could not open URL');
				alert(e);
			}
		}
		else
		{
			if(this.RequestError)
			{
				this.RequestError();
			}
				
			alert('XmlHttpRequest object could not be loaded');
		}
	}
}

// ************************************************************
// Ajax Manager Object
// ************************************************************
function AjaxManager(objectName, usecache)
{
	this.name = objectName;

	// Properties
	this.items = new Array();
	this.usecache = usecache;
	
	// Methods
	this.Add = ajaxManager_Add;
	this.PreParse = ajaxManager_PreParse;
	
	function ajaxManager_Add(url, parseMethod, requestBegin, requestEnd, requestError, parameters, post)
	{
		// If client-side caching was enabled for this manager
		if(this.usecache)
		{
			// Looks at the items, and sees if we have one with the same URL
			for(var i = 0 ;i < this.items.length; i++)
			{
				// Found a cached item
				if(this.items[i].url == url && (this.items[i].PostData == post || !this.items[i].PostData))
				{
					if(this.items[i].RequestBegin)
						this.items[i].RequestBegin();
					
					// Creates a parsecache method
					this.items[i].ParseCache = parseMethod;
					
					// Runs the parser
					this.items[i].ParseCache();
					
					if(this.items[i].RequestEnd)
						this.items[i].RequestEnd();

					// Ends the request					
					return;
				}
			}
		}
		
		// Creates a new ajax item
		var newItem = new AjaxItem(this.name, this.items.length, url, parseMethod, requestBegin,
									requestEnd, requestError, parameters, post);
		
		// Adds it to the storage
		this.items[this.items.length] = newItem;

		// Starts the Ajax process
		newItem.Load();

	}

	function ajaxManager_PreParse(pos)
	{
		if (this.items[pos].httpRequest.readyState == 4) // readyState = 4 -> Complete
		{
			this.items[pos].Parse();
			
			if(this.items[pos].RequestEnd != null)
			{
				this.items[pos].RequestEnd();
			}
		}
	}
}
// ************************************************************
// Ajax Manager Object
// ************************************************************
function AjaxManagerGeneric(objName, usecache)
{
	//Properties
	this.manager = new AjaxManager(objName + ".manager", usecache);
	
	//Methods
	this.Add = _AjaxManagerGeneric_Add;
	this.AddDefault = _AjaxManagerGeneric_AddDefault;
	
	function _AjaxManagerGeneric_AddDefault(url, divId, notify, post, trigger)
	{
		if(notify)
		{
			this.manager.Add(url, DefaultParser, CreateLoading, EvalHtmlJavaScript, DestroyLoading, divId, post);
		}
		else
		{
			this.manager.Add(url, DefaultParser, null, EvalHtmlJavaScript, null, divId, post);
		}
		this.Trigger = trigger;
	}
	
	function _AjaxManagerGeneric_Add(url, parseMethod, requestBegin, requestEnd, requestError, trigger)
	{
		this.manager.Add(url, parseMethod, requestBegin, requestEnd, requestError);
		this.Trigger = trigger;
	}
}
/* -------------------------------------------------------------
/ Evaluate JavaScript
/ -------------------------------------------------------------*/
function EvalHtmlJavaScript()
{
	//s&oacute; para n&atilde;o dar pau. est&aacute; incorreto
	if(this.RequestError)
	{
		DestroyLoading();
	}
	
	var html = this.httpRequest.responseText;

	var regex = new RegExp("<script[^>]*>[^/]*//VIEW SCRIPT[^<]*</script>");

	if(html.match(regex) != null)
	{
		var result = html.match(regex)[0].toString();
		if (result != null)
		{
			result = result.replace(/<script[^>]*>/, "").replace("</script>", "");
			eval(result);
		}
	}
}

/* -------------------------------------------------------------
/ Default parser
/ -------------------------------------------------------------*/
/* -------------------------------------------------------------
/ Default parser
/ -------------------------------------------------------------*/
function DefaultParser()
{
	if(this.httpRequest.status == 200)
	{
		var html = this.httpRequest.responseText;
		var divList = this.parameters.split(',');
		
		for(var i = 0; i < divList.length; i++)
		{
			var div = document.getElementById(divList[i]);
			
			if(div != null)
			{
				div.innerHTML = html;
			}
		}
		if(genericManager.Trigger)
		{
			genericManager.Trigger();
		}
		
		//alert("here2");
	}
}
// ************************************************************
// Default AJAX Management
// ************************************************************

//Ajax manager
var ajaxManager = new AjaxManager("ajaxManager", false);
var ajaxManagerCache = new AjaxManager("ajaxManagerCache", true);
var genericManager = new AjaxManagerGeneric("genericManager", false);

function getAjaxContent(divName, contentUrl, showNotify, post, trigger)
{
	genericManager.AddDefault(contentUrl, divName, showNotify, post, trigger);
}

function getAjaxContentNoCache(divName, contentUrl, showNotify, post, trigger)
{
	genericManager.manager.usecache = false;
	genericManager.AddDefault(contentUrl, divName, showNotify, post, trigger);
	genericManager.manager.usecache = true;
}
// ************************************************************
// LOADING NOTIFY METHODS
// ************************************************************
function CreateLoading()
{
	var loadingTop = document.getElementById('loadingTop');
	var loadingBottom = document.getElementById('loadingBottom');
	
	if(loadingTop)
	{
		loadingTop.style.display = '';
	}
	if(loadingBottom)
	{
		loadingBottom.style.display = '';
	}
}
function DestroyLoading()
{
	var loadingTop = document.getElementById('loadingTop');
	var loadingBottom = document.getElementById('loadingBottom');
	
	if(loadingTop)
	{
		loadingTop.style.display = 'none';
	}
	if(loadingBottom)
	{
		loadingBottom.style.display = 'none';
	}
}

// ************************************************************************************************
// *** EventManager holds object names / method names pairs and permforms them when requested.
//	The events will be instances of this object
// ************************************************************************************************

// Constuctor
function EventManager() {
	// ************************************************************************************************
	// *** EventManager interface
	// ************************************************************************************************
	
	this.add = em_Add;
	this.exec = em_Exec;	
	
	// ************************************************************************************************
	// *** Implementation
	// ************************************************************************************************

	this.eventItems = new Array();
	
	// Subscribe an event handler (object name/method name pair)
	function em_Add(obj, method) {
		this.eventItems.push(new EventItem(obj, method));
	}
	
	// Performs all subscribed event handlers
	function em_Exec() {
		var i;
		
		for(i = 0; i < this.eventItems.length; i++)
		{
			if(this.eventItems[i].object)
			{
				eval(this.eventItems[i].object + '.' + this.eventItems[i].method + '()');
			}
			else
			{
				eval(this.eventItems[i].method + '()');
			}
		}
	}
}

function EventItem(object, method) {
	this.object = object;
	this.method = method;
}
// ************************************************************************************************
// *** Constructs a MediaItem object
// ************************************************************************************************
var lastMediaItemId = 0;
var uniqueUrl = true;

function MediaItem(id, title, image, duration, ads) {
	// ************************************************************************************************
	// *** MediaItem interface
	// ************************************************************************************************
	
	// Fields
	this.contentId = id; // Media's content id
	this.title = title; // Media's title
	this.imgUrl = image; // Media's playlist image
	this.duration = duration; // Media's duration
	this.ads = ads; // Array of advertisements media items
	
	// Methods
	this.getUrl = mediaItem_GetUrl;	// Gets url for a quality
	this.setUrl = mediaItem_SetUrl; // Sets url for a quality
	
	// ************************************************************************************************
	// *** MediaItem implementation
	// ************************************************************************************************
	
	// Fields
	// ******
	this.mediaUrls = new Array(); // Holds the urls for all media item qualities
	
	// Methods
	// *******
	
	// Gets the media URL considering the quality
	function mediaItem_GetUrl(quality) {
		return this.mediaUrls[quality];
	}
	
	// Sets the media URL for the specified quality
	function mediaItem_SetUrl(quality, url)
	{
		if(url && url != "")
		{
			if(uniqueUrl)
			{
				// Adds a 'counter' to the media URL, to avoid problems with duplicate items in the playlist
				if(url.indexOf('?') > -1)
				{
					url = url.replace('?', '?' + 'uid=' + (lastMediaItemId++) + '&');
				}
				else
				{
					url += '?' + 'uid=' + (lastMediaItemId++);
				}
			}

			this.mediaUrls[quality] = url;
		}
		else
		{
			this.mediaUrls[quality] = "";
		}
	}
}
// ************************************************************************************************
// *** Holds the player states
// ************************************************************************************************

function PlayState() {
	this.undefined = 0;
	this.stopped = 1;
	this.paused = 2;
	this.playing = 3;
	this.buffering = 4;
	this.forwarding = 5;
	this.rewinding = 6;
}
// ************************************************************************************************
// *** Constructs a Quality object that represents a media quality
// ************************************************************************************************

function Quality() {
	this.low = 0;
	this.high = 1;
}
// ************************************************************************************************
// *** Constructs a player object that wraps the Windows Media player (No internal playlist)
// ************************************************************************************************

function PlayerWmSimple(objName, playerObject) {
	// ************************************************************************************************
	// *** Interface
	// ************************************************************************************************
	
	// Control methods
	this.getCurrentMediaDuration = wm_GetCurrentMediaDuration;
	this.getPosition = wm_GetPosition;
	this.setPosition = wm_SetPosition;

	this.next = wm_Next;
	this.pause = wm_Pause;
	this.play = wm_Play;
	this.playItem = wm_PlayItem;
	this.playUrl = wm_PlayUrl;
	this.previous = wm_Previous;
	this.stop = wm_Stop;
	this.fastForward = wm_FastForward;
	this.rewind = wm_Rewind;
	
	// Settings methods
	this.getMute = wm_GetMute;
	this.setMute = wm_SetMute;	
	this.getRepeat = wm_GetRepeat;
	this.setRepeat = wm_SetRepeat;

	this.getVolume = wm_GetVolume;
	this.setVolume = wm_SetVolume;
	
	// Media quality methods
	this.getQuality = wm_GetQuality;
	this.setQuality = wm_SetQuality;
	
	// Playlist related methods
	this.getCurrentPlaylist = wm_GetCurrentPlaylist;
	this.setCurrentPlaylist = wm_SetCurrentPlaylist;
	
	// Play state
	this.getPlayState = wm_GetPlayState;
	
	// Player general methods
	this.getCurrentMedia = wm_GetCurrentMedia;
	this.getStatus = wm_GetStatus;
	this.getBitrate = wm_GetBitrate;
	this.fullScreen = wm_FullScreen;
	this.resize = wm_Resize;
	
	// Events
	this.onCurrentMediaChange = new EventManager(); // Occurs when the current media changes
	this.onCurrentPositionChange = new EventManager(); // Occurs when the current position in the media item changes
	this.onMuteChange = new EventManager(); // Occurs when the mute state changes
	this.onPlayerStateStringChange = new EventManager(); // Occurs when the player state string changes	
	this.onPlayStateChange = new EventManager(); // Occurs when the play state changes

	// ************************************************************************************************
	// *** Implementation
	// ************************************************************************************************
	
	// Fields
	// ******
	this.currentPlaylist = null;	
	this.objName = objName;
	this.playerObject = playerObject;
	this.playState = new PlayState();
	this.quality = new Quality().low;
	this.repeat = false;
		
	// Tick fields
	this.lastCurrentPosition = 0;
	this.lastMediaUrl = '';
	this.lastMute = false;
	this.lastPlayState = this.playState.undefined;
	this.lastStateStr = '';	
	
	// Methods
	// *******
	this.sync = wm_Sync;
	this.createInternalPlaylist = wm_CreateInternalPlaylist;
	this.getCurrentPlaySequenceIndex = wm_GetCurrentPlaySequenceIndex;
	this.getCurrentIndex = wm_GetCurrentIndex;
	this.tick = wm_Tick;
	
	// Create internal playlist
	this.createInternalPlaylist();
	
	// Differentiates manual stop from natural stop
	this.manualStop = true;
	
	// Start tick
	setTimeout(this.objName +'.tick();', 500);
	
	
	// Control methods implementation 
	// ******************************
	
	// Sets the current item to the next item in the playlist
	function wm_Next() {
		if(this.getCurrentIndex()<this.currentPlaylist.count()-1)
		{
			this.playItem(this.getCurrentIndex()+1);
		}
		else
		{
			// Loops around
			this.playItem(0);
		}
	}	
	
	// Pauses the playing of media item
	function wm_Pause() {
		if(this.playerObject)
		{
			if(this.playerObject.controls)
			{
				this.playerObject.controls.pause();
			}
		}
			
	}
	
	// Plays the current media item
	function wm_Play() {
		if(this.getPlayState()!=this.playState.paused && this.getPlayState()!=this.playState.playing)
		{
			// Starting
			this.playItem(0);
		}
		else
		{
			// Resuming
			this.playerObject.controls.play();
		}
		this.currentPlayState = this.playState.playing;
	}
	
	// Plays the specified media item
	function wm_PlayItem(index)
	{
		if(this.currentPlaylist.count() > 0 && index < this.currentPlaylist.count())
		{
			// Gets the play sequence
			var playSequence = this.currentPlaylist.getPlaySequence();

			// Get the play sequence index for the requested index
			var psIndex = this.currentPlaylist.getPlaySequenceIndex(index);
						
			// Plays the item
			this.playerObject.URL = playSequence[psIndex].mediaUrls[this.quality];	
			this.playerObject.controls.play();
			this.manualStop = false;
		}
	}
	
	// Plays the specified url
	function wm_PlayUrl(url) {
		// Do NOT use this when working with playlists
		// Sets the URL and plays
		this.playerObject.URL = url;	
		this.playerObject.controls.play();

		executePlayerStateChange();
		
		this.manualStop = false;
	}

	// Sets the current item to the previous in the playlist
	function wm_Previous() {
		if(this.getCurrentIndex()>0)
		{
			this.playItem(this.getCurrentIndex()-1);
		}
		else
		{
			// Loops around
			this.playItem(this.currentPlaylist.count()-1);			
		}
	}
	
	// Stops the playing of media item
	function wm_Stop() {
		this.playerObject.controls.stop();
		this.manualStop = true;
	}

	// Fast forwards the playing of media item
	function wm_FastForward() {
		this.playerObject.controls.fastForward();
	}
	
	// Rewinds the playing of media item
	function wm_Rewind() {
		this.playerObject.controls.fastReverse();
	}
	
	// Returns the duration (in seconds) of the current media
	function wm_GetCurrentMediaDuration() {
		if(this.playerObject.currentMedia != null)
			return this.playerObject.currentMedia.duration;
		return 0;
	}
	
	// Gets the current position in the media item in seconds from the beginning
	function wm_GetPosition() {
		if(this.playerObject)
			if(this.playerObject.controls)
				return parseInt(this.playerObject.controls.currentPosition);
		return 0;
	}
	
	// Sets the current position in the media item in seconds from de beginning
	function wm_SetPosition(position) {
		this.playerObject.controls.currentPosition = position;
	}
	
	// Settings methods implementation
	// *******************************
	
	// Sets the player volume
	function wm_SetVolume(val)
	{
		if(this.playerObject.settings)
		{
			this.playerObject.settings.volume = val;
			
			
		}
	}
	
	// Retrieves the player volume
	function wm_GetVolume()
	{
		if(this.playerObject.settings)
		{
			return this.playerObject.settings.volume;
		}
	}
	
	// Sets the player's mute state
	function wm_SetMute(mute)
	{
		if(this.playerObject.settings)
		{
			this.playerObject.settings.mute = mute;
			
		}
	}
	
	// Gets the player's mute state
	function wm_GetMute()
	{
		if(this.playerObject)
			if(this.playerObject.settings)
				return this.playerObject.settings.mute;
				
		return(false);
	}
	
	// Gets the repeat flag
	function wm_GetRepeat() 
	{
		return(this.repeat);
	}
	
	// Sets the repeat flag
	function wm_SetRepeat(state)
	{
		this.repeat = state;		
	}
	
	// Playlist related methods implementation
	// ***************************************

	// Gets the current player's playlist
	function wm_GetCurrentPlaylist() {
		return(this.currentPlaylist);
	}
	
	// Sets the current player's playlist
	function wm_SetCurrentPlaylist(playlist) {
		this.currentPlaylist = playlist;
	}
	
	// Syncronize external and internal playlist
	function wm_Sync() {
		// Compatibility only
	}
	
	// Media quality methods
	// *********************
	
	// Get the current media quality
	function wm_GetQuality() {
		return this.quality;
	}

	// Set the current media quality	
	function wm_SetQuality(quality) {
		this.quality = quality;
	}
	
	// Play state
	// **********
	
	// Gets the play state
	function wm_GetPlayState() {
		var playerState;
		
		// Get the play state from player object
		playerState = (this.playerObject) ? this.playerObject.playState : 0;
		
		switch(playerState) {
			case 1 : // Stopped
			case 10 : // Ready
				return this.playState.stopped;
			case 2 : // Paused
				return this.playState.paused;
			case 7 : // Waiting
				this.next(); // End of live, go to next and return 'playing'
			case 4 : // ScanForward
				return this.playState.forwarding;
			case 5 : // ScanReverse
				return this.playState.rewinding;
			case 3 : // Playing
			case 8 : // MediaEnded
				return this.playState.playing;
			case 6 : // Buffering
			case 9 : // Transitioning
			case 11 : // Reconnecting
				return this.playState.buffering;
			default :
				return this.playState.undefined;
		}
	}

	// General methods implementation
	// *******************************
	
	// Gets the current media item
	function wm_GetCurrentMedia() {
		if(this.currentPlaylist == null)
			return null;
			
		var playSequence = this.currentPlaylist.getPlaySequence();
		var index = this.getCurrentPlaySequenceIndex();
		
		return (index >= 0) ? playSequence[index] : null;
	}
	
	// Gets the status string from player
	function wm_GetStatus() {
		return this.playerObject.status;
	}

	// Get the bitrate of the video
	function wm_GetBitrate()
	{
		if(this.playerObject)
			if(this.playerObject.currentMedia != null)
				return this.playerObject.currentMedia.getItemInfo("Bitrate");
		return 0;
	}
	
	// Puts the player in full screen mode
	function wm_FullScreen() {
		try {
			this.playerObject.fullScreen = true;
		} catch(e) {}
	}
	
	// Resizes the player
	function wm_Resize(width, height)
	{
		this.playerObject.width = width;
		this.playerObject.height = height;

		// Workaround for Mozilla
		// Usually it doesn't redraw the player correctly after resizing
		// Setting the body height and returning it to auto forces a redraw
		if(window.GeckoActiveXObject)
		{
			document.getElementsByTagName("body")[0].style.height = '1px';
			window.setTimeout('document.getElementsByTagName("body")[0].style.height = \'auto\';',100); // Apparently a small delay is required
		}
	}
	
	// Creates the internal playlist
	function wm_CreateInternalPlaylist() {
		// Compatibility-only
	}

	// Returns the index of current media item index (play sequence) (-1 if it is not found)
	function wm_GetCurrentIndex() {

		// Determine the current index
		for(var i = 0; i < this.currentPlaylist.mediaItems.length; i++)
		{
			// Strips protocol information
			var url = this.currentPlaylist.mediaItems[i].mediaUrls[this.quality];
			url = url.substring(url.indexOf("://") + 3);

			if(this.playerObject.URL.indexOf(url)>0)
			{
				return i;
			}
			else
			{
				for(var j = 0; j < this.currentPlaylist.mediaItems[i].ads.length;j++)
				{
					// Strips protocol information
					var urlAd = this.currentPlaylist.mediaItems[i].ads[j].mediaUrls[this.quality];
					urlAd = urlAd.substring(urlAd.indexOf("://") + 3);
					if(this.playerObject.URL.indexOf(urlAd)>0)
					{
						return i;
					}
				}
			}
		}
		
		return -1;
	}

	// Returns the index of current media item index (play sequence) (-1 if it is not found)
	function wm_GetCurrentPlaySequenceIndex() {
		var playSequence = this.currentPlaylist.getPlaySequence();

		// Determine the current index
		if(playSequence!=null && this.playerObject!=null)
		{
			for(i = 0; i < playSequence.length; i++)
			{
				// Must strip url from protocol to allow comparison
				var url = playSequence[i].mediaUrls[this.quality];
				url = url.substring(url.indexOf("://") + 3);
				
				if(this.playerObject.URL!=null)
				{
					if(this.playerObject.URL.indexOf(url)>0)
						return i;
				}
			}
		}
		
		return -1;
	}
	
	// Function to check for changes in the player state
	function wm_Tick() {
		var currentMedia = this.getCurrentMedia();
		var currentMediaUrl = currentMedia != null ? currentMedia.mediaUrls[this.quality] : '';
		
		// Detects change and manually sets the next media
		if(this.getPlayState()==this.playState.stopped && !this.manualStop)
		{
			if(this.currentPlaylist)
			{
				var playSequence = this.currentPlaylist.getPlaySequence();
				var currentIndex = this.getCurrentPlaySequenceIndex();
					
				// Goes to the next playlist index
				if(playSequence!=null)
				{
					if(currentIndex<playSequence.length-1)
					{
						this.playerObject.URL = playSequence[currentIndex+1].mediaUrls[this.quality];	
						this.playerObject.controls.play();
					}
					else 
					{
						if(this.repeat)
						{
							this.playItem(0);
						}
						else
						{
							this.manualStop = true;
						}
					}
				}
			}
		}
		
		// State string
		if(this.getStatus() != this.lastStateStr) {
			// Trigger event
			this.onPlayerStateStringChange.exec();
			
			this.lastStateStr = this.getStatus();
		}
		
		// Media change
		if(currentMediaUrl != this.lastMediaUrl && this.getPlayState()!=this.playState.stopped) {
			this.onCurrentMediaChange.exec();
			
			this.lastMediaUrl = currentMediaUrl;
		}
		
		// Current position
		if(this.lastCurrentPosition != this.getPosition()) {
			this.onCurrentPositionChange.exec()
			
			this.lastCurrentPosition = this.getPosition();
		}
		
		// Mute change
		if(this.lastMute != this.getMute()) {
			this.onMuteChange.exec();
			
			this.lastMute = this.getMute();
		}
		
		// Play state change
		if(this.lastPlayState != this.getPlayState()) {
			this.onPlayStateChange.exec();
			
			this.lastPlayState = this.getPlayState();
		}
		
		setTimeout(this.objName +'.tick();', 500);
	}
}

// ************************************************************************************************
// *** Constructs a player object that wraps the QuickTime for Mach
// ************************************************************************************************

function PlayerMac(objName, playerObject)
{
	// ************************************************************************************************
	// *** Interface
	// ************************************************************************************************

	// Control methods
	this.getCurrentMediaDuration = mac_GetCurrentMediaDuration;
	this.getPosition = mac_GetPosition;
	this.setPosition = mac_SetPosition;

	this.next = mac_Next;
	this.pause = mac_Pause;
	this.play = mac_Play;
	this.playItem = mac_PlayItem;
	this.playUrl = mac_PlayUrl;
	this.previous = mac_Previous;
	this.stop = mac_Stop;
	this.fastForward = mac_FastForward;
	this.rewind = mac_Rewind;
		
	// Settings methods
	this.getMute = mac_GetMute;
	this.setMute = mac_SetMute;	
	this.getRepeat = mac_GetRepeat;
	this.setRepeat = mac_SetRepeat;

	this.getVolume = mac_GetVolume;
	this.setVolume = mac_SetVolume;
	
	// Media quality methods
	this.getQuality = mac_GetQuality;
	this.setQuality = mac_SetQuality;
	
	// Playlist related methods
	this.getCurrentPlaylist = mac_GetCurrentPlaylist;
	this.setCurrentPlaylist = mac_SetCurrentPlaylist;
	
	// Play state
	this.getPlayState = mac_GetPlayState;
	
	// Player general methods
	this.getCurrentMedia = mac_GetCurrentMedia;
	this.getStatus = mac_GetStatus;
	this.getBitrate = mac_GetBitrate;
	this.fullScreen = mac_FullScreen;
	this.resize = mac_Resize;
	
	// Events
	this.onCurrentMediaChange = new EventManager(); // Occurs when the current media changes
	this.onCurrentPositionChange = new EventManager(); // Occurs when the current position in the media item changes
	this.onMuteChange = new EventManager(); // Occurs when the mute state changes
	this.onPlayerStateStringChange = new EventManager(); // Occurs when the player state string changes	
	this.onPlayStateChange = new EventManager(); // Occurs when the play state changes

	// ************************************************************************************************
	// *** Implementation
	// ************************************************************************************************
	
	// Fields
	// ******
	this.currentPlaylist = null;	
	this.objName = objName;
	this.playerObject = playerObject;
	this.playState = new PlayState();
	this.quality = new Quality().low;
	this.repeat = false;
	this.paused = false;
	
	// Tick fields
	this.lastCurrentPosition = 0;
	this.lastMediaUrl = '';
	this.lastMute = false;
	this.lastPlayState = this.playState.undefined;
	this.lastStateStr = '';	
	
	// Methods
	// *******
	this.sync = mac_Sync;
	this.createInternalPlaylist = mac_CreateInternalPlaylist;
	this.getCurrentPlaySequenceIndex = mac_GetCurrentPlaySequenceIndex;
	this.getCurrentIndex = mac_GetCurrentIndex;
	this.tick = mac_Tick;
	
	// Create internal playlist
	this.createInternalPlaylist();
	
	// Differentiates manual stop from natural stop
	this.manualStop = true;
	
	// Start tick
	setTimeout(this.objName +'.tick();', 1000);
	
	// Control methods implementation 
	// ******************************
	
	// Sets the current item to the next item in the playlist
	function mac_Next() {
		if(this.getCurrentIndex()<this.currentPlaylist.count()-1)
		{
			this.playItem(this.getCurrentIndex()+1);
		}
		else
		{
			// Loops around
			this.playItem(0);
		}
	}	

	
	// Pauses the playing of media item
	function mac_Pause()
	{
		try
		{
			this.playerObject.Stop();
			this.paused = true;
		}catch(e){}
	}
	
	// Plays the current media item
	function mac_Play(wait)
	{
		if(this.getPlayState()!=this.playState.paused && this.getPlayState()!=this.playState.playing)
		{
			// Starting
			this.playItem(0);
		}
		else
		{
			// Resuming
			try
			{
				this.playerObject.Play();
				this.paused = false;
			}catch(e){}
		}
	}
	
	// Plays the specified media item
	function mac_PlayItem(index, wait)
	{
		if(this.currentPlaylist.count() > 0 && index < this.currentPlaylist.count())
		{
			// Gets the play sequence
			var playSequence = this.currentPlaylist.getPlaySequence();

			// Get the play sequence index for the requested index
			var psIndex = this.currentPlaylist.getPlaySequenceIndex(index);
						
			// Plays the item
			this.playerObject.SetResetPropertiesOnReload(false);
			this.playerObject.SetURL(playSequence[psIndex].mediaUrls[this.quality]);
			this.playerObject.Play();
			
			this.paused = false;
			this.manualStop = false;
		}
	}
	
	// Plays the specified url
	function mac_PlayUrl(url)
	{
		// Plays the item
		this.playerObject.SetResetPropertiesOnReload(false);
		this.playerObject.SetURL(url);
		this.playerObject.Play();
		
		this.paused = false;
		this.manualStop = false;
	}

	// Sets the current item to the previous in the playlist
	function mac_Previous()
	{
		if(this.getCurrentIndex()>0)
		{
			this.playItem(this.getCurrentIndex()-1);
		}
		else
		{
			// Loops around
			this.playItem(this.currentPlaylist.count()-1);			
		}
	}
	
	// Stops the playing of media item
	function mac_Stop()
	{
		try
		{
			this.playerObject.Stop();
			this.paused = false;
			this.manualStop = true;
		}
		catch(e){}
	}
	
	// Fast forwards the playing of media item
	function mac_FastForward()
	{
		// Not supported
	}
	
	// Rewinds the playing of media item
	function mac_Rewind()
	{
		// Not supported
	}
	
	// Returns the duration (in seconds) of the current media
	function mac_GetCurrentMediaDuration()
	{
		try
		{
			return(this.playerObject.GetDuration() / this.playerObject.GetTimeScale());
		}
		catch(e)
		{
			return(0);
		}
	}
	
	// Gets the current position in the media item in seconds from the beginning
	function mac_GetPosition()
	{
		try
		{
			return(this.playerObject.GetTime() / this.playerObject.GetTimeScale());
		}
		catch(e)
		{
			return(0);			
		}
	}
	
	// Sets the current position in the media item in seconds from de beginning
	function mac_SetPosition(position)
	{
		if(this.playerObject)
			this.playerObject.SetTime(position * this.playerObject.GetTimeScale());
	}
	
	// Settings methods implementation
	// *******************************
	
	// Sets the player volume
	function mac_SetVolume(val)
	{
		try
		{
			this.playerObject.SetVolume(val * 2.56);
		}
		catch(e){}
	}
	
	// Retrieves the player volume
	function mac_GetVolume() 
	{
		try
		{
			return this.playerObject.GetVolume() / 2.56;
		}
		catch(e)
		{
			return(0);
		}
	}
	
	// Sets the player's mute state
	function mac_SetMute(mute)
	{
		this.playerObject.SetMute(mute);
	}
	
	// Gets the player's mute state
	function mac_GetMute() 
	{
		return this.playerObject.GetMute();
	}
	
	// Gets the repeat flag
	function mac_GetRepeat() 
	{
		return(this.repeat);
	}
	
	// Sets the repeat flag
	function mac_SetRepeat(state)
	{
		this.repeat = state;
	}
	
	// Playlist related methods implementation
	// ***************************************

	// Gets the current player's playlist
	function mac_GetCurrentPlaylist()
	{
		return(this.currentPlaylist);
	}
	
	// Sets the current player's playlist
	function mac_SetCurrentPlaylist(playlist)
	{
		this.currentPlaylist = playlist;
	}
	
	// Syncronize external and internal playlist
	function mac_Sync()
	{
		// Windows-media compatibility only
	}
	
	// Media quality methods
	// *********************
	
	// Get the current media quality
	function mac_GetQuality()
	{
		return this.quality;
	}

	// Set the current media quality	
	function mac_SetQuality(quality)
	{
		this.quality = quality;
	}
	
	// Play state
	// **********
	
	// Gets the play state
	function mac_GetPlayState()
	{
		// Buffering 
		var playerState = this.playerObject.GetPluginStatus();
		if(playerState=="Waiting" || playerState=="Loading")
		{
			return this.playState.buffering;
		}
		
		// Manual stop
		if(this.manualStop)
		{
			return(this.playState.stopped);
		}
		
		// Automatic stop at end of media
		try
		{
			// At the end of the media
			var duration = this.playerObject.GetDuration();
			var time = this.playerObject.GetTime();
			
			if(time>0 && duration>0 && Math.abs(duration-time)<100)
			{
				return(this.playState.stopped)
			}
		}
		catch(e)
		{
		}
		
		// Playing or paused
		if(this.paused)
		{
			return(this.playState.paused);
		}
		else
		{
			return this.playState.playing;
		}
	}

	// General methods implementation
	// *******************************
	
	// Gets the current media item
	function mac_GetCurrentMedia()
	{
		if(this.currentPlaylist == null)
			return null;
			
		var playSequence = this.currentPlaylist.getPlaySequence();
		var index = this.getCurrentPlaySequenceIndex();
		
		return (index >= 0) ? playSequence[index] : null;
	}
	
	// Gets the status string from player
	function mac_GetStatus()
	{
		var status = '';
		try
		{
			status = this.playerObject.GetPluginStatus();
		}
		catch(e){}
		return(status);
	}
	
	// Get the bitrate of the video
	function mac_GetBitrate()
	{
		return -1; // Not implemented
	}
	
	// Puts the player in fullscreen mode
	// QuickTime not supports fullscreem mode
	function mac_FullScreen() 
	{
	}

	// Resizes the player
	function mac_Resize(width, height)
	{
		this.playerObject.width = width;
		this.playerObject.height = height;
	}	
	
	// Creates the internal playlist
	function mac_CreateInternalPlaylist() {
		// Windows-media compatibility only
	}
	
	// Returns the index of current media item index (not play sequence) (-1 if it is not found)
	function mac_GetCurrentIndex() {

		// Determine the current index
		for(var i = 0; i < this.currentPlaylist.mediaItems.length; i++)
		{
			// Strips protocol information
			var url = this.currentPlaylist.mediaItems[i].mediaUrls[this.quality];
			url = url.substring(url.indexOf("://") + 3);

			if(this.playerObject.GetURL().indexOf(url)>0)
			{
				return i;
			}
			else
			{
				for(var j = 0; j < this.currentPlaylist.mediaItems[i].ads.length;j++)
				{
					// Strips protocol information
					var urlAd = this.currentPlaylist.mediaItems[i].ads[j].mediaUrls[this.quality];
					urlAd = urlAd.substring(urlAd.indexOf("://") + 3);
					if(this.playerObject.GetURL().indexOf(urlAd)>0)
					{
						return i;
					}
				}
			}
		}
		
		return -1;
	}

	// Returns the index of current media item index (play sequence) (-1 if it is not found)
	function mac_GetCurrentPlaySequenceIndex()
	{
		var playSequence = this.currentPlaylist.getPlaySequence();
		
		try
		{
			// Determine the current index
			if(playSequence!=null)
			{
				for(i = 0; i < playSequence.length; i++)
				{
					// Must strip url from protocol to allow comparison
					var url = playSequence[i].mediaUrls[this.quality];
					url = url.substring(url.indexOf("://") + 3);
					
					if(this.playerObject.GetURL().indexOf(url)>0)
						return i;
				}
			}
		}
		catch(e)
		{
			return -1;
		}
	}
	
	// Function to check for changes in the player state
	function mac_Tick()
	{
		var currentMedia = this.getCurrentMedia();
		var currentMediaUrl = currentMedia != null ? currentMedia.mediaUrls[this.quality] : '';

		// Detects change and manually sets the next media
		if(this.getPlayState()==this.playState.stopped && !this.manualStop)
		{
			if(this.currentPlaylist)
			{
				var playSequence = this.currentPlaylist.getPlaySequence();
				var currentIndex = this.getCurrentPlaySequenceIndex();
					
				// Goes to the next playlist index
				if(playSequence!=null)
				{
					if(currentIndex<playSequence.length-1)
					{
						this.playerObject.SetURL(playSequence[currentIndex+1].mediaUrls[this.quality]);
						this.playerObject.Play();
					}
					else
					{
						if(this.repeat)
						{
							this.playItem(0);
						}
						else
						{
							this.manualStop = true;
							this.paused = false;
						}
					}
				}
			}
		}
		
		
		// State string
		if(this.playerObject)
		{
			if(this.getStatus() != this.lastStateStr)
			{
				// Trigger event
				this.onPlayerStateStringChange.exec();
				
				this.lastStateStr = this.getStatus();
			}
		}
		
		// Media change
		if(currentMediaUrl != this.lastMediaUrl)
		{
			this.onCurrentMediaChange.exec();
			this.lastMediaUrl = currentMediaUrl;
		}
		
		// Current position
		if(this.lastCurrentPosition != this.getPosition())
		{
			this.onCurrentPositionChange.exec();
			this.lastCurrentPosition = this.getPosition();
		}
				
		// Mute change
		if(this.lastMute != this.getMute())
		{
			this.onMuteChange.exec();			
			this.lastMute = this.getMute();
		}
		
		// Play state change
		if(this.lastPlayState != this.getPlayState())
		{
			this.onPlayStateChange.exec();			
			this.lastPlayState = this.getPlayState();
		}
		
		setTimeout(this.objName +'.tick();', 1000);
	}
}

// ************************************************************************************************
// *** Detects if wm player is installed
// ************************************************************************************************
var cookieFallBack;
function GetPlayerTypeWm()
{
	var player = null;
	// IE7 + Windows Media ActiveX
	if (window.ActiveXObject && enableWmp)
	{
		try
		{
			player = new ActiveXObject("WMPlayer.OCX.7");
		}
		catch(e) {}
		
		if(player)
			return (playerType.WindowsMedia);
	}
	
	// IE6 + Windows Media ActiveX
	if (window.ActiveXObject && enableWmp)
	{
		try
		{
			player = new ActiveXObject("MediaPlayer.MediaPlayer.1");
		}
		catch(e) {}
		
		if(player)
			return (playerType.WindowsMedia);
	}

	// hotfix FireFox 3.0.6 / 3.0.7 (do not support wmp plugin)
	if(HasPlugin("Windows Media Player Firefox") && enableWmpMozilla & (BrowserDetect.browser == "Firefox 3.0.6" || BrowserDetect.browser == "Firefox 3.0.7"))
	{
		return playerType.WindowsMediaFallback;
	}

	// Mozilla + Windows Media Firefox (Port25)
	if(HasPlugin("Windows Media Player Firefox") && enableWmpMozilla)
	{
		return (playerType.WindowsMediaFirefox);
	}

	// Mozilla + Plugin ActiveX + Windows Media ActiveX
	if(!DisablePluginActivexOnFF)
	{
		if (window.GeckoActiveXObject && enableWmpMozilla)
		{
			try
			{
				player = new GeckoActiveXObject("MediaPlayer.MediaPlayer.1");
			}
			catch (e) {}
		
			if(player)
				return (playerType.WindowsMedia);
		}
	}

	// Mozilla / Safari + Quicktime + Flip4Mac
	if(HasPlugin("QuickTime") && enableQuickTime)
	{
		if(HasPlugin("Flip4Mac"))
			return (playerType.Quicktime);
	}

	// IE7 + Silverlight
	/*if (window.ActiveXObject && enableSilverlight)
	{
		try
		{
			player = new ActiveXObject("AgControl.AgControl");
		}
		catch(e) {}
		
		if(player)
			return (playerType.Silverlight);
	}*/
	
	// Mozilla / Safari + Silverlight
	/*if(HasPlugin("Silverlight") && enableSilverlight)
	{
		return playerType.Silverlight;
	}*/
	
	// chrome com wmp actx (analisar)
	/*
	if(enableChrome && BrowserDetect.browser == 'Chrome')
	{
		alert('chrome wmp');
		return (playerType.WindowsMedia);
	}*/


	if(!cookieFallBack)
	{
		cookieFallBack = cookieManager.getValue("video_fall_back");
	}

	// Windows Media fallback - forced by user request
	if(enableFallback && cookieFallBack == '1')
	{
		// Other/Old Browsers
		if(navigator.mimeTypes["application/x-mplayer2"])
		{
			wmFallBackMode = true;
			return playerType.WindowsMediaFallback;
		}
	}

	// Windows Media fallback - forced by user request
	if(cookieFallBack == '1')
	{
		wmFallBackMode = true;
		return playerType.WindowsMediaFallback;
	}

	return (playerType.Unsupported);
}

// ********************************************************************************
// Initialization
// ********************************************************************************
function InitializeWm()
{
	// Player
	var direction = new DragDirection();
	var actualVolume = 50;
	var actualVolumeSliderSize = 45;
	
	playerTerra = new PlayerTerraWm('playerHtml', GetPlayerTypeWm());

	// Volume Slider
	//playerCustom
	if(document.getElementById("CustomPlayer"))
	{	
				
		if(enableCustomMute)
		{
			setTimeout('playerTerra.mute()',500);							
			// force mute mode - to playstateChangeEvent
			playerTerra.muteMode = true;
			
		}
		else
		{
			tmpMute = cookieManager.getValue("muteActive");
			if(parseBool(tmpMute))
			{
				setTimeout('playerTerra.mute()',500);
				//playerTerra.mute();
				// force mute mode - to playstateChangeEvent
				playerTerra.muteMode = true;
			}
		}
		
		if(VolumeSliderSize)
		{
			actualVolumeSliderSize = VolumeSliderSize;
		}
		
		
		if (customVolume)
		{	
			tmpVolume = cookieManager.getValue("endVolValue");
			if(tmpVolume)
			{
				actualVolume = tmpVolume
			}
			else
			{
				actualVolume = customVolume;
			}	
		}

		if(document.getElementById('CustomPlayer').className == "player Flash")
		{
			document.getElementById('CustomPlayer').className = "player";
		}

	}
	else
	{
		// load mute state from cookie
		tmpMute = cookieManager.getValue("muteActive");
		if(parseBool(tmpMute))
		{
			setTimeout('playerTerra.mute()',500);
			//playerTerra.mute();
			// force mute mode - to playstateChangeEvent
			playerTerra.muteMode = true;
		}
	}
	
	
	playerTerra.volumeSlider = new DragItem(document.getElementById('volumePointer'), document.getElementById('volumeResize'), -1, actualVolumeSliderSize, direction.horizontal);
	playerTerra.volumeSlider.onDragFinish.add('playerTerra', 'sliderVolume');
	playerTerra.volumeSlider.onDrag.add('playerTerra', 'sliderVolume');
	playerTerra.volumeSlider.onDrag.add('playerTerra', 'syncVolume');	
	
	// Position slider
	playerTerra.positionSlider = new DragItem(document.getElementById('positionPointer'), document.getElementById('positionResize'), -1, slideWidth, direction.horizontal);
	playerTerra.positionSlider.onDragFinish.add('playerTerra', 'setPosition');
	playerTerra.positionSlider.onDrag.add('playerTerra', 'syncPosition');
	
	// Drag & drop
	ddItems.push(playerTerra.volumeSlider);
	ddItems.push(playerTerra.positionSlider);
		
	// Initial volume
	playerTerra.setVolume(actualVolume);

	// Starts playback
	playerTerra.playMediaItem(currentMedia);
	
	if(isPlayerCustom)
	{
		// Show Layer Premium
		playerTerra.showLayerPremium();
	}
}

function CheckInitializeWm()
{
	var playerType = GetPlayerTypeWm();

	var playerHtml = document.getElementById("playerHtml");
	var dragVolume = document.getElementById("volumePointer");
	var dragBar = document.getElementById("volumeResize");

	var proceed = true;
	
	// Checks for the player object itself
	if(proceed && !document.getElementById("playerHtml")) proceed = false;

	// Checks for the drag objects
	if(proceed && !document.getElementById("positionPointer")) proceed = false;
	if(proceed && !document.getElementById("volumePointer")) proceed = false;
	if(proceed && !document.getElementById("positionResize")) proceed = false;
	if(proceed && !document.getElementById("volumeResize")) proceed = false;

	// Object/specific checks 
	
	// Windows-Media
	if(proceed && (playerType == playerType.WindowsMedia || playerType==playerType.WindowsMediaFirefox))
	{
		if(!document.getElementById("playerHtml").settings) proceed = false;
	}

	// Silverlight
	if(proceed && playerType == playerType.Silverlight)
	{
		try
		{
			if((document.getElementById("playerHtml").Content.findName("media")))
			{
				// Hides fullscreen button
				var fsButton = document.getElementById('fullscreenButton');
				if(fsButton)
				{
					fsButton.style.display = 'none';
				}
			}
		}
		catch(e)
		{
			proceed = false;
		}
	}
		
	if(proceed)
	{
		InitializeWm();
	}
	else
	{
		setTimeout("CheckInitializeWm()", 1000);
	}
}

// ********************************************************************************
// Player rendering
// ********************************************************************************
function RenderWm(className)
{
	var classString = '';
	if(className!='') classString = ' class="' + className + '" ';

	if(GetPlayerTypeWm()!=playerType.WindowsMediaFallback)
	{
	//	document.write('<div id="playerHost" ' + classString + '>\n');
	}
	
	if(playerWidthWm==0)
	{
		document.write('<div class="video autoSize" id="videoDetais">\n');
	}
	else
	{	
		document.write('<div class="video" id="videoDetais">\n');
	}

	switch (GetPlayerTypeWm())
	{
		case playerType.WindowsMedia:
			RenderWmpIE();
			ShowControlsWm();
			CheckInitializeWm();
			break;
		case playerType.Quicktime:
			RenderQuickTime();
			ShowControlsWm();
			CheckInitializeWm();
			break;
		case playerType.Silverlight:
			RenderSilverlight();
			ShowControlsWm();
			CheckInitializeWm();
			break;
		case playerType.WindowsMediaFirefox:
			RenderWmpMozilla(true);
			ShowControlsWm();
			CheckInitializeWm();
			break;
		case playerType.WindowsMediaFallback:
			RenderWmpFallback();
			break;
	}
	
	document.write('</div>\n');
	
	if(GetPlayerTypeWm()!=playerType.WindowsMediaFallback)
	{
	//	document.write('</div>\n');
	}
}



function RenderWmpIE()
{
	// enable player resize for wide screen videos
	enableUpdateSize = true;

	document.write('<OBJECT id=\"playerHtml\" name=\"playerHtml\" CLASSID=\"CLSID:6BF52A52-394A-11d3-B153-00C04F79FAA6\" width=\"' + playerWidthWm + '\" height=\"' + playerHeightWm + '\" ' + metricPlayerTag + '>\n');
	document.write('<param name=\"URL\" value=\"\">\n');
	document.write('<param name=\"AutoStart\" value=\"False\">\n');
	document.write('<param name=\"TransparentAtStart\" value=\"0\">\n');
	document.write('<param name=\"ShowStatusBar\" value=\"0\">\n');
	document.write('<param name=\"ShowDisplay\" value=\"0\">\n');
	document.write('<param name=\"AutoSize\" value=\"0\">\n');
	document.write('<param name=\"UImode\" value=\"none\">\n');
	document.write('<param name=\"AnimationAtStart\" value=\"True\">\n');
	document.write('<param name=\"StretchToFit\" value=\"True\">\n');	
	/*
	var tmpMute = cookieManager.getValue("muteActive");
	if(parseBool(tmpMute))
	{
		document.write('<param name=\"Mute\" VALUE=\"True\">\n');
	}else{
		document.write('<param name=\"Mute\" VALUE=\"False\">\n');
	}
	*/
	var EnableFirebugVerbose = cookieManager.getValue("debug_firebug_verbose");
	if(EnableFirebugVerbose && EnableFirebugVerbose != "")
	{
		document.write('<param name=\"EnableContextMenu\" value=\"True\">\n');
	}else{
		document.write('<param name=\"EnableContextMenu\" value=\"False\">\n');
	}
	
	document.write('</OBJECT>\n');
	document.write('<SCRIPT style=\"display:none\" language=\"JavaScript\" for=\"playerHtml\" EVENT=\"Click( iButton, iShiftState, fX, fY )\">\n');
	document.write('executePlayerClick();\n');
	document.write('</SCRIPT>\n');	
	
	document.write('<SCRIPT style=\"display:none\" language="JavaScript" for="playerHtml" EVENT="playStateChange( x,y )">\n');
	document.write('executePlayerStateChange();\n');
	document.write('</SCRIPT>\n');

}

function RenderWmpMozilla()
{
	document.write('<OBJECT id=\"playerHtml\" name=\"playerHtml\" type=\"application/x-ms-wmp\" width=\"' + playerWidthWm + '\" height=\"' + playerHeightWm + '\" ' + metricPlayerTag + '>\n');
	document.write('<param name=\"URL\" value=\"\">\n');
	document.write('<param name=\"AutoStart\" value=\"False\">\n');
	document.write('<param name=\"TransparentAtStart\" value=\"0\">\n');
	document.write('<param name=\"ShowStatusBar\" value=\"0\">\n');
	document.write('<param name=\"ShowDisplay\" value=\"0\">\n');
	document.write('<param name=\"AutoSize\" value=\"0\">\n');
	document.write('<param name=\"UImode\" value=\"none\">\n');
	document.write('<param name=\"AnimationAtStart\" value=\"True\">\n');
	document.write('<param name=\"StretchToFit\" value=\"True\">\n');
	/*
	var tmpMute = cookieManager.getValue("muteActive");
	if(parseBool(tmpMute))
	{
		document.write('<param name=\"Mute\" VALUE=\"True\">\n');
	}else{
		document.write('<param name=\"Mute\" VALUE=\"False\">\n');
	}
	*/
	var EnableFirebugVerbose = cookieManager.getValue("debug_firebug_verbose");
	if(EnableFirebugVerbose && EnableFirebugVerbose != "")
	{
		document.write('<param name=\"EnableContextMenu\" value=\"True\">\n');
	}else{
		document.write('<param name=\"EnableContextMenu\" value=\"False\">\n');
	}
	
	document.write('</OBJECT>\n');
	document.write('<SCRIPT style=\"display:none\" language=\"JavaScript\" for=\"playerHtml\" EVENT=\"Click( iButton, iShiftState, fX, fY )\">\n');
	document.write('executePlayerClick();\n');
	document.write('</SCRIPT>\n');	

	document.write('<SCRIPT style=\"display:none\" language="JavaScript" for="playerHtml" EVENT="playStateChange( x,y )">\n');
	document.write('executePlayerStateChange();\n');
	document.write('</SCRIPT>\n');
}

function RenderWmpFallback()
{
	// Grabs the URL
	var url = currentMedia.urlWm;
	
	document.write('<embed id=\"playerHtml\" type="application/x-mplayer2" ');
	document.write('src="' + url + '" ');
	document.write('width="' + playerWidthFull + '" ');
	document.write('height="' + playerHeightFull + '" ');
	document.write('ShowPositionControls=1 ');
	document.write('ShowTracker=1 ');
	document.write('ShowControls=1 ');
	document.write('ShowStatusBar=1 ');
	document.write('Volume=50 ');
	document.write('AutoSize=0 ');
	document.write('DisplaySize=0 ');
	document.write('StretchToFit=1 ');
	document.write('></embed>');
}

function RenderWmpFallbackOnDiv(divName)
{
	var oDivToRender = document.getElementById(divName);
	
	if(oDivToRender)
	{
		// Grabs the URL
		var url = currentMedia.urlWm;
		var cHtmlEmbed = '';
		
		cHtmlEmbed += '<embed id=\"playerHtml\" type="application/x-mplayer2" ';
		cHtmlEmbed += 'src="' + url + '" ';
		cHtmlEmbed += 'width="' + playerWidthFull + '" ';
		cHtmlEmbed += 'height="' + playerHeightFull + '" ';
		cHtmlEmbed += 'ShowPositionControls=1 ';
		cHtmlEmbed += 'ShowTracker=1 ';
		cHtmlEmbed += 'ShowControls=1 ';
		cHtmlEmbed += 'ShowStatusBar=1 ';
		cHtmlEmbed += 'Volume=50 ';
		cHtmlEmbed += 'AutoSize=0 ';
		cHtmlEmbed += 'DisplaySize=0 ';
		cHtmlEmbed += 'StretchToFit=1 ';
		cHtmlEmbed += '></embed>';
		
		oDivToRender.innerHTML = cHtmlEmbed;
	}
}


function RenderQuickTime()
{
	document.write("<EMBED width=\"" + playerWidthWm + "\" height=\"" + playerHeightWm + "\"\n");
	document.write("controller=\"False\" \n");
	document.write("src=\"\" \n");
	document.write("scale=\"ASPECT\" \n");
	document.write("TYPE=\"video/quicktime\"\n");
	document.write("PLUGINSPAGE=\"www.apple.com/quicktime/download\"\n");
	document.write("name=\"playerHtml\"\n");
	document.write("id=\"playerHtml\"\n");
	document.write("enablejavascript=\"true\"\n");
	document.write("volume=\"50\"\n");
	document.write("bgcolor=\"#000000\">\n");
	document.write("</EMBED>\n");
}

function RenderSilverlight()
{
	RenderSilverlight(playerWidthWm, playerHeightWm, "playerHost");
}

function ShowControlsWm()
{
	var divControls = document.getElementById('playerControls');
	if(divControls)
	{
		divControls.style.display = '';
	}
	else
	{
		window.setTimeout('ShowControlsWm()',100);
	}
}
// Disables uniqueUrl for player
uniqueUrl = false;
adultAccepted = false;

function PlayerTerraWm(playerObjName, type)
{
	// ************************************************************************************************
	// *** Initialization
	// ************************************************************************************************

	// Fields
	// ******
	this.currentPlaylist = null;
	this.type = type;	
	switch(type)
	{
		// Windows Media Player
		case 1:
		case 4: 
			this.player = new PlayerWmSimple('playerTerra.player', document.getElementById(playerObjName));
			break;
		// Mac + QuickTime + Flip4Mac
		case 2:
			this.player = new PlayerMac('playerTerra.player', document.getElementById(playerObjName));
			break;
		// Silverlight + Mac or Windows
		case 3:
			this.player = new PlayerSilverlight('playerTerra.player', document.getElementById(playerObjName));
			break;
	}	
	
	// ************************************************************************************************
	// *** Interface
	// ************************************************************************************************	
	 
	// Methods
	this.reset = player_Reset;
	this.getCurrentMedia = player_GetCurrentMedia;
	this.getCurrentInternalMedia = player_GetCurrentInternalMedia;
	this.play = player_Play;
	this.playUrl = player_PlayUrl;
	this.playMediaItem = player_PlayMediaItem;
	this.stop = player_Stop;
	this.mute = player_Mute;
	this.getBitrate = player_GetBitrate;
	this.setVolume = player_SetVolume;
	this.syncVolume = player_SyncVolume;
	this.increaseVolume = player_IncreaseVolume;
	this.decreaseVolume = player_DecreaseVolume;
	this.maxVolume = player_MaxVolume;
	this.sliderVolume = player_SliderVolume;
	this.fullScreen = player_FullScreen;
	this.getPlayState = player_GetPlayState;
	this.setPosition = player_SetPosition;
	this.syncPosition = player_SyncPosition;
	this.adPost = player_AdPost;
	this.adCallback = player_AdCallback;
	this.adMonitor = player_AdMonitor;
	this.printNextMedia = player_PrintNextMedia;	
	this.resize = player_Resize;
	
	this.showLayerPremium = player_ShowLayerPremium;
	
	// Ad frequency controls
	this.getPlayedVideoCount = player_GetPlayedVideoCount;
	this.resetPlayedVideoCount = player_ResetPlayedVideoCount;
	this.incrementPlayedVideoCount = player_IncrementPlayedVideoCount;

	// Adult content methods
	this.adultContent = player_AdultContent;
	this.adultAccept = player_AdultAccept;
	this.adultRefuse = player_AdultRefuse;
	this.adultRefuseCustom = player_AdultRefuseCustom;
	
	// Bandwidth test methods
	this.bandwidthTest = player_BandwidthTest;
	this.bandwidthTestFinished = player_BandwidthTestFinished;
	this.bandwidthBufferLimit = player_BandwidthBufferLimit;

	// Event Handlers
	this.updateTimeInfo = player_UpdateTimeInfo;
	this.updatePositionSlider = player_UpdatePositionSlider;
	this.updatePlayPauseButton = player_updatePlayPauseButton;
	this.updateState = player_UpdateState;
	this.currentMediaChange = player_CurrentMediaChange;
	this.moveToNextMedia = player_MoveToNextMedia;

	// Bind player event handlers
	this.player.onCurrentPositionChange.add('playerTerra', 'updateTimeInfo');
	this.player.onCurrentPositionChange.add('playerTerra', 'updatePositionSlider');
	this.player.onPlayStateChange.add('playerTerra', 'updatePlayPauseButton');
	this.player.onPlayStateChange.add('playerTerra', 'updateState');
	this.player.onPlayStateChange.add('playerTerra', 'moveToNextMedia');
	
	this.playState = new PlayState();
	this.bandwidthTester = new SpeedTester('playerTerra.bandwidthTester',sbrTestCount,sbrTestImage,sbrTestImageSize);
	
	// Stores information for the current media
	this.currentPosition = -1;
	
	// Informs if the current stop was a manual or not
	this.manualStop = true;
	
	// Informs if the currently playing video is an ad
	this.playingAd = false;
	
	// Objects being played
	this.currentObject = null;
	this.currentAdObject = null;
	
	// Blocks further ad playback after video start, for coherency with Flash player
	this.adBlock = false;
	
	// Management to handle problems in the adserver
	this.adLoadStart = null;
	this.adMonitorTimer = null;
	
	// Informs if the currently playing video is a related
	this.playingRelated = false;
	this.currentRelated = -1;
	
	// Informs if repeat is enabled or not
	this.repeat = false;
	
	// Adult video settings
	this.beforeDiscContent = -1;
	
	// Bandwidth test settings
	this.currentBandwidth = 0;
	this.bandwidthTestFinishedUrl = null;
	
	// Buffering controls
	this.bufferingTimes = new Array();
	this.bufferingLimitReached = false;
	this.bufferingNotified = false;
	this.bufferingIgnoreNext = true;
	
	// ************************************************************************************************
	// *** Implementation
	// ************************************************************************************************

	// Resets player to "stopped" state
	function player_Reset()
	{
		this.manualStop = true;
		this.playingAd = false;
	}

	// Gets the current media index
	function player_GetCurrentIndex()
	{
		if(this.playingRelated)
		{
			return(-1);
		}
		else
		{
			return (this.currentPosition);
		}
	}
	
	// Gets the current media ("visible", doesn't include ads)
	function player_GetCurrentMedia()
	{
		return (this.currentObject);
	}

	// Gets the current media ("internal", include ads)
	function player_GetCurrentInternalMedia()
	{
		if(this.playingAd)
		{
			return (this.currentAdObject);
		}
		else
		{
			return (this.currentObject);
		}
	}
	
	function player_PlayUrl(url)
	{
		this.manualStop = true;
		this.player.pause(); // For aesthetic reasons only
		
		var performBandwidthTest = false;
		if(playerTester)
		{
			if(playerTester.currentBandwidth<=0)
			{
				performBandwidthTest = true;
			}
		}
		if(sbrEnabled && performBandwidthTest)
		{
			playerTester.bandwidthTestFinishedUrl = url;
			playerTester.bandwidthTest();
			return;
		}
		else
		{
			// Clears the buffering counts on a video change
			this.bufferingTimes = new Array();
			this.bufferingLimitReached = false;
			this.bufferingNotified = false;

			if(sbrEnabled && playerTester)
			{
				var bandwidth = CookieRestore(cookieSettings, "bandwidth");	

				if(bandwidth)				
					url += '&bandwidth=' + bandwidth;
				else
					url += '&bandwidth=' + userDefaultBandwidth; 
	
			}
			
			Verbose("Playing URL " + url);
			window.setTimeout("playerTerra.player.playUrl('" + url + "');playerTerra.manualStop = false;playerTerra.currentMediaChange();",500);
		}
	}
	
	// Plays the current media item
	function player_Play()
	{
		var state = this.player.getPlayState();
		if(state == this.playState.playing)
		{
			var currentMedia = this.getCurrentMedia();
			if(currentMedia.isLive)
			{
				this.player.stop();
			}
			else
			{
				this.player.pause();
			}
		}
		else
		{
			if(state == this.playState.paused)
			{
				this.player.play();
			}
			else
			{
				this.playMediaItem(this.currentObject);
			}
		}

		// Updates state now instead of relying on timed update
		this.updatePlayPauseButton();
		
	}
	
	// Plays a specific playlist item
	function player_PlayMediaItem(mi)
	{

		this.currentObject = mi;
		if(this.currentObject)
		{
			if(this.currentObject.isAdult && !CookieRestore(cookieSession, "adult") && !adultAccepted)
			{
				this.adultContent();
				return;
			}
		
			// Gets the number of videos played since the last ad
			var videoCount = this.getPlayedVideoCount();

			// Quick fix to prevent ad from playing multiple times without reloading
			// Used to make the behavior between WM and Flash coherent
			if(!this.adBlock && allowVideoAd)
			{
				// Checks if it's time to play an ad
				if(this.currentObject.adFrequency>0 && !this.playingAd)
				{
					if(videoCount % this.currentObject.adFrequency == 0)
					{
						this.resetPlayedVideoCount(); // Resets the frequency counter
						//Set UVTag
						uvTagFrameCall(this.currentObject.isLive, true, false);
						this.adPost(this.currentObject);
						return;
					}
				}
			}

			// Plays the video
			var url = this.currentObject.urlWm;
			if(url)
			{
				this.incrementPlayedVideoCount(); // Increments the frequency counter
				this.adBlock = true;
				this.playingAd = false;
				this.playUrl(url);

			}
		}
		uvTagFrameCall(this.currentObject.isLive, false, false);
	}
	
	// Stops player
	function player_Stop() 
	{
		this.player.stop();
		this.reset();
	}	
	
	// Mute
	function player_Mute()
	{
		this.muteMode = !this.player.getMute();
		this.player.setMute(this.muteMode);
		
		cookieManager.setValue("muteActive", this.muteMode);
		if(!this.player.getMute())
		{
			this.player.setVolume(parseInt(this.volumeSlider.getValue() * 100));
		}

		var btnMute = document.getElementById("btnMute");		

		if(btnMute)
		{
			if(this.player.getMute())
			{
				btnMute.className = "mute selected";
			}
			else
			{
				btnMute.className = "mute";
			}
		}
	}	

	// Gets the current bitrate in kbps
	function player_GetBitrate()
	{
		var bitrate = this.player.getBitrate();
		if(bitrate>0) bitrate = bitrate/1000; // In KBps
		return(bitrate);
	}
	
	// Sets the player's volume
	function player_SetVolume(volume)
	{
		this.volumeSlider.setValue(volume / 100);
		this.syncVolume();
		this.player.setVolume(volume);
		cookieManager.setValue("endVolValue", parseInt(this.volumeSlider.getValue() * 100));
							
	}
		
	// Increases player volume by 10
	function player_IncreaseVolume()
	{
		var volume = this.player.getVolume();
		volume = Math.min(volume + 10, 100);
		this.setVolume(volume);
	}
	
	// Decreases player volume by 10
	function player_DecreaseVolume()
	{
		var volume = this.player.getVolume();
		volume = Math.max(volume - 10, 0);
		this.setVolume(volume);
	}	

	// Sets the volume to max
	function player_MaxVolume()
	{
		this.setVolume(100);
	}

	// Sets the volume to the slider volume
	function player_SliderVolume()
	{	
		// salvar no cookie
		newVol = parseInt(this.volumeSlider.getValue() * 100)
		cookieManager.setValue("endVolValue",newVol);
						
		if(!this.player.getMute())
		{			
			
			this.player.setVolume(this.volumeSlider.getValue() * 100);
			
		}
	}
	
	// Syncs the player slider with the slider bar
	function player_SyncVolume()
	{
		// Keeps button and bar sync'ed
		var pointerObj = document.getElementById('volumePointer');
		var barObj = document.getElementById('volumeResize');
		if(pointerObj && barObj)
		{
			if(pointerObj.style.left!=barObj.style.width)
			{
				pointerObj.style.left=barObj.style.width;
			}
		}
	}
	
	// Full screen	
	function player_FullScreen()
	{
		this.player.fullScreen();
	}

	// Retrieves the current player playstate	
	function player_GetPlayState()
	{
		return(this.player.getPlayState());	
	}
	
	// Sets the current position
	function player_SetPosition()
	{
		if(this.getCurrentMedia())
		{
			if(!this.playingAd)
			{
				this.bufferingIgnoreNext = true;
				var pos = this.positionSlider.getValue() * this.player.getCurrentMediaDuration();
				this.player.setPosition(pos);
			}
		}
	}
	
	// Syncs the player slider with the slider bar
	function player_SyncPosition()
	{
		// Keeps button and bar sync'ed
		var pointerObj = document.getElementById('positionPointer');
		var barObj = document.getElementById('positionResize');
		if(pointerObj && barObj)
		{
			if(pointerObj.style.left!=barObj.style.width)
			{
				pointerObj.style.left=barObj.style.width;
			}
		}
	}
	
	// Resizes the player
	function player_Resize(width, height)
	{
		this.player.resize(width, height);
	}

	//
	// AD FREQUENCY CONTROLS
	//
	function player_IncrementPlayedVideoCount()
	{
		cookieManager.setValue("playedVideoCount", this.getPlayedVideoCount()+1);
	}

	function player_ResetPlayedVideoCount()
	{
		cookieManager.setValue("playedVideoCount", "0");
	}

	function player_GetPlayedVideoCount()
	{
		var value = cookieManager.getValue("playedVideoCount");
		if(value!=null && value!='')
		{
			value = parseInt(value);	
		}
		else
		{
			value = 0;
		}
		return(value);
	}

	//
	// EVENT HANDLERS
	//
	
	// Updates time info	
	

/*	
	// player custom
	if(isPlayerCustom)
	{
		document.getElementById("loadingtimedetails").className="loaded";
	}
*/
	
	function player_UpdateTimeInfo()
	{
		// custom player
		if(isPlayerCustom)
		{
			if((isCustomPrivate && !logged) || isCustomPrivate)
			{
			
			}
			else
			{
				if(disableAutoPlay)
				{
					this.stop();
					disableAutoPlay = false;
				}
				if(enableCustomMute)
				{
					this.player.setMute(this.muteMode);
				}
				
				var divLoadingTime = document.getElementById('loadingTime');
				var divCurrentTime = document.getElementById('currentTime');
				var divSlashTime = document.getElementById('slashTime');
				var divTotalTime = document.getElementById('totalTime');
				var divKbps = document.getElementById('kbps');
				var divCustomLoading = document.getElementById('dvCustomLoading');
				var divPlayerHost = document.getElementById('playerHost');

				var duration = this.player.getCurrentMediaDuration();
				var currentPosition = this.player.getPosition();
				var currentMedia = this.getCurrentMedia();							
				var player = document.getElementById('playerHtml');
				
				
				// loading box
				if(divLoadingTime)
				{
					var state = this.getPlayState();
					if((state == (new PlayState()).buffering))
					{
																	
						if(enableCustomLoading)
						{
							if(divCustomLoading && player)
							{
								divCustomLoading.style.zIndex = 99999999;
								player.style.visibility = 'hidden';
								divCustomLoading.style.display = 'block';
													
							}
						}
						else
						{
							divLoadingTime.className = 'loadingTimeloading';
						}
					}
					else
					{
						divLoadingTime.className = 'hidedetail';
						

						if(enableCustomLoading)
						{
							if(divCustomLoading) divCustomLoading.style.zIndex = -1;
							player.style.visibility = 'visible';
							
						}
					}
				}
				// running time
				if(divCurrentTime) 
				{
					if(this.getPlayState() == 3) // catch playing
					{	
						divCurrentTime.className = 'currentTime';
						divCurrentTime.innerHTML = FormatTime(currentPosition);
					}
					else
					{
						divCurrentTime.className = 'hidedetail';
					}
				}
				// slash time
				if(divSlashTime)
				{
					if(this.getPlayState() == 3) // catch playing
					{	
						divSlashTime.className = 'slashTime';
					}
					else
					{
						divSlashTime.className = 'hidedetail';
					}				
				}
				// total time
				if(divTotalTime)
				{
					if(this.getPlayState() == 3) // catch playing
					{
						divTotalTime.className = 'totalTime';
						divTotalTime.innerHTML = FormatTime(duration);
					}
					else
					{
						divTotalTime.className = 'hidedetail';
					}
				}
				// bit rate 
				if(divKbps)
				{
					if(this.getPlayState() == 3) // catch playing
					{
						divKbps.className = 'kbps';
						divKbps.innerHTML = Math.round(this.getBitrate()) + 'kbps';
					}
					else
					{
						divKbps.className = 'hidedetail';
					}			
				}
			}
		}
		else
		{
			var div = document.getElementById('currentTime');

			if(div)
			{
				var state = this.getPlayState();
				var text;
				
				if((state == (new PlayState()).buffering))
				{
					text = Translate("LOADING") + "...";
					
				}		
				else
				{
					var duration = this.player.getCurrentMediaDuration();
					var currentPosition = this.player.getPosition();

					var currentMedia = this.getCurrentMedia()
					if(currentMedia)
					{
						if(currentMedia.isLive)
						{
							text = FormatTime(currentPosition);
						}
						else
						{
							text = FormatTime(currentPosition) + ' / ' + FormatTime(duration);
						}
					}
					else
					{
						text = FormatTime(currentPosition) + ' / ' + FormatTime(duration);
					}
					
				}
				if(div)
				{
					div.innerHTML = text;
				}
				if(this.getBitrate() > 0)
				{
					div.innerHTML += "&nbsp;&nbsp;" + parseInt(this.getBitrate(), 10) + "kbps";
				}
			}
		}
	}

	
	// Update position slider
	function player_UpdatePositionSlider()
	{
		var currentMediaDuration;
		
		if(this.positionSlider)
		{			
			// Move the position slider only if it is not being dragged
			if(!this.positionSlider.isDragging)
			{
				currentMediaDuration = this.player.getCurrentMediaDuration();
				this.positionSlider.setValue((currentMediaDuration > 0) ? this.player.getPosition() / currentMediaDuration : 0);
				this.syncPosition();
			}
		}
	}
	
	// Updates the play/pause button
	function player_updatePlayPauseButton()
	{
		var state = this.getPlayState();
		var btnPlay = document.getElementById("btnPlay");
		
		if(btnPlay)
		{
			if(state == 3)
			{
				var currentMedia = this.getCurrentMedia();
				if(currentMedia)
				{
					if(currentMedia.isLive)
					{
						btnPlay.className = "bts stop";
					}
					else
					{
						btnPlay.className = "bts pause";
					}
				}
			}
			else
			{
				btnPlay.className = "bts play";
			}
		}
	}
		
	// Event handler for playstate
	function player_UpdateState()
	{
	
		// Updates the time info
		this.updateTimeInfo();
		
		// Hides the banner if we're stopped
		if(this.player.getPlayState() < 2)
		{
			this.bufferingIgnoreNext = true;
			ResizeBanner();
		}
		
		// Increments buffering count if the new state is "buffering"
		if(this.getPlayState()==this.playState.buffering && sbrEnabled)
		{
			if(this.bufferingIgnoreNext)
			{
				Verbose('Player is buffering, count not incremented');
				
			}
			else
			{
				Verbose('Player is buffering');

				// Stores the buffering
				this.bufferingTimes[this.bufferingTimes.length]=new Date();
				
				// Checks if the buffering count has reached the limit
				var bufferingCount = 0;
				var startDate = new Date((new Date().getTime())-sbrBufferingLimitTime*1000);
				for(var i=0;i<this.bufferingTimes.length;i++)
				{
					if(this.bufferingTimes[i]>startDate)
					{
						bufferingCount++;
					}
				}
				
				if(bufferingCount>=sbrBufferingLimit)
				{
					this.bufferingLimitReached = true;
				}
			}
		}
		
		// Clears the ignore buffering flag if the playback started
		if(this.getPlayState()==this.playState.playing)
		{
			this.bufferingIgnoreNext = false;
		}
		
		// After reaching the limit and finished buffering, shows alert
		if(this.getPlayState()==this.playState.playing && this.bufferingLimitReached)
		{
			playerTester.bandwidthBufferLimit();
		}
		
		// After reaching the limit and finished buffering, shows alert
		if(this.getPlayState()==this.playState.playing && this.bufferingLimitReached)
		{
			this.bandwidthBufferLimit();
		}
		
		// After reaching the limit and finished buffering, shows alert
		if(this.getPlayState()==this.playState.playing && this.bufferingLimitReached)
		{
			playerTester.bandwidthBufferLimit();
		}
	}
	
	// Function to be called on media change
	function player_CurrentMediaChange()
	{
		// Loads medias
		var current = playerTerra.getCurrentMedia();
		var currentInternal = this.getCurrentInternalMedia();

		if(current && currentInternal)
		{
			// Custom start script
			if(currentInternal && currentInternal.startScript && currentInternal.startScript!='')
			{
				Verbose("Start of video script: " + currentInternal.startScript);
				eval(currentInternal.startScript);
			}

			// Next item ticker
			var nextItemObj = document.getElementById('nextVideoTicker');
			if(nextItemObj)
			{
				if(nextItemTitle!='')
				{
					nextItemObj.innerHTML = '<strong>' + Translate('NEXT_ITEM') + '</strong>' + ': <a style="cursor:pointer" onclick="PlayNext();">' + nextItemTitle + '</a>';
				}
				else
				{
					nextItemObj.innerHTML = '';
				}
			}

			// Hides timeline for live contents
			var divTimeline = document.getElementById('divTimeline');
			if(currentInternal.isLive)
			{
				// Hides timeline for live signals
				if(divTimeline)
				{
					divTimeline.style.visibility = 'hidden';
				}
			}
			else
			{
				// Shows timeline for ondemand signals
				if(divTimeline)
				{
					divTimeline.style.visibility = 'visible';
				}
			}

			// Updates player to regular/wide mode
			if(enableUpdateSize)
			{
				var holderObj = document.getElementById('playerHolder');
				if(holderObj)
				{
					if(currentInternal.isWide)
					{
						holderObj.className = 'videoContent wide';
						this.resize(550,310);
					}
					else
					{
						holderObj.className = 'videoContent';
						this.resize(480,360);
					}
				}
			}
			// Updates time display
			this.updateTimeInfo();
		}
	}

	// Moves to the next media when the current one stops	
	function player_MoveToNextMedia()
	{
	
		var state = this.getPlayState();

		if(state == this.playState.stopped && !this.manualStop)
		{
			var currentMedia = this.getCurrentInternalMedia();
			
			if(currentMedia && currentMedia.endScript && currentMedia.endScript!='')
			{
				Verbose("End of video script: " + currentMedia.endScript);
				eval(currentMedia.endScript);
			}			
			if(this.playingAd)
			{
				// Currently playing ad, call playItem on the same media to start the actual video
				this.playMediaItem(this.currentObject);
			}
			else
			{
				//custom player
				var oDvCustomPlayer = document.getElementById("CustomPlayer");
				var oDvPlayerHtml = document.getElementById("playerHtml");
				
				if(oDvCustomPlayer)
				{
					if (!disableRelated)
	   				{
	   					ShowRelatedsBox();
	   				}else{	   					
	   					
						if(playerpreview3)
						{
							var playerClassName = 'player details';
							if(currentMedia)
							{
								if(currentMedia.urlFlash!='')
								{
									playerClassName = 'player details';
								}
							}
							
							if (oDvPlayerHtml)
							{
								oDvPlayerHtml.style.visibility='hidden';
							}
							
							
							oDvCustomPlayer.className=playerClassName;
							var oDvLayer3 = document.getElementById("detailsLayer3");
							if(oDvLayer3)
							{
								oDvLayer3.style.display='block';
							}
						}
					}
				}
				else
				{
					// Shows the related box
					if (!disableRelated)
					{
						if(DisplayRelatedUIatTTV)
						{
							ShowRelatedsBox();
						}
						else
						{
							if(nextItemUrl != '')
							{
								top.location = nextItemUrl;
							}
						
						}
					}
				}
			}					
			
			// Procedures to keep actual volume state with WMV and Flash medias						
			
			// Retirada temporariamente
			keep_CurrentVolume();
		}
	}
	
	function keep_CurrentVolume()
	{		
		/* sequencia das regras para volume:
			1 - se houver querystring volumeLevel, dever gravar a querystring do volume no cookie
			2 - no existindo querystring, ler do cookie o ultimo volume marcado
			3 - regravar o estado do volume no cookie ao terminar o video
		*/

		var tmpVol;
		if(customVolume)
		{
			try
			{
				tmpVol = cookieManager.getValue("endVolValue");
				if(!tmpVol)
				{
				cookieManager.setValue("endVolValue",customVolume);
				}
			}
			catch(e)
			{
				//alert("um erro ocorreu : " + e.toString());
			}
		}
		else
		{

			tmpVol = cookieManager.getValue("endVolValue");
			if(tmpVol && player)
			{
				player.setVolume(tmpVol); 
			}
			else
			{
				var tmpvol2 = player.getVolume();
				cookieManager.setValue("endVolValue", tempvol2);
			}


			tmpMute = cookieManager.getValue("muteActive");
			if(parseBool(tmpMute))
			{
				this.player.setMute(parseBool(this.tmpMute)); 
			}
	    }	

/*
		
		var vol_1 = cookieManager.getValue("endVolValue");
		alert('vol_1' + vol_1);
		// converter para (player)?flash:wmp;
		var player = (document.getElementById('playerHtml'))?document.getElementById('playerHtml'):document.getElementById('playerHtml') ;	
		
		
		
		
		alert('novo player'+player+' valor do volume '+volume);
		
			var volume = player.getVolume();						
			
			
				cookieManager.setValue("endVolValue", volume);
		
			if (player.getMute())
			{
				cookieManager.setValue("valorBkp", 40);			
				cookieManager.setValue("muteActive", true);
			}
			else
			{
				cookieManager.setValue("valorBkp", null);
				cookieManager.setValue("muteActive", false);
			}	
		
		   
		   alert('Valor do cookie 1>>> '+cookieManager.getValue('endVolValue'));
		   alert('Valor do cookie 2>>> '+cookieManager.getValue('muteActive'));
		   
		*/   
		  
	}
	
	function player_AdPost(media)
	{
		// Creates the iframe
		var iframe = document.getElementById('videoAdFrame');
		if(!iframe)
		{
			iframe = document.createElement('iframe');
			iframe.id = 'videoAdFrame';
			iframe.frameBorder = 0;
			iframe.height = 0;
			iframe.width = 0;
			document.body.appendChild(iframe);
		}
		
		// Replaces the "random part in the url"
		UpdateRandom();
		var postUrl = new String(media.videoadurl);
		postUrl = postUrl.replace("#random#",currentRandom);
		postUrl = postUrl.replace("%23random%23",currentRandom); // Escaped
		
		// Logs information
		Verbose("Requesting Ad using URL: " + postUrl);
		
		// Posts to the iframe
		iframe = (iframe.frameElement) ? iframe.frameElement : iframe;
		iframe.setAttribute("src", postUrl);
		
		// Starts the monitor
		this.adLoadStart = (new Date()).getTime();
		this.adMonitor();
	}
	
	function player_AdCallback(mi)
	{
		// Clears the monitor timer
		window.clearTimeout(this.adMonitorTimer);

		var playbackUrl = mi.urlWm;
		this.playingAd = true;
		
		// Logs callbacl information
		Verbose("Ad received, playback URL: " + playbackUrl);		
		if(playbackUrl && playbackUrl!='')
		{
			// Starts playback of the ad
			this.currentAdObject = mi;
			this.playUrl(playbackUrl);
		}
		else
		{
			// No ad, goes straight to the video
			this.playMediaItem(this.currentObject);
		}
	}
	
	function player_AdMonitor()
	{
		if((new Date()).getTime()-this.adLoadStart > externalAdTimeout * 1000)
		{
			// Prevents the iframe from proceeding
			var iframe = document.getElementById('videoAdFrame');
			if(iframe)
			{
				iframe = (iframe.frameElement) ? iframe.frameElement : iframe;
				iframe.setAttribute("src","");
			}
			
			Verbose("Ad timeout, proceeding to video playback");
			
			// Proceeds to the video itself
			this.playingAd = true;
			this.playMediaItem(this.currentObject);
		}
		else
		{
			this.adMonitorTimer = window.setTimeout('playerTerra.adMonitor()',1000)
		}
	}
	
	function player_AdultContent()
	{
		var playerObject = document.getElementById("playerHtml");
		var alertBox = document.getElementById("playerWarning");
		var adultBox = document.getElementById("adultWarning");
		
		
		if(playerObject && alertBox && adultBox)
		{
			playerObject.style.visibility = "hidden";
			alertBox.className = "aviso";
			adultBox.className = "adulto";
		}		
	}

	function player_AdultAccept()
	{
		// Stores values in cookie
		CookieSave(cookieSession, "adult", true, ckDomain, expirationDate, ckModeWrite);
		
		// Displays back the player
		var playerObject = document.getElementById("playerHtml");
		var alertBox = document.getElementById("playerWarning");
		var adultBox = document.getElementById("adultWarning");
		
		if(playerObject && alertBox && adultBox)
		{
			playerObject.style.visibility = "visible";
			alertBox.className = "aviso none";
			adultBox.className = "adulto none";
		}
		
		// Starts playing
		adultAccepted = true;
		this.playMediaItem(this.currentObject);
	}
	
	function player_AdultRefuse(homeRedirect)
	{
		// Displays back the player
		var playerObject = document.getElementById("playerHtml");
		var alertBox = document.getElementById("playerWarning");
		var adultBox = document.getElementById("adultWarning");
		
		
		if(playerObject && alertBox && adultBox)
		{
			playerObject.style.visibility = "visible";
			alertBox.className = "aviso none";
			adultBox.className = "adulto none";
		}
		
		
		
		top.location.href = homeRedirect;
	}
	
	function player_AdultRefuseCustom()
	{
		var alertBox = document.getElementById("playerWarning");
		var oDvCustomControls = document.getElementById("customControls");
		
		alertBox.className = "aviso none";
		oDvCustomControls.style.display = 'none';
		
	}
	
	function player_ShowLayerPremium()
	{
		var oDvLayerPremium = document.getElementById("layerPremium");
		var playerObject = document.getElementById("playerHtml");
		if(isCustomPrivate && oDvLayerPremium)
		{
			playerObject.style.visibility = "hidden";
			oDvLayerPremium.style.zIndex = '99999999';
			oDvLayerPremium.style.visibility = "visible";
		}	
	}
	
	//TODO: Fake, somente para compatibilidade, tendo q acertar para o playerCustom
	function player_PrintNextMedia()
	{
		// Prints the "next video" display
		var obj = document.getElementById('nextVideoTicker');
		if(obj)
		{
			if(playerTerra && this.currentPosition>=0)
			{	
				var nextItem;
				var nextPos = -1;
				var nextRelated = -1;
				var maxPos = this.currentPlaylist.getCount() - 1;
				var maxRelated = this.currentPlaylist.getItem(this.currentPosition).relateds.length - 1;
				if(maxPos>=0)
				{
					// Checks if it's playing a regular item
					if(this.currentPosition<maxPos)
					{
						nextPos = this.currentPosition+1;
						nextItem = playlistTerra.getItem(nextPos);
					}
					else
					{
						// Checks if it's a related item
						if(this.currentPosition==maxPos && this.currentRelated<maxRelated)
						{
							nextPos = this.currentPosition;
							nextRelated = this.currentRelated+1;
							nextItem = this.currentPlaylist.getItem(nextPos).relateds[nextRelated];
							checkcustom = true;
						}
					}
				}
				if(nextItem)
				{
					obj.innerHTML = '<a style=cursor:hand onclick="playerPlayNextVideoItem(' + nextPos + ',' + nextRelated + ')"><strong>' + Translate('NEXT_ITEM') + '</strong>' + ': ' + nextItem.title + '</a>';
				}
				else
				{
					obj.innerHTML = '';
				}
			}
			else
			{
				obj.innerHTML = '';
			}
		}
	 }
	
	function player_BandwidthTest(forceTest)
	{
		// Attempts to load from cookie
		var bandwidth = CookieRestore(cookieSettings, "bandwidth");

		if(bandwidth && !forceTest)
		{
			// Loaded from cookie
			Verbose('Bandwidth loaded from cookie: ' + bandwidth);
			this.currentBandwidth = parseInt(bandwidth,10);
			this.playUrl(this.bandwidthTestFinishedUrl);
		}
		else
		{
			// Changes layout		
			var playerObject = document.getElementById("playerHtml");
			var alertBox = document.getElementById("playerWarning");
			var bandBox = document.getElementById("bandWarning");
			
			if(playerObject && alertBox && bandBox)
			{
				playerObject.style.visibility = "hidden";
				alertBox.className = "aviso";
				bandBox.className = "banda";
			}

			// Execute test
			Verbose('Starting bandwidth test');
			this.bandwidthTester.test(new Function('bandwidth','playerTerra.bandwidthTestFinished(bandwidth)'));
		}
	}
	
	function player_BandwidthTestFinished(bandwidth)
	{
		Verbose('Bandwidth test result: ' + bandwidth + 'kbps');

		// Restores layout		
		var playerObject = document.getElementById("playerHtml");
		var alertBox = document.getElementById("playerWarning");
		var bandBox = document.getElementById("bandWarning");

		if(playerObject && alertBox && bandBox)
		{
			playerObject.style.visibility = "visible";
			alertBox.className = "aviso none";
			bandBox.className = "banda none";
		}
		
		// Write bandwidth in cookie		
		CookieSave(cookieSettings, "bandwidth", bandwidth, ckDomain, expirationDate, ckModeWrite);
		
		this.currentBandwidth = bandwidth;
		this.playUrl(this.bandwidthTestFinishedUrl);
	}
	
	function player_BandwidthBufferLimit()
	{
		if(!this.bufferingNotified)
		{
			Verbose('Bandwidth limit reached');
			
			// Marks that we already notified it once
			this.bufferingNotified = true;

			// Removes control flag	
			this.bufferingLimitReached = true;
			
			// Loads current degradation level
			var cookieValue = cookieManager.getValue('bandwidthDegradation');
			if(cookieValue==null || cookieValue=='')
			{
				cookieValue = 0;
			}
			else
			{
				cookieValue = parseInt(cookieValue);
			}
			
			// Increments degradation level
			cookieManager.setValue('bandwidthDegradation',cookieValue+1);
			Verbose('Degradation level increased to ' + (cookieValue+1));
		}
	}
}

// ************************************************************************************************
// *** Detects if wm player is installed
// ************************************************************************************************
function GetPlayerTypeFlash()
{	
	if (pluginlist.indexOf("Flash")!=-1)
	{
		return(playerType.Flash);
	}	
	else
	{
		return (playerType.Unsupported);
	}
}


//This script detects the following:
//Flash
//Windows Media Player
//Java
//Shockwave
//RealPlayer
//QuickTime
//Acrobat Reader
//SVG Viewer
var agt=navigator.userAgent.toLowerCase();
var ie  = (agt.indexOf("msie") != -1);
var ns  = (navigator.appName.indexOf("Netscape") != -1);
var op = (navigator.appName.indexOf("Opera") != -1);
var win = ((agt.indexOf("win")!=-1) || (agt.indexOf("32bit")!=-1));
var mac = (agt.indexOf("mac")!=-1);

if (ie && win) {
	pluginlist = detectIE("ShockwaveFlash.ShockwaveFlash.1","Shockwave Flash");
	//pluginlist += detectIE("Adobe.SVGCtl","SVG Viewer");
	//pluginlist += detectIE("SWCtl.SWCtl.1","Shockwave Director");
	//pluginlist += detectIE("rmocx.RealPlayer G2 Control.1","RealPlayer");
	//pluginlist += detectIE("QuickTimeCheckObject.QuickTimeCheck.1","QuickTime");
	//pluginlist += detectIE("MediaPlayer.MediaPlayer.1","Windows Media Player");
	//pluginlist += detectIE("PDF.PdfCtrl.5","Acrobat Reader");*/
}

if (op || ns || !win) {
	nse = ""; for (var i=0;i<navigator.mimeTypes.length;i++) 
	nse += navigator.mimeTypes[i].type.toLowerCase();
	
	pluginlist = detectNS("image/svg-xml","SVG Viewer") + 
	detectNS("application/x-director","Shockwave Director") + 
	detectNS("application/x-shockwave-flash","Shockwave Flash") + 
	detectNS("audio/x-pn-realaudio-plugin","RealPlayer") + 
	detectNS("video/quicktime","QuickTime") + 
	detectNS("application/x-mplayer2","Windows Media Player") + 
	detectNS("application/pdf","Acrobat Reader");
	
	
}

function detectIE(ClassID,name) { 
 result = false; document.write('<SCRIPT LANGUAGE=VBScript>\n on error resume next \n result = IsObject(CreateObject("' + ClassID + '"))<\/SCRIPT>\n');
	if (result) 
		return name+','; 
	else 
		return ''; 
}

function detectNS(ClassID,name) {
	n = ""; 

	if(navigator.mimeTypes[ClassID])
	{
		if (nse.indexOf(ClassID) != -1) 
			if (navigator.mimeTypes[ClassID].enabledPlugin != null) 
				n = name+","; 
		return n; 
	}
}

pluginlist += navigator.javaEnabled() ? "Java," : "";
if (pluginlist.length > 0) 
	pluginlist = pluginlist.substring(0,pluginlist.length-1);

//SAMPLE USAGE- detect "Flash"
//if (pluginlist.indexOf("Flash")!=-1)
//document.write("You have flash installed")

// ********************************************************************************
// Initialization
// ********************************************************************************
function InitializeFlash()
{
	// Player
	playerTerra = new PlayerTerraFlash('playerHtml');	
	// Starts playback
	playerTerra.playMediaItem(currentMedia);

	objCustom = document.getElementById("CustomPlayer");
	var initVol = 50;
	var bkpVol = 50;

	//set initial volume parameters
	if(!objCustom)
	{
	
		initVol = CookieRestore(cookieSession, "endVolValue", ckModeWrite);
		bkpVol = CookieRestore(cookieSession, "valorBkp", ckModeWrite);	
	
		initVol = initVol != null ? initVol : 50;
			
		tmpMute = CookieRestore(cookieSession, "muteActive", ckModeWrite);		
		if(parseBool(tmpMute))
		{
			bkpVol = initVol;
			initVol = 0;
		}
	}else{
		if(customVolume)
		{
			initVol = customVolume;
			bkpVol = customVolume;
		}
		if(enableCustomMute)
		{
			initVol = 0;
		}
	}
	SetVolumeToPlayer(initVol, bkpVol);
	
	if(isPlayerCustom)
	{
		// Show Layer Premium
		playerTerra.showLayerPremium();
	}
}

// Call Flash Texts Translation (flash call)
function SetVolumeToPlayer(vol, volBkp){
	var obj = document.getElementById('playerHtml');		
		obj.setVolumeToPlayer(vol, volBkp);
}

function setVolumeToCookie(endVolValue, valorBkp){
	cookieManager.setValue("endVolValue", endVolValue);
	cookieManager.setValue("valorBkp", valorBkp);
}

function InitializeTranslationFlash()
{
	setTimeout("TranslatingFlash()",1000);
}

function TranslatingFlash(){
	setTimeout("TranslatingFlashTimed()",1000);
}

function TranslatingFlashTimed(){
	try
	{
		// Sets translated texts
		var obj = document.getElementById('playerHtml');
		if(obj)
		{
			obj.translateData(Translate('MUTE'),Translate('FULLSCREEN'),Translate('NEXT_ITEM'),Translate('LOADING'), Translate('PLAY_AFTER_BUFFER'));
		}

		flashMute = Translate('MUTE');
		flashFullScreen = Translate('FULLSCREEN');
		flashNextItem = Translate('NEXT_ITEM');
		flashLoading = Translate('LOADING');
		flashPlayAfterBuffer = Translate('PLAY_AFTER_BUFFER');
	}catch(e){
		setTimeout("TranslatingFlashTimed()",1000);
	}
}

function PlayedAdFlash()
{
	//Set UVTag (AD)
	if(playerTerra)
	{
		if(playerTerra.currentObject)
		{
			if(!flashUvTagAdLoaded)
			{
				uvTagFrameCall(playerTerra.currentObject.isLive, true, true);
				flashUvTagAdLoaded = true;
			}
		}
	}

	// Custom start script for ad
	var obj = playerTerra.currentAdObject;
	if(obj && obj.startScript && obj.startScript!='')
	{		
		Verbose("Start of video script: " + obj.startScript);
		eval(obj.startScript);
	}
	
	playerTerra.resetPlayedVideoCount(); // Resets the frequency counter	
	
	playerTerra.playingAd = true;
}

function PlayedVideoFlash()
{
	//Set UVTag
	if(playerTerra)
	{
		if(playerTerra.currentObject)
		{
			if(!flashUvTagOdLoaded)
			{
				uvTagFrameCall(playerTerra.currentObject.isLive, false, true);
				flashUvTagOdLoaded = true;
			}
		}
	}

	// Custom end script for ad
	var obj = playerTerra.currentAdObject;
	if(obj && obj.endScript && obj.endScript!='')
	{		
		Verbose("End of video script: " + obj.endScript);
		eval(obj.endScript);
	}

	// Custom start script for video
	obj = playerTerra.currentObject;
	if(obj && obj.startScript && obj.startScript!='')
	{
		Verbose("Start of video script: " + obj.startScript);
		eval(obj.startScript);
	}

	playerTerra.playingAd = false;
	
	var objRel = document.getElementById('relatedFlash');	

	if (objRel == null)
	{	
	 playerTerra.incrementPlayedVideoCount(); // Increments the frequency counter
	}
}

function FlashVideoComplete()
{
	objCustom = document.getElementById("CustomPlayer");
	
	if(!objCustom)
	{
		if(DisplayRelatedUIatTTV)
		{
			ShowRelatedsFlashBox();
		}
		else
		{
			if(nextItemUrl != '')
			{
				this.location = nextItemUrl;
			}
		}
	}
	else
	{
		if (!disableRelated)
		{
			ShowRelatedsFlashBox();
		}	   	
	   	else
	   	{
			if(playerpreview3)
			{
				var urlHasFlash = currentMedia.urlFlash!='';
				var oDvLayer3 = document.getElementById("detailsLayer3");
				
				if(urlHasFlash)
				{
					document.getElementById("CustomPlayer").className="player Flash details";
				}
				else
				{
					document.getElementById("CustomPlayer").className="player details";
				}
				
				if(oDvLayer3)
				{
					oDvLayer3.style.display='block';
				}
			}
		}
	}  
}

function NextVideoFlash()
{
	PlayNext();
}

// ********************************************************************************
// Player rendering
// ********************************************************************************
function RenderFlash()
{
	if(currentContentIsWide) {
		document.write('<object id="playerHtml" class="playerFlash" type="application/x-shockwave-flash" data="/swf/player_wide.swf?videoMode=' + playerLayout + '&whiteLabel=' + whiteLabel + '" width="'+ playerWidthFull +'" height="' + playerHeightFull + '">');
		document.write('<param name="movie" value="/swf/player_wide.swf?videoMode=' + playerLayout + '&whiteLabel=' + whiteLabel + '" />');
		
		var holderObj = document.getElementById('playerHolder');
		if(holderObj)
		{
			holderObj.className = 'videoContent wide';
		}
					
	}
	else {
		document.write('<object id="playerHtml" class="playerFlash" type="application/x-shockwave-flash" data="/swf/player.swf?videoMode=' + playerLayout + '&whiteLabel=' + whiteLabel + '" width="'+ playerWidthFull +'" height="' + playerHeightFull + '">');
		document.write('<param name="movie" value="/swf/player.swf?videoMode=' + playerLayout + '&whiteLabel=' + whiteLabel + '" />');
	}
	document.write('<param name="allowFullScreen" value="true" />');
	document.write('<param name=\"quality\" value=\"high\" />');	
	document.write('<param name="allowScriptAccess" value="always" />');
	document.write('<param name="wmode" value="transparent" />');
	document.write('</object>');	
}

// for player custom
function RenderFlashCustom(path)
{
	path += '?path=' + functionSwfUrl;
	if(disableAutoPlay)
	{
		path += '&initPaused=1';
	}
	if(whiteLabel == 1)
	{
		path += '&whiteLabel=1';
	}

	document.write('<object id="playerHtml" class="playerFlash" type="application/x-shockwave-flash" data="' + path + '" width="100%" height="100%">');
	document.write('<param name="movie" value="' + path + '" />');
	document.write('<param name="allowFullScreen" value="true" />');
	document.write('<param name=\"quality\" value=\"high\" />');
	document.write('<param name="allowScriptAccess" value="always" />');
	document.write('<param name="wmode" value="transparent" />');
	document.write('</object>');
}

// Disables uniqueUrl for player
uniqueUrl = false;
adultAccepted = false;

function PlayerTerraFlash(playerObjName, type)
{
	// ************************************************************************************************
	// *** Initialization
	// ************************************************************************************************

	// Fields
	// ******
	this.currentPlaylist = null;
	this.type = 6;
	this.player = true; //null;
	this.playState = new PlayState();
	
	// ************************************************************************************************
	// *** Interface
	// ************************************************************************************************	
	 
	// Methods
	this.reset = player_Reset;
	this.getCurrentMedia = player_GetCurrentMedia;
	this.getCurrentInternalMedia = player_GetCurrentInternalMedia;
	this.play = player_Play;
	this.playUrl = player_PlayUrl;
	this.playMediaItem = player_PlayMediaItem;
	this.stop = player_Stop;
	this.mute = player_Mute;
	this.getBitrate = player_GetBitrate;
	this.setVolume = player_SetVolume;
	this.syncVolume = player_SyncVolume;
	this.increaseVolume = player_IncreaseVolume;
	this.decreaseVolume = player_DecreaseVolume;
	this.maxVolume = player_MaxVolume;
	this.sliderVolume = player_SliderVolume;
	this.fullScreen = player_FullScreen;
	this.getPlayState = player_GetPlayState;
	this.setPosition = player_SetPosition;
	this.syncPosition = player_SyncPosition;
	this.adPost = player_AdPost;
	this.adCallback = player_AdCallback;
	this.adMonitor = player_AdMonitor;
	
	this.showLayerPremium = player_ShowLayerPremium;
	
	// Ad frequency controls
	this.getPlayedVideoCount = player_GetPlayedVideoCount;
	this.resetPlayedVideoCount = player_ResetPlayedVideoCount;
	this.incrementPlayedVideoCount = player_IncrementPlayedVideoCount;

	// Adult content methods
	this.adultContent = player_AdultContent;
	this.adultAccept = player_AdultAccept;
	this.adultRefuse = player_AdultRefuse;
	this.adultRefuseCustom = player_AdultRefuseCustom;
	
	// Bandwidth test methods
	this.bandwidthTest = player_BandwidthTest;
	this.bandwidthTestFinished = player_BandwidthTestFinished;
	this.bandwidthBufferLimit = player_BandwidthBufferLimit;

	// Event Handlers
	this.updateTimeInfo = player_UpdateTimeInfo;
	this.updatePositionSlider = player_UpdatePositionSlider;
	this.updatePlayPauseButton = player_updatePlayPauseButton;
	this.updateState = player_UpdateState;
	this.currentMediaChange = player_CurrentMediaChange;
	this.moveToNextMedia = player_MoveToNextMedia;
	
	// Stores information for the current media
	this.currentPosition = -1;
	
	// Informs if the current stop was a manual or not
	this.manualStop = true;
	
	// Informs if the currently playing video is an ad
	this.playingAd = false;
	
	// Objects being played
	this.currentObject = null;
	this.currentAdObject = null;

	// Blocks further ad playback after video start, for coherency with Flash player
	this.adBlock = false;
	
	// Management to handle problems in the adserver
	this.adLoadStart = null;
	this.adMonitorTimer = null;

	// Informs if the currently playing video is a related
	this.playingRelated = false;
	this.currentRelated = -1;
	
	// Informs if repeat is enabled or not
	this.repeat = false;
	
	// Adult video settings
	this.beforeDiscContent = -1;
	
	// Bandwidth test settings
	this.currentBandwidth = 0;
	this.bandwidthTestFinishedUrl = null;
	
	// Buffering controls
	this.bufferingTimes = new Array();
	this.bufferingLimitReached = false;
	this.bufferingNotified = false;
	this.bufferingIgnoreNext = true;
	
	// ************************************************************************************************
	// *** Implementation
	// ************************************************************************************************

	// Resets player to "stopped" state
	function player_Reset()
	{
		// Compatibility only
	}

	// Gets the current media index
	function player_GetCurrentIndex()
	{
		if(this.playingRelated)
		{
			return(-1);
		}
		else
		{
			return (this.currentPosition);
		}
	}
	
	// Gets the current media ("visible", doesn't include ads)
	function player_GetCurrentMedia()
	{
		return (this.currentObject);
	}

	// Gets the current media ("internal", include ads)
	function player_GetCurrentInternalMedia()
	{
		if(this.playingAd)
		{
			return (this.currentAdObject);
		}
		else
		{
			return (this.currentObject);
		}
	}
	
	function player_PlayUrl(url, adUrl)
	{
		Verbose('play url: ' + url);
		try
		{
			var obj = document.getElementById('playerHtml');
			if(adUrl=='')
			{
				if(nextItemTitle=='')
				{
					obj.setVideoData('noAd', url, 'noVideo');
				}
				else
				{
					obj.setVideoData('noAd', url, nextItemTitle);
				}
			}
			else
			{
				if(nextItemTitle=='')
				{
					obj.setVideoData(adUrl, url, 'noVideo');
				}
				else
				{
					obj.setVideoData(adUrl, url, nextItemTitle);
				}
			}
		}
		catch(e)
		{
			//alert('Exception calling method on flash: ' + e);
			window.setTimeout("playerTerra.playUrl('" + url + "','" + adUrl + "');",1000);
		}
	}

	// Plays the current media item
	function player_Play()
	{
		var obj = document.getElementById('playerHtml');
		if(obj)
		{
			obj.playAgain();
		}
	}
	
	// Plays a specific playlist item
	function player_PlayMediaItem(mi)
	{		
		this.currentObject = mi;
		if(this.currentObject)
		{			
			
			if(this.currentObject.isAdult && !CookieRestore(cookieSession, "adult") && !adultAccepted)
			{				
				this.adultContent();
				return;
			}			
		
			// Gets the number of videos played since the last ad
			var videoCount = this.getPlayedVideoCount();
						
			// Quick fix to prevent ad from playing multiple times without reloading
			// Used to make the behavior between WM and Flash coherent
			if(!this.adBlock && allowVideoAd)
			{			
				// Checks if it's time to play an ad
				if(this.currentObject.adFrequency>0 && !this.playingAd)
				{
				//alert(videoCount % this.currentObject.adFrequency);
					if(videoCount % this.currentObject.adFrequency == 0)
					{	
						this.adPost(this.currentObject);
						return;
					}
				}
			}
			
			// Plays the video
			var url = this.currentObject.urlFlash;
			if(url)
			{
				this.adBlock = true;
				this.playingAd = false;
				this.playUrl(url,'');
			}									
		}
	}	
	
	// Stops player
	function player_Stop() 
	{
		// Compatibility only
	}	
	
	// Mute
	function player_Mute()
	{
		// Compatibility only
	}	
	
	// Gets the current bitrate in kbps
	function player_GetBitrate()
	{
		// Compatibility only
	}
	
	// Sets the player's volume
	function player_SetVolume(volume)
	{
		// Compatibility only
	}
		
	// Increases player volume by 10
	function player_IncreaseVolume()
	{
		// Compatibility only
	}
	
	// Decreases player volume by 10
	function player_DecreaseVolume()
	{
		// Compatibility only
	}	

	// Sets the volume to max
	function player_MaxVolume()
	{
		// Compatibility only
	}

	// Sets the volume to the slider volume
	function player_SliderVolume()
	{
		// Compatibility only
	}
	
	// Syncs the player slider with the slider bar
	function player_SyncVolume()
	{
		// Compatibility only
	}
	
	// Full screen	
	function player_FullScreen()
	{
		// Compatibility only
	}

	// Retrieves the current player playstate	
	function player_GetPlayState()
	{
		if(metricsFlash)
		{
			return metricsFlash.GetPlaystate();
		}
	}
	
	// Sets the current position
	function player_SetPosition()
	{
		// Compatibility only
	}
	
	// Syncs the player slider with the slider bar
	function player_SyncPosition()
	{
		// Compatibility only
	}
	
	// Resizes the player
	function player_Resize(width, height)
	{
		// Compatibility only
	}

	//
	// AD FREQUENCY CONTROLS
	//
	function player_IncrementPlayedVideoCount()
	{
		cookieManager.setValue("playedVideoCount", this.getPlayedVideoCount()+1);
	}

	function player_ResetPlayedVideoCount()
	{
		cookieManager.setValue("playedVideoCount", "0");
	}

	function player_GetPlayedVideoCount()
	{
		var value = cookieManager.getValue("playedVideoCount");
		if(value!=null && value!='')
		{
			value = parseInt(value);	
		}
		else
		{
			value = 0;
		}
		return(value);
	}

	//
	// EVENT HANDLERS
	//
	
	// Updates time info	
	function player_UpdateTimeInfo()
	{
		// Compatibility only
	}
	
	// Update position slider
	function player_UpdatePositionSlider()
	{
		// Compatibility only
	}
	
	// Updates the play/pause button
	function player_updatePlayPauseButton()
	{
		// Compatibility only
	}
		
	// Event handler for playstate
	function player_UpdateState()
	{
		// Compatibility only
	}
	
	// Function to be called on media change
	function player_CurrentMediaChange()
	{
		// Compatibility only
	}

	// Moves to the next media when the current one stops	
	function player_MoveToNextMedia()
	{
		// Compatibility only
	}
	
	function player_AdPost(media)
	{
		// Creates the iframe
		var iframe = document.getElementById('videoAdFrame');
		if(!iframe)
		{
			iframe = document.createElement('iframe');
			iframe.id = 'videoAdFrame';
			iframe.frameBorder = 0;
			iframe.height = 0;
			iframe.width = 0;
			document.body.appendChild(iframe);
		}
		
		// Replaces the "random part in the url"
		UpdateRandom();
		var postUrl = new String(media.videoadurl);
		postUrl = postUrl.replace("#random#",currentRandom);
		postUrl = postUrl.replace("%23random%23",currentRandom); // Escaped
		
		// Logs information
		Verbose("Requesting Ad using URL: " + postUrl);
		
		// Posts to the iframe
		iframe = (iframe.frameElement) ? iframe.frameElement : iframe;
		iframe.setAttribute("src", postUrl);
		
		// Starts the monitor
		this.adLoadStart = (new Date()).getTime();
		this.adMonitor();
	}
	
	function player_AdCallback(mi)
	{		
		// Clears the monitor timer
		window.clearTimeout(this.adMonitorTimer);

		var adUrl = mi.urlFlash;
		this.playingAd = true;
		
		// Logs callbacl information
		Verbose("Ad received, playback URL: " + adUrl);

		// Stores ad for later use
		this.currentAdObject = mi;

		// Video url
		var videoUrl = this.currentObject.urlFlash;			
		this.playUrl(videoUrl,adUrl);
		//window.setTimeout("playerTerra.playUrl('" + videoUrl + "','" + adUrl + "');",1000);
	}

	function player_AdMonitor()
	{
		if((new Date()).getTime()-this.adLoadStart > externalAdTimeout * 1000)
		{
			// Prevents the iframe from proceeding
			var iframe = document.getElementById('videoAdFrame');
			if(iframe)
			{
				iframe = (iframe.frameElement) ? iframe.frameElement : iframe;
				iframe.setAttribute("src","");
			}
			
			Verbose("Ad timeout, proceeding to video playback");
			
			// Proceeds to the video itself
			this.playingAd = true;
			this.playMediaItem(this.currentObject);
		}
		else
		{
			this.adMonitorTimer = window.setTimeout('playerTerra.adMonitor()',1000)
		}
	}
	
	function player_AdultContent()
	{
		var playerObject = document.getElementById("playerHtml");
		var alertBox = document.getElementById("playerWarning");
		var adultBox = document.getElementById("adultWarning");
		
		
		if(playerObject && alertBox && adultBox)
		{
			playerObject.style.visibility = "hidden";
			alertBox.className = "aviso";
			adultBox.className = "adulto";
		}		
	}

	function player_AdultAccept()
	{
		// Stores values in cookie
		CookieSave(cookieSession, "adult", true, ckDomain, expirationDate, ckModeWrite);
		
		// Displays back the player
		var playerObject = document.getElementById("playerHtml");
		var alertBox = document.getElementById("playerWarning");
		var adultBox = document.getElementById("adultWarning");
		var playerCust = document.getElementById("CustomPlayer");
		
		if(playerObject && alertBox && adultBox)
		{
			playerObject.style.visibility = "visible";
			alertBox.className = "aviso none";
			adultBox.className = "adulto none";
		}				
		
		// Starts playing
		adultAccepted = true;
		this.playMediaItem(this.currentObject);
	}
	
	function player_AdultRefuse(homeRedirect)
	{
		// Displays back the player
		var playerObject = document.getElementById("playerHtml");
		var alertBox = document.getElementById("playerWarning");
		var adultBox = document.getElementById("adultWarning");
		
		if(playerObject && alertBox && adultBox)
		{
			playerObject.style.visibility = "visible";
			alertBox.className = "aviso none";
			adultBox.className = "adulto none";
		}
		top.location.href = homeRedirect;
	}
	
	function player_AdultRefuseCustom()
	{
		var alertBox = document.getElementById("playerWarning");
		var oDvCustomControls = document.getElementById("customControls");
		
		alertBox.className = "aviso none";
		oDvCustomControls.style.display = 'none';
		
	}
	
	function player_ShowLayerPremium()
	{
		var oDvLayerPremium = document.getElementById("layerPremium");
		var playerObject = document.getElementById("playerHtml");
		if(isCustomPrivate && oDvLayerPremium)
		{
			playerObject.style.visibility = "hidden";
			oDvLayerPremium.style.zIndex = '99999999';
			oDvLayerPremium.style.visibility = "visible";
		}
	}
	
	function player_BandwidthTest(forceTest)
	{
		// Compatibility only
	}
	
	function player_BandwidthTestFinished(bandwidth)
	{
		// Compatibility only
	}
	
	function player_BandwidthBufferLimit()
	{
		// Compatibility only
	}	
}
function MetricsFlash(variableName, flashName){
	this.id = variableName;
	this.flash = flashName;
	this.obj = null;
}

MetricsFlash.prototype.CheckFlash = function(){
	// Not loaded yet, attempts loading
	if(!this.obj)	{
		if (navigator.appName.indexOf("Microsoft") != -1){
			this.obj = window[this.flash];
		}else{
			this.obj = document[this.flash];
		}
		try{
			// Calls one of the functions to make sure the flash has loaded
			this.obj.metrics_GetVersion()	
		}catch(e){
			// Not ready yet
			this.obj = null;
		}
	}
	if(this.obj){
		return(true);
	}else{
		return(false);
	}
}

MetricsFlash.prototype.GetVersion = function(){
	if(this.CheckFlash()){
		return(this.obj.metrics_GetVersion());
	}
	return('');
}

MetricsFlash.prototype.GetDuration = function(){
	if(this.CheckFlash()){
		return(this.obj.metrics_GetDuration());
	}
	return(-1);
}

MetricsFlash.prototype.GetPosition = function(){
	if(this.CheckFlash()){
		return(this.obj.metrics_GetPosition());
	}
	return(-1);
}

MetricsFlash.prototype.GetBitrate = function(){
	if(this.CheckFlash()){
		return(this.obj.metrics_GetBitrate());
	}
	return(-1);
}

MetricsFlash.prototype.GetMaxBitrate = function(){
	return(this.GetBitrate());
}

MetricsFlash.prototype.GetMinBitrate = function(){
	return(this.GetBitrate());
}

MetricsFlash.prototype.GetBitrateSwitches = function(){
	return(0);
}

MetricsFlash.prototype.GetMediaUrl = function(){
	if(this.CheckFlash()){
		return(this.obj.metrics_GetMediaUrl());
	}
	return('');
}

MetricsFlash.prototype.GetPercentPlayed = function(){
	if(this.CheckFlash()){
		return(this.obj.metrics_GetPercentPlayed());
	}
	return('');
}

MetricsFlash.prototype.GetPlaystate = function(){
	if(this.CheckFlash()){
		return(this.obj.metrics_GetPlaystate());
	}
	return('');
}

MetricsFlash.prototype.GetBufferingCount = function(){
	if(this.CheckFlash()){
		return(this.obj.metrics_GetBufferingCount());
	}
	return(-1);
}

MetricsFlash.prototype.GetBufferingTimeFirst = function(){
	if(this.CheckFlash()){
		return(this.obj.metrics_GetBufferingTimeFirst());
	}
	return(-1);
}

MetricsFlash.prototype.GetBufferingTimeTotal = function(){
	if(this.CheckFlash()){
		return(this.obj.metrics_GetBufferingTimeTotal());
	}
	return(-1);
}

MetricsFlash.prototype.GetMaxBandwitdh = function(){
	if(this.CheckFlash()){
		return(this.obj.metrics_GetMaxBandwitdh());
	}
	return(-1);
}

MetricsFlash.prototype.GetMinBandwitdh = function(){
	if(this.CheckFlash()){
		return(this.obj.metrics_GetMinBandwitdh());
	}
	return(-1);
}

MetricsFlash.prototype.GetAvgBandwitdh = function(){
	if(this.CheckFlash()){
		return(this.obj.metrics_GetAvgBandwitdh());
	}
	return(-1);
}

MetricsFlash.prototype.GetAvailBandwitdh = function(){
	if(this.CheckFlash()){
		return(this.obj.metrics_GetAvailBandwitdh());
	}
	return(-1);
}

MetricsFlash.prototype.AddPlaystateChangeHandler = function(functionName){
	if(this.CheckFlash()){
		this.obj.metrics_AddPlaystateChangeHandler(functionName);
		eval(functionName + '()');
	}else if(eval("typeof "+this.id)!="undefined"){
		window.setTimeout(this.id + '.AddPlaystateChangeHandler(\'' + functionName + '\')',50);
	}
}

MetricsFlash.prototype.RemovePlaystateChangeHandler = function(){
	if(this.CheckFlash()){
		this.obj.metrics_RemovePlaystateChangeHandler();
	}else if(eval("typeof "+this.id)!="undefined"){
		window.setTimeout(this.id + 'RemovePlaystateChangeHandler()',50);
	}
}
// ********************************************************************************
// Related rendering
// ********************************************************************************
function RenderFlashRelated()
{
	var cHtml = '';
	var urlParams = '';

	urlParams += '&titNextVideo=' + flashtitNextVideo;
	urlParams += '&titRelatedList=' + flashtitRelatedList;
	urlParams += '&playAgainTit=' + flashplayAgainTit;
	urlParams += '&videoName=' + flashVideoName;

	for(var i = 0; i < relatedList.length; i++)
	{
		urlParams += '&flashRelTitle' + (i+1) + '=' + relatedList[i].flashRelTitle;
		urlParams += '&flashRelThumb' + (i+1) + '=' + relatedList[i].flashRelThumb;
		urlParams += '&flashRelLink' + (i+1) + '=' + relatedList[i].flashRelLink;
		if(i==0) urlParams += '&flashRelChannel' + (i+1) + '=' + relatedList[i].flashRelChannel;
	}

	cHtml += '<object id="relatedFlash" type="application/x-shockwave-flash" data="' + relatedSwfUrl + '?timeCount=3&videoMode=' + playerLayout + urlParams + '" width="'+ playerWidthFull +'" height="' + playerHeightFull + '">';
	cHtml += '<param name="movie" value="' + relatedSwfUrl + '?timeCount=3&videoMode=' + playerLayout + urlParams + '" />';
	cHtml += '<param name="allowFullScreen" value="true" />';
	cHtml += '<param name="allowScriptAccess" value="always" />';
	cHtml += '<param name="wmode" value="transparent" />';
	cHtml += '</object>';

	var dvPlayerHostRelated = document.getElementById('playerHostRelated');
	//var dvPlayerHostRelated = document.getElementById('playerHostRelated_bkp');
	if(dvPlayerHostRelated)
	{
		dvPlayerHostRelated.innerHTML = cHtml;
	}
}

// ************************************************************************************************
// *** Player Type Enumeration
// ************************************************************************************************
function PlayerType ()
{
	this.Unsupported = 0;
	this.WindowsMedia = 1;
	this.Quicktime = 2;
	this.Silverlight = 3;
	this.WindowsMediaFirefox = 4;
	this.WindowsMediaFallback = 5;
	this.Flash = 6;
}

var playerType = new PlayerType();
// ************************************************************************************************
// Detects if a certain plugin is installed
// ************************************************************************************************
function HasPlugin(plugin)
{
	for(var i = 0; i < navigator.plugins.length; i++)
	{
		if(navigator.plugins[i].name.indexOf(plugin) != -1)
			return (true);
	}
	
	return (false);
}

// ************************************************************************************************
// Detects the user browser
// ************************************************************************************************
var BrowserDetect = {
	init: function () {
		this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
		this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "an unknown version";
		this.OS = this.searchString(this.dataOS) || "an unknown OS";
	},
	searchString: function (data) {
		for (var i=0;i<data.length;i++)	{
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			}
			else if (dataProp)
				return data[i].identity;
		}
	},
	searchVersion: function (dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) return;
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
	},
	dataBrowser: [
		{ 	string: navigator.userAgent,
			subString: "OmniWeb",
			versionSearch: "OmniWeb/",
			identity: "OmniWeb"
		},
		{
			string: navigator.userAgent,
			subString: "Chrome",
			identity: "Chrome",
			versionSearch: "rv"
		},
		{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari"
		},
		{
			prop: window.opera,
			identity: "Opera"
		},
		{
			string: navigator.vendor,
			subString: "iCab",
			identity: "iCab"
		},
		{
			string: navigator.vendor,
			subString: "KDE",
			identity: "Konqueror"
		},
		{
			string: navigator.userAgent,
			subString: "Firefox/3.0.6",
			identity: "Firefox 3.0.6"
		},
		{
			string: navigator.userAgent,
			subString: "Firefox/3.0.7",
			identity: "Firefox 3.0.7"
		},
		{
			string: navigator.userAgent,
			subString: "Firefox/3",
			identity: "Firefox 3"
		},
		{
			string: navigator.userAgent,
			subString: "Firefox",
			identity: "Firefox"
		},
		{
			string: navigator.vendor,
			subString: "Camino",
			identity: "Camino"
		},
		{		// for newer Netscapes (6+)
			string: navigator.userAgent,
			subString: "Netscape",
			identity: "Netscape"
		},
		{
			string: navigator.userAgent,
			subString: "MSIE",
			identity: "Explorer",
			versionSearch: "MSIE"
		},
		{
			string: navigator.userAgent,
			subString: "Gecko",
			identity: "Mozilla",
			versionSearch: "rv"
		},
		{ 		// for older Netscapes (4-)
			string: navigator.userAgent,
			subString: "Mozilla",
			identity: "Netscape",
			versionSearch: "Mozilla"
		}
	],
	dataOS : [
		{
			string: navigator.platform,
			subString: "Win",
			identity: "Windows"
		},
		{
			string: navigator.platform,
			subString: "Mac",
			identity: "Mac"
		},
		{
			string: navigator.platform,
			subString: "Linux",
			identity: "Linux"
		}
	]

};
BrowserDetect.init();

function GotoCheckPage(pluginName)
{
	var checkBrowser = false;
	var checkOS = false;
	
	// Fetches browser name ( "Firefox", "Safari", "Explorer" )
	var browser = BrowserDetect.browser;

	// Fetches os name
	var OS = BrowserDetect.OS;

	var paramPlayerCustom = '';
	if(document.getElementById('CustomPlayer'))
	{
		paramPlayerCustom = '&customPlayer=1';
		if(customStyle)
		{
			paramPlayerCustom += '&style=' + customStyle;
		}
		//paramPlayerCustom += '&contentid=' + mi.id;
	}

	var urlBack = ''
	urlBack = this.location.href.replace('?','^^');
	for(i=0;i<=10;i++)urlBack = urlBack.replace('&','||');

	// Redirects to check page
	this.location.href='/templates/checkBrowser.aspx?OS=' + OS + '&browser=' + browser + '&plugin=' + pluginName + paramPlayerCustom + '&urlback=' + urlBack;
}


// Object for bandwidth testing
function SpeedTester(objectName, numTests, fileUrl, fileSize)
{
	// element index for array fileUrl
	var imageTesteIndex = 0;
	
	// Object name
	this.objectName = objectName;

	// Number of tests to be run
	this.numTests = numTests;

	// Data of the test file	
	this.fileUrl = fileUrl;
	this.fileSize = fileSize;
		
	// Speed for each attempt will be stored here
	this.connectionSpeed = new Array();

	// Image used in the current test
	this.imageTest = null;

	// Stores the start and end times of each test
	this.startTest = null;
	this.endTest = null;
	
	// Stores the callback to be used on testing
	this.finishedCallback = null;
	this.statusUpdateCallback = null;

	// Methods
	this.test = speedTester_Test;
	this.testCallback = speedTester_TestCallback;
	this.loadUrlError = speedTester_LoadUrlError;

	function speedTester_Test(finishedCallback, statusUpdateCallback)
	{
				
		// Stores the callback method
		if(finishedCallback) this.finishedCallback = finishedCallback;
		if(statusUpdateCallback) this.statusUpdateCallback = statusUpdateCallback;
			
		// Stores the start time
		this.startTest = (new Date()).getTime();
			
		// Appens a timestamp to make sure the file won't be cached
		var url = this.fileUrl[imageTesteIndex] + '?ts=' + escape(this.startTest);
					
		// Loads the test image
		this.imageTest = new Image();
		this.imageTest.src = url;
			
		this.imageTest.onload = new Function(this.objectName + '.testCallback()');			
		this.imageTest.onerror = new Function(this.objectName + '.loadUrlError()');
			
	}

	function speedTester_TestCallback()
	{
		// Gets the end date
		this.endTest = (new Date()).getTime();

		// Gets the connection speed
		
		var bytes = this.fileSize;

		var seconds = (this.endTest - this.startTest) /1000 ; // transform milliseconds to seconds

		var connectionSpeedPart =  (((bytes/1024) * 8) / (seconds)); // transform size byte to bits
		
		this.connectionSpeed[this.connectionSpeed.length] = Math.floor(connectionSpeedPart); // to kilobits
				
		// Executes the required number of tests
		
		if(this.connectionSpeed.length<this.numTests)
		{
			// call status update
			this.statusUpdateCallback(((this.numTests-(this.numTests-this.connectionSpeed.length)) * 100) / this.numTests);
			this.test();	
		}
		else
		{
			// Gets the average speed of the tests
			var total = 0;
			for(var i=0;i<this.connectionSpeed.length;i++)
			{
				total += this.connectionSpeed[i];
			}

			var averageSpeed = Math.floor((total/this.connectionSpeed.length));
			
			// Calls the post-test action
			if(this.finishedCallback)
			{
				this.finishedCallback(averageSpeed);
			}
			
			// Clears test data
			this.connectionSpeed = new Array();
			this.imageTest = null;
			this.startTest = null;
			this.endTest = null;
			this.finishedCallback = null;
		}
	}		
	
	
	function speedTester_LoadUrlError()
	{
		// Next position for URLs Array		
		imageTesteIndex++;
		if ( imageTesteIndex <= this.fileUrl.length ) 
			this.test();	
	}	
	
}
function PlayerTester()
{
	// Bandwidth test methods	
	this.bandwidthTest = player_BandwidthTest;
	this.bandwidthTestStatusUpdate = player_BandwidthTestStatusUpdate;
	this.bandwidthTestFinished = player_BandwidthTestFinished;
	this.bandwidthBufferLimit = player_BandwidthBufferLimit;
	this.bandwidthBelowBufferLimit = player_BandwidthBelowBufferLimit;
	
	this.bandwidthTester = new SpeedTester('playerTester.bandwidthTester', sbrTestCount, sbrTestImage, sbrTestImageSize);

	// Bandwidth test settings
	this.currentBandwidth = 0;
	this.bandwidthTestFinishedUrl = null;

	// Loads bandwidth
	if(userBandwidth)
	{
		Verbose('Bandwidth loaded from cookie: ' + userBandwidth);
		this.currentBandwidth = parseInt(userBandwidth,10);
	}
						
	function player_BandwidthTest(forceTest)
	{			
		// verify d'ont exist saved cookie test
		var ttv_cookie_test = CookieRestore("ttv_cookie_test", "ttv_cookie");
		if ( ttv_cookie_test != 10 && !forceTest )
		{		
			this.currentBandwidth = userDefaultBandwidth; // from Web.Config
			CancelConfigBox(); // execute the video-player
			return;
		}
		
		// Attempts to load from cookie	
		var bandwidth = CookieRestore(cookieSettings, "bandwidth");
		
		if(bandwidth && !forceTest)
		{
			// Loaded from cookie
			Verbose('Bandwidth loaded from cookie: ' + bandwidth);
			this.currentBandwidth = parseInt(bandwidth,10);
		}
		else 
		{		
			// Changes layout
			var oDvConfigBox = document.getElementById('dvConfigBox');
			if(!oDvConfigBox) return;
			oDvConfigBox.style.display='block';

			var cHtml = '';
			
			
			cHtml += '<div class="ico"></div>';
			cHtml += '	<a style=\"cursor:pointer\" onclick="javascript:HideConfigBox()" title="' + Translate('CLOSE') + '" class=close>' + Translate('CLOSE') + '</a>';
			cHtml += '	<h3>' + Translate('CONFIG_TEST_TITLE') + '</h3>';
			cHtml += '	<h4>' + Translate('CONFIG_TEST_DESCRIPTION') + '</h4>';
			cHtml += '	<div class="loadBar">';
			cHtml += '		<span>';
			cHtml += '			<img src="/imagesES/spacer.gif" alt="' + Translate('LOADING') + '" style="width:1px;" id="imgLoadBarSpacer" />';
			cHtml += '		</span>';
			cHtml += '	</div>';
			cHtml += '	';
			oDvConfigBox.innerHTML = cHtml;
									
			if(sbrTestImage.length>0)
			{
				// Execute test
				Verbose('Starting bandwidth test');
				this.bandwidthTester.test(new Function('bandwidth','playerTester.bandwidthTestFinished(bandwidth)'), new Function('bandwidthstatusupdate','playerTester.bandwidthTestStatusUpdate(bandwidthstatusupdate)'));	
			}
		}

	}
	
	function player_BandwidthTestStatusUpdate(percentCompleted)
	{	
		var oImgLoadBar = document.getElementById('imgLoadBarSpacer');
		if(!oImgLoadBar) return;
		oImgLoadBar.style.width = (percentCompleted * 2) + 'px';
	}

	function player_BandwidthTestFinished(bandwidth)
	{		
		Verbose('Bandwidth test result: ' + bandwidth + 'kbps');

		// Restores layout
		var oDvConfigBox = document.getElementById('dvConfigBox');
		if(!oDvConfigBox) return;
		
		var underLimit = false;
		
		// verify if the bandwith detected is under the lower bandwidth configured
		if(sbrSpeeds.length > 0)
		{
			if(sbrSpeeds[0] > bandwidth)
			{
				//playerTester.bandwidthBelowBufferLimit();
				//return;
				underLimit = true;
			}
		}		
		
		oDvConfigBox.style.display='block';

		var cHtml = '<div class="ico"></div>';

		cHtml += '<a style=\"cursor:pointer\" onclick="javascript:HideConfigBox()" title="' + Translate("CLOSE") + '" class="close">' + Translate("CLOSE") + '</a>';
		cHtml += '<h3>' + Translate('CONFIG_RESULT_TITLE') +  ' ' + bandwidth + 'Kbps.</h3>';
		if(underLimit)
		{
			cHtml += '<p>' + Translate('CONFIG_ERROR_BELOW_LIMIT_DESCRIPTION') + '</p>';
		}else{
			cHtml += '<p>' + Translate('CONFIG_RESULT_DESCRIPTION') + '</p>';
		}
		cHtml += '<ul>';
		cHtml += '<form name="frmVelocidades">';
		for(var i=0;i<sbrSpeeds.length;i++)
		{
			cHtml += '	<li><input name="rbVelocidade" type="radio" value="' + sbrSpeeds[i] + '" /><label>' + sbrSpeeds[i] + 'Kbps</label></li>';
		}
		cHtml += '</form>';
		cHtml += '</ul>';
		cHtml += '<a style=\"cursor:pointer\" onclick="javascript:ConfirmConfigBox()" title="' + Translate('CONFIG_RESULT_CONFIRM') + '" class="btn"><strong>' + Translate('CONFIG_RESULT_CONFIRM') + '</strong></a>';
		cHtml += '<a style=\"cursor:pointer\" onclick="javascript:ShowConfigBox(true)" title="' + Translate('CONFIG_RESULT_AUTOCONFIG') + '" class="btn">' + Translate('CONFIG_RESULT_AUTOCONFIG') + '</a>';

		oDvConfigBox.innerHTML = cHtml;		
		
		CookieSave(cookieSettings, "bandwidth", bandwidth, ckDomain, expirationDate, ckModeWrite);
			
		this.currentBandwidth = bandwidth;
		PreSelectConfigBox(bandwidth);
		
		//this.playUrl(this.bandwidthTestFinishedUrl);
	}

	function player_BandwidthBufferLimit()
	{
		if(!playerTerra.bufferingNotified)
		{
			playerTerra.play();

			Verbose('Bandwidth limit reached');
			
			// Marks that we already notified it once
			playerTerra.bufferingNotified = true;

			// Removes control flag	
			playerTerra.bufferingLimitReached = true;

			// pop-up the config window
			var oDvConfigBox = document.getElementById('dvConfigBox');
			if(!oDvConfigBox) return;

			var cHtml = '<div class="ico"></div>';
			cHtml += '<a style=\"cursor:pointer\" onclick="javascript:HideConfigBox()" title=fechar class=close>fechar</a>';
			cHtml += '<h3>' + Translate('CONFIG_ERROR_TITLE') + ' ' + this.currentBandwidth + ' Kbps</h3>';
			cHtml += '<p>' + Translate('CONFIG_ERROR_DESCRIPTION') + '</p>';
			cHtml += '<a style=\"cursor:pointer\" onclick="javascript:ShowConfigBox(true)" title="' + Translate('CONFIG_ERROR_CONFIG') + '" class="btn"><strong>' + Translate('CONFIG_ERROR_CONFIG') + '</strong></a>';
			cHtml += '<a style=\"cursor:pointer\" onclick="javascript:CancelConfigBox()" title="' + Translate('CONFIG_ERROR_CANCEL') + '" class="btn">' + Translate('CONFIG_ERROR_CANCEL') + '</a>';

			oDvConfigBox.innerHTML = cHtml;
			oDvConfigBox.style.display='block';
		}
	}

	function player_BandwidthBelowBufferLimit()
	{
		if(playerTerra.getPlayState()==playerTerra.playState.playing)
		{
			// pause
			playerTerra.play();
		}

		Verbose('Bandwidth limit Below limit reached');

		// Marks that we already notified it once
		playerTerra.bufferingNotified = true;

		// Removes control flag	
		playerTerra.bufferingLimitReached = true;

		// pop-up the config window
		var oDvConfigBox = document.getElementById('dvConfigBox');
		if(!oDvConfigBox) return;

		var cHtml = '<div class="ico"></div>';
		cHtml += '<a style=\"cursor:pointer\" onclick="javascript:HideConfigBox()" title=fechar class=close>fechar</a>';
		cHtml += '<h3>' + Translate('CONFIG_ERROR_BELOW_LIMIT_TITLE') + ' ' + this.currentBandwidth + ' Kbps</h3>';
		cHtml += '<p>' + Translate('CONFIG_ERROR_BELOW_LIMIT_DESCRIPTION') + '</p>';
		cHtml += '<a style=\"cursor:pointer\" onclick="javascript:ShowConfigBox(true)" title="' + Translate('CONFIG_ERROR_CONFIG') + '" class="btn"><strong>' + Translate('CONFIG_ERROR_CONFIG') + '</strong></a>';
		cHtml += '<a style=\"cursor:pointer\" onclick="javascript:CancelConfigBox()" title="' + Translate('CONFIG_ERROR_CANCEL') + '" class="btn">' + Translate('CONFIG_ERROR_CANCEL') + '</a>';

		oDvConfigBox.innerHTML = cHtml;
		oDvConfigBox.style.display='block';
	}
}
// Objects
var playerTerra;

var ajaxManager = new AjaxManager("ajaxManager", false);
var ajaxTools = new AjaxTools();
var privateList = new Array();
var relatedList = new Array();

var isPlayerCustom = false;

var playerTester;

// Current content
var currentContent = 0;
var currentRelatedsFrom = 0;
var currentContentIsWide = false;

// Embed player-playlist
var embedPlayer = false;
var embedPlayerPlaylist = "";

// Current media object
var currentMedia;

// Player add queuing
var loadingMedia = false;
var loadingMediaQueue = new Array();

//search check
var search_check = false;

//custom volume
var customVolume = 50;
var enableCustomMute = false;
var VolumeSliderSize = 45;

//custom flash
var playerflashaddr;

// metrics flash
var metricsFlash;

// to control the retries calling the related contents
var retriesCallRelatedFlash = 0;

// flag to show or not the relateds windows
var enableShowRelatedWindow = true;

var enableCustomLoading = false;

// used to wide videos
var enableUpdateSize = false;

var flashMute = 'Mute';
var flashFullScreen = 'FullScreen';
var flashNextItem = 'Next Item';
var flashLoading = 'Loading';
var flashPlayAfterBuffer = 'play after buffer';

var flashplayAgainTit = '';
var flashtitNextVideo = '';
var flashtitRelatedList = '';
var flashplayingIn = '';
var usingFlash = false;

var flashVideoName = '';

var wmFallBackMode = false;

var isOlympicPlayer = false;

var defineLocation = '';

var whiteLabel = 0;

var flashUvTagOdLoaded = false;
var flashUvTagAdLoaded = false;

var relatedSwfUrl = '/swf/related.swf';
var functionSwfUrl = '';

var isCustomPrivate = false;

// ********************************************************************************
// Player rendering
// ********************************************************************************
function RenderPlayer(className)
{
	if(currentMedia)
	{
		var userHasFlash = enableFlash && (GetPlayerTypeFlash() > 0);

		// Automatic FallBack for Google Chrome
		if(enableChrome && BrowserDetect.browser == 'Chrome')
		{
			cookieFallBack = '1';
		}
		
		var userHasWm = (enableWmp || enableWmpMozilla || enableFallback) && (GetPlayerTypeWm() > 0);
		
		var urlHasFlash = currentMedia.urlFlash!='';
		var urlHasWm = currentMedia.urlWm!='';
		var objCustom = document.getElementById("CustomPlayer");
		
		if((!urlHasWm) && (!urlHasFlash))
		{
			// video not published
			if(EnableTrace || EnableVerbose)
			{
				Verbose('ERRO: nenhum MMedia relacionado ao content');
			}else{
				alert(Translate('VIDEO_NOT_PUBLISHED'));
				this.location.href = urlRedirectVideoNotPublished;
			}
			return;
		}

		if(userHasFlash && urlHasFlash)
		{
			usingFlash = true;
			if(!objCustom)
			{
				RenderFlash(className);
				RenderFlashRelated();
			}
			else
			{				
				RenderFlashCustom(playerflashaddr);
			}
		}
		else
		{
			usingFlash = false;
			if(userHasWm && urlHasWm)
			{
				if(document.getElementById('CustomPlayer'))
				{
					RenderWm(className);
				}
				else
				{
					RenderWm(className);
					RenderFlashRelated();
				}
			}
			else
			{
				// User is missing plugins
				if(urlHasFlash)
				{
					GotoCheckPage('flash');
				}
				else
				{
					GotoCheckPage('windowsmedia');
				}
			}
		}
	}
}

// ********************************************************************************
// Play link
// ********************************************************************************
var nextItemUrl = '';
var nextItemTitle = '';

function PlayNext()
{
	if(nextItemUrl!='' && !playerTerra.playingAd)
	{
		enableShowRelatedWindow = false;
		location.href = nextItemUrl;
	}
}

function PlayAgain()
{
	flashUvTagOdLoaded = false;
	flashUvTagAdLoaded = false;

	HideRelatedsBox();
	playerTerra.play();
	//var tmpMute = cookieManager.getValue("muteActive"); //playerTerra.player.getMute();
	//playerTerra.player.setMute(tmpMute);
	
	//if(tmpMute)
	//{
	//	setTimeout('playerTerra.mute()',1000);
	//}

	var dvPlayerHostRelated = document.getElementById('playerHostRelated');
	if(dvPlayerHostRelated)
	{
		dvPlayerHostRelated.innerHTML = '';
	}

}

// ********************************************************************************
// Related videos box WMV
// ********************************************************************************
var relatedsBoxVisible = false;
var relatedsBoxTimer = 0;
var relatedsBoxTimeout = 0;

function ShowRelatedsBox()
{
	if(enableShowRelatedWindow && allowRelated && relatedList.length > 0)
	{
		// returns from wide mode
		if(enableUpdateSize)
		{
			var holderObj = document.getElementById('playerHolder');
			if(holderObj)
			{
				if(playerTerra)
				{
					var currentInternal = playerTerra.getCurrentInternalMedia();
					if(currentInternal.isWide)
					{
						holderObj.className = 'videoContent';
						playerTerra.resize(480,360);
					}
				}
			}
		}

		RenderFlashRelated();

	    var player = document.getElementById('playerHtml');
		var objRel = document.getElementById('relatedFlash');
		var objPlayerHostRelated = document.getElementById('playerHostRelated');
		var urlHasFlash = currentMedia.urlFlash!='';
		
		if(urlHasFlash)
		{
			player.style.zIndex = -1;
			objPlayerHostRelated.style.zIndex = 999;
		}
		else
		{
			//player.style.visibility = 'hidden';
			AdaptationStyleOpera(true,'hidden');
			
		}

		if(objRel)
		{
			if(urlHasFlash)
			{
				objRel.style.zIndex = 999;
			}else{
				objRel.style.zIndex = 999;
				objRel.style.visibility = 'visible';	
			}
			
			if(objPlayerHostRelated)
			{
				objPlayerHostRelated.style.zIndex = 99999;
			}
		}
		setTimeout(CallRelatedFlash,10);
	}
}

function HideRelatedsBox()
{	
	// Hides the next videos box	
	var objRel = document.getElementById('relatedFlash');
	var objPlayerHostRelated = document.getElementById('playerHostRelated');
	var player = document.getElementById('playerHtml');
	var urlHasFlash = currentMedia.urlFlash!='';
	
	if(objRel && player)
	{
		objRel.style.zIndex = -1;
		if(objPlayerHostRelated)
		{
			objPlayerHostRelated.style.zIndex = -1;
		}

		if(urlHasFlash)
		{
			player.style.zIndex = 999;
		}else{
			//objRel.style.visibility = 'hidden';
			//player.style.visibility = 'visible';
			AdaptationStyleOpera(false,'visible');
			
		}
	}	
}

// ********************************************************************************
// Related videos box FLASH
// ********************************************************************************
 
 // Flash Video is complete (flash call)
 function ShowRelatedsFlashBox()
 {	
	if(enableShowRelatedWindow && allowRelated)
	{
		// returns from wide mode
		
				
		if(enableUpdateSize)
		{
			var holderObj = document.getElementById('playerHolder');
			if(holderObj)
			{
				if(playerTerra)
				{
					var currentInternal = playerTerra.getCurrentInternalMedia();
					if(currentInternal.isWide)
					{
						holderObj.className = 'videoContent';
						playerTerra.resize(480,360);
					}
				}
			}
		}

		RenderFlashRelated();
		
		var objRel = document.getElementById('relatedFlash');
		var objFla = document.getElementById('playerHtml');
		var objHost = document.getElementById('playerHostRelated');
		
		objHost.style.zIndex = 9;
		objRel.style.zIndex = 999;
		objFla.style.zIndex = -1;
		setTimeout(CallRelatedFlash,10);
	}
 }

 // Call Related (js call)
 function CallRelatedFlash()
 { 	
    var objRel = document.getElementById('relatedFlash');
    var objCustom = document.getElementById('CustomPlayer');   

    if(objRel)
    {
		if(typeof(FlashVideoSetRelated) == 'function')
		{
			if(!document.getElementById('CustomPlayer'))
			{
				if(retriesCallRelatedFlash < 5)
				{
					try{
						objRel.callRelatedFlash();
						retriesCallRelatedFlash = 0;
					}catch(e){
						retriesCallRelatedFlash++;
						setTimeout(CallRelatedFlash,400);
					}
				}
			}
		}
	}
 }
 
 // ActualVideoName (js call)
 function ActualVideoName(videoName)
 {	
	flashVideoName = videoName;
	/*
	var obj = document.getElementById('relatedFlash');
		obj.actualVideoName(videoName); */
 }

 // Translate Flash Texts (js call)
 function TranslateRelated(playAgainTit, titNextVideo, titRelatedList, playingIn)
 {	
	var obj = document.getElementById('relatedFlash');
		obj.translateRelatedData(playAgainTit, titNextVideo, titRelatedList, playingIn);
		
	flashplayAgainTit = playAgainTit;
	flashtitNextVideo = titNextVideo;
	flashtitRelatedList = titRelatedList;
	flashplayingIn = playingIn;
 }
 
 // Flash is loaded and ready (flash call)
 function InitializeRelatedFlash()
 {	
	if(typeof(FlashVideoSetRelated) == 'function')
	{
		FlashVideoSetRelated();
	}
 }

 // Send Parameters to Related (js call)
 function SetFlashRelatedData(flashRelTitle, flashRelThumb, flashRelLink, flashRelChannel, id)
 {
	try
	{
		//var obj = document.getElementById('relatedFlash');
	   	//obj.setRelatedData(flashRelTitle, flashRelThumb, flashRelLink, flashRelChannel, id);
		relatedList.push(new relatedData(flashRelTitle, flashRelThumb, flashRelLink, flashRelChannel, id));
	}
	catch(e)
	{
	}
 }

 function PlayAgainFlash()
 {	
 	var objRel = document.getElementById('relatedFlash');
	var objFla = document.getElementById('playerHtml');
	var objPlayerHostRelated = document.getElementById('playerHostRelated');
	
	
	if(objRel) objRel.style.zIndex = -1;
	if(objPlayerHostRelated) objPlayerHostRelated.style.zIndex = -1;
	if(objFla) objFla.style.zIndex = 999;
	currentMedia.urlFlash!='';

	if (currentMedia.urlFlash)
	{
		objFla.playAgain();
	}
	else
	{
		PlayAgain();
	}
}

// ********************************************************************************
// Banner
// ********************************************************************************
function RenderBanner(bannerUrl,bigBannerUrl,sponsorUrl,sponsor,expanded,wide)
{
	
	var msg = '';
	msg += 'RenderBanner called\n';
	msg += 'bannerUrl: ' + bannerUrl + '\n';
	msg += 'bigBannerUrl: ' + bigBannerUrl + '\n';
	msg += 'sponsorUrl: ' + sponsorUrl + '\n';
	msg += 'sponsor: ' + sponsor + '\n';
	msg += 'expanded: ' + expanded + '\n';
	msg += 'wide: ' + wide + '\n';
	Verbose(msg);

	var sponsorDiv = document.getElementById("sponsor1");
	if(sponsorDiv && sponsorUrl && sponsorUrl!='')
	{
		// Replaces the special values in the "random" for the url
		sponsorUrl = ApplyBannerParameters(sponsorUrl,sponsor);

		var html = '';
		html += "<h3><img src=\"" + sponsoredByUrl + "\" /></h3>";
		html += "<iframe src=\"" + sponsorUrl + "\" marginheight=\"0\" marginwidth=\"0\" topmargin=\"0\" leftmargin=\"0\" frameborder=\"no\" border=\"0\" scrolling=\"no\"></iframe>";
		sponsorDiv.innerHTML  = html;
	}

	var bannerDiv = document.getElementById("publicidade");
	var bigBannerDiv = document.getElementById("publicidadeBig");
	if(bannerDiv && bigBannerDiv && bannerUrl && bannerUrl!='')
	{
		// player resize enabled only for IE
		var bigBannerFrameWidth;
		var urlHasFlash = false;
		if(currentMedia) {		
			urlHasFlash = currentMedia.urlFlash!='';
		}		
		
		if( wide && (BrowserDetect.browser == "Explorer" || urlHasFlash) )		
		{
			bigBannerFrameWidth = 420;
		}
		else
		{
			bigBannerFrameWidth = 490;
		}
		
		bannerUrl = ApplyBannerParameters(bannerUrl,sponsor);
		bigBannerUrl = ApplyBannerParameters(bigBannerUrl,sponsor);

		var html = '';
		if(expanded)
		{		
			// Close button
			bannerDiv.innerHTML = '';
			bigBannerDiv.innerHTML = "<a id=\"bannerClose\" style=\"cursor:pointer\" onclick=\"ResizeBanner();return(false);\" title=\"" + Translate("CLOSE") + "\" class=\"close\">" + Translate("CLOSE") + " [X]</a>";

			// Two banners, with big banner visible
			bannerDiv.innerHTML += "<iframe id=\"bannerFrame\" src=\"" + bannerUrl + "\" width=\"150\" height=\"420\" marginheight=\"0\" marginwidth=\"0\" topmargin=\"0\" leftmargin=\"0\" frameborder=\"no\" border=\"0\" scrolling=\"no\"></iframe>";
			bigBannerDiv.innerHTML += "<iframe id=\"bigBannerFrame\" src=\"" + bigBannerUrl + "\" width=\"" + bigBannerFrameWidth + "\" height=\"420\" marginheight=\"0\" marginwidth=\"0\" topmargin=\"0\" leftmargin=\"0\" frameborder=\"no\" border=\"0\" scrolling=\"no\"></iframe>";

			bannerDiv.style.display = 'none';
			bigBannerDiv.style.display = '';
		}
		else
		{
			// Regular banner only
			bannerDiv.innerHTML = "<iframe src=\"" + bannerUrl + "\" width=\"150\" height=\"420\" marginheight=\"0\" marginwidth=\"0\" topmargin=\"0\" leftmargin=\"0\" frameborder=\"no\" border=\"0\" scrolling=\"no\"></iframe>";
			bigBannerDiv.innerHTML = '';

			bannerDiv.style.display = '';
			bigBannerDiv.style.display = 'none';
		}
	}
}

// Hides the expanded ad, necessary to open login/my services
function ResizeBanner()
{
	if(playerTerra)
	{
		if(playerTerra.playingAd)
		{
			var currentMedia = playerTerra.getCurrentInternalMedia();
			if(currentMedia && currentMedia.endScript)
			{
				eval(currentMedia.endScript);
			}
		}
	}
}

function RenderVideoBanner(sponsor,expanded)
{
	var wide = false;
	var currentItem = playerTerra.getCurrentMedia();
	var urlHasFlash = currentItem.urlFlash!='';
	var currentInternal = playerTerra.getCurrentInternalMedia();
			
	if(currentItem && currentInternal)
	{ 
		wide = ( currentItem.isWide && ( urlHasFlash || (!currentInternal.isWide && !BrowserDetect.browser == "Explorer") || (currentInternal.isWide && BrowserDetect.browser == "Explorer") ) );
			
		if( !playerTerra.playingAd )
		{
			return;
		}

		var bannerUrl = '';
		var bigBannerUrl = '';
		var sponsorUrl = '';
		if(sponsor && sponsor!='')
		{
			// Preroll sync banner
			bannerUrl    = currentItem.syncBannerUrl;
			bigBannerUrl = currentItem.syncBigBannerUrl;
			sponsorUrl   = currentItem.syncSponsorUrl;
		}
		else
		{
			// Standard video banner
			bannerUrl = currentItem.bannerUrl;
			sponsorUrl = currentItem.sponsorUrl;
		}

		RenderBanner(bannerUrl,bigBannerUrl,sponsorUrl,sponsor,expanded && bigBannerUrl && bigBannerUrl!='',wide);
	
	}
}

function SwapVideoBanner()
{
	var bannerDiv = document.getElementById('publicidade');
	var bigBannerDiv = document.getElementById('publicidadeBig');
	
	if(bannerDiv && bigBannerDiv)
	{
		bannerDiv.style.display = '';
		bigBannerDiv.style.display = 'none';
	}
}

function ApplyBannerParameters(url,sponsor)
{
	// Replaces the special values in the "random" for the url
	var baseUrl = new String(url);

	// Replaces sponsor
	if(sponsor && sponsor!='')
	{
		baseUrl = baseUrl.replace("#sponsor#",sponsor);
		baseUrl = baseUrl.replace("%23sponsor%23",sponsor); // Escaped
	}

	// Replaces random	
	baseUrl = baseUrl.replace("#random#",currentRandom);
	baseUrl = baseUrl.replace("%23random%23",currentRandom); // Escaped
	
	return(baseUrl);
}

var currentRandom = 0;
function UpdateRandom()
{
	var seed = parseInt(Math.random() * 100000);
	currentRandom = new String(seed);
	//Verbose('Random updated to ' + currentRandom);
}
UpdateRandom();

// ********************************************************************************
// Player Tag Controls
// ********************************************************************************
var currentPlayerTag = '';
var currentId = 0;

function CheckPlayerTag()
{
	// Makes sure everything is properly initialized
	if(playerTerra)
	{
		if(playerTerra.player)
		{
			// Is playing - should create tag
			var curPlayState = playerTerra.getPlayState();
			if(curPlayState==playerTerra.playState.playing || curPlayState=='playing')
			{
				// Checks if we can read the current item
				var item = playerTerra.getCurrentMedia();
				if(item)
				{	
					var tag = item.playertag;
					if(tag)
					{
						// Creates a new tag
						CreatePlayerTagFrame(tag,item.id,item.channel);
					}
				}
			}
			else
			{
				// Not playing - destroys tag
				DestroyPlayerTagFrame(currentPlayerTag,currentId);
			}
		}
	}
	
	window.setTimeout('CheckPlayerTag()',1000);
}

function CreatePlayerTagFrame(playerTag, id, channel)
{
	// Only performs action on tag changes
	if(playerTag!=currentPlayerTag || id!=currentId)
	{
		// Destroys any previous tags
		DestroyPlayerTagFrame(currentPlayerTag,currentId)

		// Performs the action
		if(playerTag!='')
		{
						
			// Creates the frame
			var tagFrame = document.getElementById('playerTagFrame_' + playerTag + '_' + id);
			if(!tagFrame)
			{
				tagFrame = document.createElement('iframe');
				tagFrame.id = 'playerTagFrame_' + playerTag + '_' + id;
				tagFrame.frameBorder = 0;
				tagFrame.height = 0;
				tagFrame.width = 0;
				document.body.appendChild(tagFrame);
				
				var params = '';

				if(disableUvTag)
				{
					params = '&disableUvTag=true';
				}
				tagFrame.src = "/templates/playerTag.aspx?channel=" + channel + "&id=" + id + params;
			}

			// Stores the current tag and id
			currentPlayerTag = playerTag;
			currentId = id;
		}
	}
}

function DestroyPlayerTagFrame(playerTag,id)
{
	if(playerTag!='' && id>0)
	{
		// Removes the frame
		var tagFrame = document.getElementById('playerTagFrame_' + playerTag + '_' + id);
		if(tagFrame)
		{
			document.body.removeChild(tagFrame);	
		}
		
		// Clears the control flag
		currentPlayerTag = '';
		currentId = 0;
	}
}

// Inits the control thread
CheckPlayerTag();

// ********************************************************************************
// For the metric script
// ********************************************************************************
function GetMediaInfo(propertyName)
{
	var propertyValue = null;
	if(playerTerra)
	{
		var item = playerTerra.getCurrentInternalMedia();
		
		// Checks if this is an ad
		var isAd = playerTerra.playingAd;
		
		// Gets the property value
		if(item)
		{
			switch(propertyName.toLowerCase())
			{
				case 'contentid':
					propertyValue = item.originalid;
					break;
				case 'contenttitle':
					propertyValue = item.title;
					break;
				case 'contentname':
					propertyValue = item.title;
					break;
				case 'contentthumb':
					propertyValue = item.image;
					break;				
				case 'sourceid':
				case 'channelid':
					if(isAd)
					{
						// Uses item source instead of ad source
						var currentItem = playerTerra.getCurrentMedia();
						propertyValue = currentItem.channel;
					}
					else
					{
						propertyValue = item.channel;
					}
					break;
				case 'sourcetitle':
				case 'channeltitle':
					if(isAd)
					{
						// Uses item source instead of ad source
						var currentItem = playerTerra.getCurrentMedia();
						propertyValue = currentItem.channelTitle;
					}
					else
					{
						propertyValue = item.channelTitle;
					}
					break;
				case 'contentproviderid':
					propertyValue = item.provider;
					break;
				case 'contentprovider':      // Compatibility-only
				case 'contentprovidertitle':
					propertyValue = item.providerTitle;
					break;
				case 'contentduration':
					propertyValue = item.duration;
					break;
				case 'islive':
					propertyValue = item.isLive;
					break;
				case 'isadult':
					propertyValue = item.isAdult;
					break;
				case 'isclosed':
					propertyValue = item.isPrivate;
					break;
				case 'iswide':
					propertyValue = item.isWide;
					break;
				case 'isrelated':
					propertyValue = item.isrelated;
					break;
				case 'ispreroll':
					propertyValue = isAd;
					break;
				case 'filename':
					if(!isAd)
					{
						propertyValue = item.filename;
					}else{
						propertyValue = (usingFlash) ? item.filenameFlv : item.filenameWmv;
					}
					break;
				case 'isembeded':
					propertyValue = item.isEmbed;
					break;
				case 'ismusicvideo':
					propertyValue = item.isMusicVideo;
					break;
				case 'musicproductid':
					propertyValue = item.musicProductId;
					break;
				case 'musicproductname':
					propertyValue = item.musicProductName;
					break;
				case 'musiclabelname':
					propertyValue = item.musicLabelName;
					break;
				case 'musictrackname':
					propertyValue = item.musicTrackName;
					break;
				case 'musicartistname':
					propertyValue = item.musicArtistName;
					break;
				case 'musicalbumname':
					propertyValue = item.musicAlbumName;
					break;
				case 'musictracknumber':
					propertyValue = item.musicTrackNumber;
					break;
				case 'musicpublishername':
					propertyValue = item.musicPublisherName;
					break;
				case 'musicalbumyear':
					propertyValue = item.musicAlbumYear;
					break;
			}
		}
	}

	// Error handling
	if(propertyValue==null)
	{
		// Error reading data, send defaults according to spec
		switch(propertyName.toLowerCase())
		{
			// Int properties
			case 'contentid':
			case 'contentduration':
			case 'sourceid':
			case 'channelid':
			case 'contentproviderid':
			case 'musictracknumber':
			case 'musicalbumyear':
				return(0);
			// String properties
			case 'contenttitle':
			case 'contentname':
			case 'contentthumb':
			case 'sourcetitle':
			case 'channeltitle':
			case 'contentprovider':      // Compatibility-only
			case 'contentprovidertitle':
			case 'filename':
			case 'musicproductid':
			case 'musicproductname':
			case 'musiclabelname':
			case 'musictrackname':
			case 'musicartistname':
			case 'musicalbumname':
			case 'musicpublishername':
				return('');
			// Bool Properties
			case 'islive':
			case 'isadult':
			case 'isclosed':
			case 'iswide':
			case 'isrelated':
			case 'ispreroll':
			case 'ismusicvideo':
			case 'isembeded':
				return(false);
		}
	}
	else
	{
		// Property retrieved, just returns the data
		return(propertyValue)
	}
}

// ********************************************************************************
// To update the channel title using the title of the current channel (media selected)
// ********************************************************************************
function ChangeChannelTitle(title)
{
	var oChangeTitle = document.getElementById('changeTitle');
	if(oChangeTitle)
	{
		oChangeTitle.innerHTML = title;
	}
}

function ShowConfigBox(forceTest)
{	
	var oDvConfigBox = document.getElementById('dvConfigBox');
	if(!oDvConfigBox) return;

	// Attempts to load from cookie			
	var bandwidth = CookieRestore(cookieSettings, "bandwidth");
	
	if(!bandwidth || forceTest)
	{
		forceStop();
		oDvConfigBox.style.display='block';
		playerTester.bandwidthTest(true);
	}
	else
	{
		oDvConfigBox.style.display='block';
		playerTester.bandwidthTestFinished(bandwidth);
	}
}

function HideConfigBox()
{
	var oDvConfigBox = document.getElementById('dvConfigBox');
	if(!oDvConfigBox) return;
	oDvConfigBox.style.display='none';
	ResizeBanner();
}

function PreSelectConfigBox(bandwidth)
{
	var oRbVelocidade = document.frmVelocidades.rbVelocidade;
	oRbVelocidade[0].checked = true;
	for(var i = 0; i < oRbVelocidade.length; i++)
	{
		if(parseInt(oRbVelocidade[i].value,10) > parseInt(bandwidth,10)) break;
		oRbVelocidade[i].checked = true;
	}
}

function ConfirmConfigBox()
{
	var oRbVelocidade = document.frmVelocidades.rbVelocidade;
	var i;
	for(i = 0; i < oRbVelocidade.length; i++) if(oRbVelocidade[i].checked) break;
	
	this.currentBandwidth = oRbVelocidade[i].value;
	HideConfigBox();	

	CookieSave(cookieSettings, "bandwidth", oRbVelocidade[i].value, ckDomain, expirationDate, ckModeWrite);

	if(playerTerra)
	{
		playerTerra.playUrl(playerTerra.getCurrentInternalMedia().urlWm);
	}
	
}

function CancelConfigBox()
{
	playerTerra.play();
	HideConfigBox();
}

function forceStop()
{
	if(playerTerra)
	{
		playerTerra.stop();
	}
}

function executePlayerClick()
{	
	if(!playerTerra)
	{
		if(mi.videoUrl)
		{
			window.open(mi.videoUrl,'TerraTvPopupPlayer');
		}
	}
	else
	{	
		if(enableClickOnVideoAd && playerTerra.playingAd)
		{
			var oCurIM = playerTerra.getCurrentInternalMedia();
			if(oCurIM)
			{
				if(oCurIM.videoClickUrl != '')
				{	
					if(playerTerra.player.playerObject)
					{
						playerTerra.player.playerObject.launchURL(oCurIM.videoClickUrl);
						
					}
					else
					{
						window.open(oCurIM.videoClickUrl,'TerraTvPopupPlayer');
					}	
				}
			}
		}
		
		if(enableClickOnVideoNormal && !playerTerra.playingAd)
		{
			var oCurIM = playerTerra.getCurrentInternalMedia();
			if(oCurIM)
			{
				if(oCurIM.videoUrl != '')
				{
					if(playerTerra.player.playerObject)
					{
						playerTerra.player.playerObject.launchURL(oCurIM.videoUrl);
						
					}
					else
					{
						window.open(oCurIM.videoUrl,'TerraTvPopupPlayer');
					}
				}
			}
		}
	}	
}

function ExecuteFlashClick()
{
	executePlayerClick();
}


//*************************************************************************
// CUSTOM PLAYER
//*************************************************************************
function CustomPlayerPlay()
{
 var playerCustom = document.getElementById('CustomPlayer');
	//disableAutoPlay=false;
	if(playerCustom)
	{ 
		var urlHasFlash = currentMedia.urlFlash!='';
		var isLive = currentMedia.isLive;
		
		if(urlHasFlash)
		{
			document.getElementById("CustomPlayer").className="player Flash";
			if(playerTerra)
			{
				playerTerra.play();
			}else{
				setTimeout('CustomPlayerPlay()', 200);
			}
		}
		else
		{	
			if(isLive){
				document.getElementById("CustomPlayer").className="player live";
			}else{
				document.getElementById("CustomPlayer").className="player";
			}

			if(wmFallBackMode)
			{
				RenderWmpFallbackOnDiv('playerHost');
			}
			else
			{
				try
				{	
					if(playerTerra)
					{
						playerTerra.play();
						document.getElementById('btnPlay').className='bts play';
						
						AdaptationStyleOpera(false,'visible');
						
						
					}	
				}
				catch(e)
				{}
			}
		}
	}
}


function CustomSendToFriend(contentId)
{
	window.open('/templates/popupSendToFriend.aspx?contentId='+contentId,'sendotofriend',('width=610,height=456'));
}

function openTerraTv(pUrl)
{
	playerTerra.stop();
	window.open(pUrl);
}

function KeyFilter(oEvent){    
    var cod_tecla=27;
    var oEvent = oEvent ? oEvent : window.event;
    var tecla = (oEvent.keyCode) ? oEvent.keyCode : oEvent.which;
    if(oEvent.type=="keydown" && navigator.appName.indexOf('Internet Explorer')<0 ){
        return true;
    }
    if (typeof(oEvent.keyCode)=='number' && oEvent.keyCode == cod_tecla){
        if (typeof(oEvent.preventDefault)=='function'){
            oEvent.preventDefault();
        } else {
            oEvent.returnValue = false;
            oEvent.keyCode = 0;
        }
    }
}
document.onkeydown = KeyFilter;


function hideLayer(playerLayer)
{
	if(document.getElementById('CustomPlayer'))
	{
		if(document.getElementById('CustomPlayer').className==playerLayer)
		{
			if(currentMedia)
			{
				var urlHasFlash = currentMedia.urlFlash!='';
				if(urlHasFlash)
				{
					document.getElementById('CustomPlayer').className="player Flash";
				}else{
					document.getElementById('CustomPlayer').className="player";
				}

				if(document.getElementById('btnPlay'))
				{
					document.getElementById('btnPlay').className="bts play";
				}
			}
		}
	}
}

// avoid moving page when hit <a> link
function voidlink(){}

// holds link for next video if playing ADs
function playerPlayNextVideoItem(nextPos, nextRelated)
{

	if(playerTerra)
	{
		if(!playerTerra.playingAd) 
		{
			playerTerra.playItem(nextPos,nextRelated);
		}
	}
}

		
function disableAutoPlayParam()
{
	var userHasWm = (enableWmp || enableWmpMozilla || enableFallback) && (GetPlayerTypeWm() > 0);
	var urlHasWm = currentMedia.urlWm!='';
	if(disableAutoPlay==true)
	{
		startPlayback = false;

		if(userHasWm && urlHasWm)
		{		
			if(playerTerra)
			{
				if(playerTerra.playState)
				{
					if(playerTerra.getPlayState() == playerTerra.playState.playing)
					{
						playerTerra.stop();
						setTimeout('playerTerra.stop()', 100);
					}
					else
					{
						setTimeout('disableAutoPlayParam()', 100);
					}
				}
			}
			else
			{
				setTimeout('disableAutoPlayParam()', 100);
			}
		}
	}
}


function muteCustom()
{
	var divmutecustom = document.getElementById("CustomPlayer");
	if(playerTerra)
	{
		playerTerra.mute();
		enableCustomMute = playerTerra.muteMode;
	}
}


function checkFlashCustomControls()
{
	if(currentMedia)
	{
		var urlHasFlash = currentMedia.urlFlash!='';
		if(document.getElementById('CustomPlayer'))
		{
			if(!disableAutoPlay)
			{
				if(urlHasFlash)
				{
					document.getElementById('CustomPlayer').className = "player Flash";
				}
			}
		}
	}
}


function ForceLogoffJS()
{
	var date = new Date((new Date()).getTime() - cookieParamMonth*24*60*60*1000);	
	var cookieManagerB = new CookieManager('B', date, ckDomain);
	cookieManagerB.setValue('B', '');
}

function parseBool(varTmp)
{
	if(varTmp == 'true')
	{
		return true;
	}else{
		return false;
	}
}

function executePlayerStateChange()
{
	// Keeps the mute, in case the player removes it on transition		
	
	if(playerTerra)
	{
		if(playerTerra.muteMode)
		{
			var tmpMute = cookieManager.getValue("muteActive");
			if ( parseBool(tmpMute) )
			{
				playerTerra.player.setMute(parseBool(tmpMute));
				setTimeout('playerTerra.player.setMute('+ tmpMute +')',100);
			}
		}
	}
}

function checkBrowserTry(urlBack)
{
	cookieManager.setValue('video_fall_back', '1');
	this.location.href = urlBack.replace('||','&');
}

function relatedData(parflashRelTitle, parflashRelThumb, parflashRelLink, parflashRelChannel, parid)
{
	this.flashRelTitle = parflashRelTitle;
	this.flashRelThumb = parflashRelThumb;
	this.flashRelLink = parflashRelLink;
	this.flashRelChannel = parflashRelChannel;
	this.id = parid;
}

function ValidateSendForm()
{
	var ret = true;
	if(document.frmSendVideo.your_name.value == '') ret = false;
	if(document.frmSendVideo.your_email.value == '') ret = false;
	if(document.frmSendVideo.friend_name.value == '') ret = false;
	if(document.frmSendVideo.friend_email.value == '') ret = false;
	if(document.frmSendVideo.comment.value == '') ret = false;
	if(!ret) alert(Translate('FILL_ALL_FIELDS'));
	return ret;
}

function PlayRelatedVideo( link )
{
	if (defineLocation == ''){
		this.location.href = link;
	}
	else //only custom 
	{
		if (  defineLocation == 'self'){		   
			self.location.href = link;
		}
		else{
			top.location.href = link;
		}			
	}		
}

function uvTagFrameCall(isLive, isAdvertise, isFlash)
{	
	var uvTagCall = document.getElementById("uvtagdiv");		
	
	// Ticket 10734 - uv tag	
	//alternateurl  = "/templates/alternate_player_tag.aspx?flash="+ isflash +"&od=" + isondemand + "&ad=" + isadvertise;	
	var alternateurl = "";		
		
	if ( isFlash ) //FLASH
	{
		
		if ( !isLive && !isAdvertise )
		{		
			alternateurl = strUvServer.replace("@UVTAG", strUvServerFlashOd );
		}
		else if ( !isLive > 0 && isAdvertise )
		{	
			alternateurl = strUvServer.replace("@UVTAG", strUvServerFlashAd );
		}
		else
		{	
			alternateurl = strUvServer.replace("@UVTAG", strUvServerFlashLive );
		}
	}
	else //WMV
	{
		if ( !isLive && !isAdvertise )
		{		
			alternateurl = strUvServer.replace("@UVTAG", strUvServerWmOd );	
		}
		else if ( !isLive && isAdvertise )
		{		
			alternateurl = strUvServer.replace("@UVTAG", strUvServerWmAd );
		}
		else
		{		
			alternateurl = strUvServer.replace("@UVTAG", strUvServerWmLive );
		}
	}		
	
	alternateurl += "&rnd=" +new Date().getTime();
	 
	uvTagCall.innerHTML = "<img id=\"moviehit\" name=\"moviehit\" src=\""+ alternateurl + "\" width=1 height=1 border=0 alt=\"\"></img>";
	
	uvTagCall.style.display = '';
	uvTagCall.style.display = 'none';
	uvTagCall.innerHTML = '';
	

}

function write(){}

function AdaptationStyleOpera(valueAdapt,valueVisibility)
{
	var oDvVideo = document.getElementById('videoDetais');
	var player = document.getElementById('playerHtml');
		
	if(BrowserDetect.browser == "Opera")
	{	if(valueAdapt)
		{
			oDvVideo.style.height = '0px';
			oDvVideo.style.width = '0px';
		
		}
		else
		{
			oDvVideo.style.height = playerHeightWm;
			oDvVideo.style.width = playerWidthWm;
		}
	}	
	else
	{
		player.style.visibility = valueVisibility;
	}
	
}	
var animating = false;
function PlayHighlight()
{
	if(Highlighs)
	{
		var item = Highlighs[currentHighlight];
		//Play(item.id, item.type, item.channel);
		top.location.href = '/templates/channelContents.aspx?channel='+item.channel+'&contentid='+item.id;
	}
}
function AddHighlight()
{
	if(Highlighs)
	{
		var item = Highlighs[currentHighlight];
		Add(item.id, item.type, item.channel);
	}
}
function BackHighlight()
{
	if(animating) return;

	if(Highlighs)
	{
		currentHighlight = currentHighlight == 0 ? Highlighs.length - 1 : currentHighlight - 1;
		ShowCurrentHighlight();
	}
}
function NextHighlight()
{
	if(animating) return;

	if(Highlighs)
	{
		currentHighlight = currentHighlight == Highlighs.length - 1 ? 0 : currentHighlight + 1;
		ShowCurrentHighlight();
	}
}
function ShowCurrentHighlight()
{

	if(Highlighs)
	{
		var item = Highlighs[currentHighlight];
		var image = document.getElementById("highlighImage");
		var imagelink = document.getElementById("highlightImageLink");
		var title = document.getElementById("highlightTitle");
		var text = document.getElementById("highlightText");
		var channelTitle = document.getElementById("highlighChannel");
		var highlightControls = document.getElementById("highlightControls");

		var url = '';
		var item = Highlighs[currentHighlight];
		//Play(item.id, item.type, item.channel);

		title.innerHTML = "<a href=\"" + item.playbackUrl + "\" >" + item.title + "</a>";
		
		if(item.isRestrict || item.isAdult)
		{
			if(item.isRestrict && item.isAdult)
			{
				title.className = 'lockedAdult';
			}
			else
			{
				if(item.isRestrict)
				{
					title.className = 'locked';
				}
				if(item.isAdult)
				{
					title.className = 'adult';
				}
			}
		}
		else
		{
			title.className = '';
		}
		text.innerHTML = item.text;
		image.src = item.image;
		imagelink.href = item.playbackUrl;
		
		outMode = false;
		FadeIn(image.id, 0);
		
		channelTitle.innerHTML = item.channelTitle;
		channelTitle.href = item.channelUrl;
		
		var highlightControlsHtml = '';
		if(Highlighs.length > 1)
		{
			highlightControlsHtml += "<a id=\"btnBackHighlight\" style=\"cursor:pointer\" onclick=\"BackHighlight(); return false;\" class=\"ant\"><img src=\"/" + imageFolder + "/btVideoBanner_ant.gif\" alt=\"" + Translate("PREVIOUS") + "\" /></a>";
		}			
		highlightControlsHtml += "<a id=\"highlightPlayLink\" href=\"" + item.playbackUrl + "\" class=\"play\">" + Translate("PLAY") + "</a>";
		
		if(Highlighs.length > 1)
		{
			highlightControlsHtml += "<a style=\"cursor:pointer\" onclick=\"NextHighlight(); return false;\" class=\"prox\"><img src=\"/" + imageFolder + "/btVideoBanner_prox.gif\" alt=\"" + Translate("NEXT") + "\" /></a>";
		}
		
		highlightControls.innerHTML = highlightControlsHtml;

	}
}

function FadeIn(objID, value)
{
	if(value <= 100)
	{
		animating = true;
		SetOpacity(objID, value);
		value += 5;
		setTimeout("FadeIn('" + objID + "', " + value + ")", 50);
	}
	else
	{
		animating = false;
	}
}

function SetOpacity(objID, opacity)
{
	var obj = document.getElementById(objID);
	
	opacity = (opacity == 100)?99.999:opacity;
	
	// IE/Win
	obj.style.filter = "alpha(opacity:"+opacity+")";
	  
	// Safari 1.2, newer Firefox and Mozilla, CSS3
	obj.style.opacity = opacity/100;
}
// ************************************************************
// Voting Settings
// ************************************************************
var voteManager = new AjaxManager('voteManager'); // Manager for posting ratings
var voteUrl = "/templates/Ajax/genericAjax.aspx?AjaxSource=TerraMediaCenter.Vote";// Ajax voting URL

var voteName = 'stars';         // Prefix for the span/div containing the stars
var voteImageName = 'starsImg'; // Prefix for the image to be resized

var voteWidth = 60;                     // Total pixels for a "full" rating
var voteStars = 5;                      // Number of the stars
var votePixels = voteWidth / voteStars;

var voteId = 0;         // Current mouse over id
var voteType = 0;       // Current mouse over type
var voteRating = 0;     // Current rating
var voteObj = null;     // Current voting div/span
var voteImageObj = null // Current voting image
var voteRedraw = false; // Allows/Denies redraw of image

var voteTimeout = -1;   // Timeout for "smoother" scrolling
var lastVote = 0;

// ************************************************************
// Voting MouseOver Methods
// ************************************************************

function Vote_Click() 
{
	try
	{
		// Updates the onmouseover event to the new constructor
		voteObj.onmouseover = null;//new Function('Vote_OnMouseOver(' + voteId + ', ' + videoMediaIndex + ', false)');
		voteObj.onclick = null;
		voteObj.onmouseout = null;
		
		// Stores the vote
		var url = voteUrl + '&p1=' + voteId + '&p2=' + voteRating;
		voteManager.Add(url, ParseVote);
		
		// Forces an update of the star to the saved rating
		Vote_UpdateDiv(voteRating);

		//VoteBox_ReloadFix
		CookieVotesControl(voteRating);
		
		// Clears the variables
		voteId = 0;
		voteType = '';
		voteRating = 0;
		voteObj = null;
		voteImageObj = null;
		voteRedraw = false;

		
	}
	catch(e){}
}

// Gets the absolute left of the DIV containing the stars
function Vote_GetLeft() 
{
	if(voteObj)
	{
		var left = voteObj.offsetLeft;
		aux = voteObj.offsetParent;
		while (aux)
		{
			left += aux.offsetLeft;
			aux = aux.offsetParent;
		}
		return(left)
	}
	return(0);
}

function Vote_OnMouseOver(id, type, redraw, last)
{
	lastVote = last;
	// Clears any pending timeouts
	if(voteTimeout>-1)
	{
		window.clearTimeout(voteTimeout);
		voteTimeout = -1;
	}

	// Clears items if we changed places
	if(voteId!=id || voteType!= type)
	{
		Vote_Clear();
	}

	// Stores the current mouseover object
	voteId = id;
	voteType = type;
	voteObj = document.getElementById(voteName + '_' + voteType + '_' + voteId);
	voteImageObj = document.getElementById(voteImageName + '_' + voteType + '_' + voteId);
	voteRedraw = redraw;

	// Enables the mousemove
	document.onmousemove = Vote_OnMouseMove;
}

function Vote_OnMouseOut()
{
	voteTimeout = window.setTimeout('Vote_Clear();',10);
}

function Vote_Clear()
{
	// Clears the current information
	if(voteRedraw)
	{
		Vote_UpdateDiv(0);
	}
	
	Vote_UpdateDiv(lastVote);
	
	voteRating = 0;
	voteId = 0;
	voteType = '';
	voteObj = null;
	voteImageObj = null;
	voteRedraw = false;
	
	var label = document.getElementById("vote_label");
	if(label)
	{
		label.innerHTML = '<h4>' + Translate("MAKE_A_VOTE") + '</h4>';
	}
	
	// Disables the mousemove
	document.onmousemove = null;
}

function Vote_OnMouseMove(e)
{
	if(voteObj)
	{
		// Gets the left position of the div
		var left = Vote_GetLeft();

		if(left>=0)
		{
			// Calls the method to get the mouse position
			// Declared in FloatingMenu.js
			GetMousePosition(e);
		
			// Checks what's the current mouseover star
			var newVote = Math.ceil((currentMouseX-left)/votePixels);
			
			// Makes sure the rating is within valid limits
			if(newVote<1) newVote = 1;
			if(newVote>5) newVote = 5;
			
			// Show label
			var label = document.getElementById("vote_label");
			if(label)
			{
				var tempText = "";
				switch(newVote)
				{
					case 1:
						tempText = Translate("TERRIBLE");
						break;
					case 2:
						tempText = Translate("BAD");
						break;
					case 3:
						tempText = Translate("REGULAR");
						break;
					case 4:
						tempText = Translate("GOOD");
						break;
					case 5:
						tempText = Translate("EXCELLENT");
						break;
					default:
						tempText = Translate("MAKE_A_VOTE");
						break;
				}
				label.innerHTML = '<h4>' + tempText + '</h4>';
			}
			
			// If the vote changed, updates the drawing
			if(voteRating!=newVote)
			{
				// Stores the vote for later usage
				voteRating = newVote;

				// Updates the screen if requested			
				if(voteRedraw) Vote_UpdateDiv(newVote);
			}
		}
	}
}

function Vote_UpdateDiv(newVote)
{
	if(voteImageObj && newVote>-1 && newVote<=voteStars)
	{
		// Updates the star	
		voteImageObj.style.width = votePixels * newVote + 'px';
	}
}

// ************************************************************
// Voting MouseOver Methods
// ************************************************************

var voteNotifyDiv = null;
var voteNotifyTimeout = -1;
var voteNotifyOffsetX = -60;
var voteNotifyOffsetY = -60;

function ParseVote()
{
	if(this.httpRequest.status == 200)
	{
		CreateVoteNotify(this.httpRequest.responseText);
	}
}
function CreateVoteNotify(text)
{
	// Clears any pending timeouts
	if(voteNotifyTimeout!=-1)
	{
		//window.clearTimeout(voteNotifyTimeout);
	}

	if(!voteNotifyDiv)
	{
		// Creates a div
		/*voteNotifyDiv = document.createElement('div');
		voteNotifyDiv.className = 'loadingNotify'; //class that contains div style
		voteNotifyDiv.style.position = 'Absolute';

		document.body.appendChild(voteNotifyDiv);*/
		
		voteNotifyDiv = document.getElementById("vote_label");
	}

	// Updates the position
	//voteNotifyDiv.style.left = currentMouseX + voteNotifyOffsetX + 58 + 'px';
	//voteNotifyDiv.style.top  = currentMouseY + voteNotifyOffsetY + 20 + 'px';
	
	// Updates the text	
	voteNotifyDiv.innerHTML = '<h4>' + text + '</h4>';
	
	CallVoteFix();

	// Schedules the notification destruction
	//voteNotifyTimeout = window.setTimeout('DestroyVoteNotify()', 2000);
}

function CallVoteFix()
{
	if(playerTerra)
	{
		playerTerra.alreadyVote = true;

		Vote_Fix();
	}else{
		setTimeout('CallVoteFix();',200);
	}
}

function DestroyVoteNotify()
{
	// Destroys the div and resets the parameters
	document.body.removeChild(voteNotifyDiv);
	voteNotifyDiv = null;
	voteNotifyTimeout = -1;
}

function Vote_Fix()
{
	if(!playerTerra) {return;}
	else 
	{
		if(!playerTerra.alreadyVote)
		{
			return;
		}
	}	
	
	// Increments in 1 the total votes
	var voteCountDiv = document.getElementById('vote_count');
	if(voteCountDiv)
	{
		var currentVoteText = new String(voteCountDiv.innerHTML);
		var totalVotes = parseInt(currentVoteText.substring(0,currentVoteText.indexOf(" ")));

		if(isNaN(totalVotes))
		{
			voteCountDiv.innerHTML = 1 + ' ' + Translate("VOTES");
		}
		else
		{
			voteCountDiv.innerHTML = (totalVotes+1) + ' ' + Translate("VOTES");
		}
	}
}

// ************************************************************
// Voting Box Reload Fix
// ************************************************************
function VoteBox_ReloadFix(id)
{	
	var alreadyVote = new Boolean(cookieManager.getValue("alreadyVote" + id));
	
	if(alreadyVote == true)
	{	
		//rating to draw stars		
		var newRating = FormatRating(cookieManager.getValue("rating" + id));
		var rating = FormatRating(ratingVotesCache);
    
		//total votes
		var newTotal = parseInt(cookieManager.getValue("total" + id),10);		
		var totalVotes = parseInt(totalVotesCache,10);

		//chace not expired
		if(newTotal > totalVotes)
		{
			// Increments in 1 the total votes
			var voteCountDiv = document.getElementById('vote_count');
			if(voteCountDiv)
			{
				if(isNaN(totalVotes))
					voteCountDiv.innerHTML = 1 + ' ' + Translate("VOTES");

				else
					voteCountDiv.innerHTML = (newTotal) + ' ' + Translate("VOTES");
			}			
			
			// redraw stars
			voteImageObj = document.getElementById(voteImageName + '_' + id);
			Vote_UpdateDiv(parseFloat(newRating));
		}
	}
}

function CookieVotesControl(newVote)
{
	cookieManager.setValue("rating" + voteId,RecalcVotesRating(newVote));
	cookieManager.setValue("total" + voteId,(parseInt(totalVotesCache,10)+1));
	cookieManager.setValue("alreadyVote" + voteId,"true");
}

function RecalcVotesRating(newVote)
{
	var rating = FormatRating(ratingVotesCache);
	var totalVotes = parseInt(totalVotesCache,10);
	return ( ((rating*totalVotes) + newVote) / (totalVotes+1));
}

function FormatRating(rating)
{
	if(rating.indexOf(".") == -1)
		return parseFloat(rating);
	else
		return parseFloat(rating.substring(0,(rating.indexOf(".")+3)));
}
