var urlGetSubscriptionInfo = "getSubscriptionInfo.aspx";
var urlMedias = 'getmediaxml.aspx';
var urlMediasValidation = 'getmediavalidationxml.aspx';
var deniedContents = ''; // Storage for the "denied" contents
var httpRequestMedias = null;
var requestInProgress = false;
var div2;
var ver = '0';
var valid = 0;
var origem;
// Performs a login using ajax
//function PerformMediaAdd(contentId, startplay, isPreview,valida)
function ShowURL(urlsearch,expression)
{
	var search = parent.document.getElementById('hiddenOrigem2').value.split('&')[0].split('/')[3].split('?')[0];
	if(search == "search.aspx")
		parent.document.getElementById('movieLibrary').src = parent.document.getElementById('hiddenOrigem2').value.split('&')[0];
	else
	{
		parent.document.getElementById('movieLibrary').src = parent.document.getElementById('hiddenOrigem2').value.split('&')[0];
	}
	
	
}
function PerformMediaAdd(contentId, startplay, isPreview)
{
	/*if(valida == '1')
		//flashMode = true;*/
	
	var url = urlMedias + '?contentId=' + contentId;
	if(startplay) url += '&startplay=' + startplay;
	url += '&isPreview=' + isPreview;
	AjaxMedias_Add(url, startplay);
	ver = 0;
}
function createCookie() {
	var cookieManager = new CookieManager('megaplayer_session_adult', null, window.location.toString().match('^(http://)?([^/]+)')[2]);
	cookieManager.eraseValue('megaplayer_session_adult',null);	
	
}
function PerformMediaAddValidation2(contentId, startplay, isPreview, isValid, urlorig)
{
		origem = urlorig;
		var cookieManager = new CookieManager('megaplayer_session_adult_back', null, window.location.toString().match('^(http://)?([^/]+)')[2]);
		cookieManager.setValue('megaplayer_session_adult_back',isValid);	
		var url = urlMediasValidation + '?contentId=' + contentId;
		if(startplay) url += '&startplay=' + startplay;
		AjaxMedias_Add(url, startplay);
}
function PerformMediaAddValidation(channelId, startplay, isPreview, contentId)
{
	var url = urlMediasValidation + '?contentId=' + channelId;
	if(startplay) url += '&startplay=' + startplay;
	AjaxMedias_Add(url, startplay);
}
function PerformPlaylistAdd(playlistId, startplay, hash)
{
	var url = urlMedias + '?playlistId=' + playlistId;
	if(startplay) url += '&startplay=' + startplay;
	if(hash) url += '&hash=' + hash;
	AjaxMedias_Add(url, startplay);
}

function PerformDefaultPlaylistAdd(channelId, startplay, valida, contentId)
{
	if(valida == '1'){
		var url = urlMedias + '?channel=42';
		if(startplay) url += '&startplay=' + startplay; 
		AjaxMedias_Add(url, startplay);
	}else{
		var url = urlMedias + '?channel=' + channelId;
		if(startplay) url += '&startplay=false'; /*+ startplay;*/
		AjaxMedias_Add(url, startplay);
		var url = urlMedias + '?contentId=' + contentId;
		if(startplay) url += '&startplay=' + startplay;
		url += '&isPreview=true';
		AjaxMedias_Add(url, startplay);
	}
}
function DefaultPlaylist(channelId, startplay)
{
		var url = urlMedias + '?channel=' + channelId;
		if(startplay) url += '&startplay=' + startplay 
		AjaxMedias_Add(url, startplay);
}
function PerformCookieAdd(startplay)
{
	var url = urlMedias + '?cookie=true';
	AjaxMedias_Add(url, startplay);
}

function AjaxMedias_Add(url, startplay)
{
	var added = false;	

	// Avoids loading before playlist is ready
	if(plIg)
	{
		// Avoids conflictng requests
		if(!requestInProgress)
		{
			requestInProgress = true;
			httpRequestMedias = CreateXmlHttpRequest();

			if(httpRequestMedias)
			{
				try
				{
					httpRequestMedias.onreadystatechange = new Function('AjaxMedias_Parse(' + startplay + ');');
					httpRequestMedias.open('GET',url);
					httpRequestMedias.send(null);
					added = true;
				}
				catch(e)
				{
					alert('Could not open URL');
					alert(e);
				}
			}
			else
			{
				alert('XmlHttpRequest object could not be loaded');
			}
		}
	}

	if(!added)
	{
		// Playlist not ready, adds to queue
		window.setTimeout('AjaxMedias_Add(\'' + url + '\')',500);
	}
}
//create cookie for adult
/*function createCookie(name) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+expires+"; path=/";
}*/
//read cookie adult
/*function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i &lt; ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}*/
//erase cookie adult
/*function eraseCookie(name) {
	createCookie(name,"",-1);
}*/
// Parses the return of the login XML
function AjaxMedias_Parse(startplay)
{
	if (httpRequestMedias.readyState == 4) // readyState = 4 -> Complete
    {
		if(httpRequestMedias.status == 200)  // status = 200 -> OK
		{
			// XML loaded properly, parses it
			var xml = httpRequestMedias.responseXML;
			
			// Gets the root node
			var root = SelectSingleNode(xml,'contents');
			
			// Gets the list of contents from the XML
			var contentList = SelectNodes(root,'content');
			
			// Checks if this is a default playlist
			var defaultPlaylist = eval(GetNodeValue(SelectSingleNode(root,'defaultPlaylist')));

			
			// Checks if this is a loaded playlist
			var playlistId = parseInt(GetNodeValue(SelectSingleNode(root,'playlistId')));
			
			
			var Adult = parseInt(GetNodeValue(SelectSingleNode(contentList[0],'adult')));
			var cookieManager = new CookieManager('megaplayer_session_adult', null, window.location.toString().match('^(http://)?([^/]+)')[2]);
			var cookieManager2 = new CookieManager('megaplayer_session_adult_back', null, window.location.toString().match('^(http://)?([^/]+)')[2]);
			var cache = cookieManager.getValue('megaplayer_session_adult');
			var cache2 = cookieManager2.getValue('megaplayer_session_adult_back');
			if(Adult == 0 && (cache == null || cache == "megaplayer_session_adult=null"))
			{
				cookieManager.setValue('megaplayer_session_adult',parseInt(GetNodeValue(SelectSingleNode(contentList[0],'id'))));	
				
				var or = 'http://'+parent.document.getElementById('hiddenOrigem').value.split('?')[0].split('/')[2] + '/contents.aspx?channel=42';
				var or2 = parent.document.getElementById('hiddenOrigem').value;
				parent.document.getElementById('movieLibrary').src = or+"&expression="+parent.document.getElementById("searchText").value+"&startplay=false&adultGrant=true&contentid="+parseInt(GetNodeValue(SelectSingleNode(contentList[0],'id')));
				parent.document.getElementById('hiddenOrigem2').value = or2;
				requestInProgress = false;
				
			}else{
				// Resets the playlist id, since a new item was added
				if(Adult == 0 && (cache2 == null || cache2 == "megaplayer_session_adult_back=null"))
				{
						var or = 'http://'+parent.document.getElementById('hiddenOrigem').value.split('?')[0].split('/')[2] + '/contents.aspx?channel=42';
						var or2 = parent.document.getElementById('hiddenOrigem').value;
						parent.document.getElementById('movieLibrary').src = or+"&expression="+parent.document.getElementById("searchText").value+"&startplay=false&adultGrant=true&contentid="+parseInt(GetNodeValue(SelectSingleNode(contentList[0],'id')));
						parent.document.getElementById('hiddenOrigem2').value = or2;
						requestInProgress = false;
				}
				else
				{
					plIg.playlist.id = playlistId;
					if(defaultPlaylist)
					{
						// This is a default playlsit
						if(plIg.allowDefaulPlaylist)
						{
							// Default playlist is allowed - clears the current one to load the default
							plIg.clear();
						}
						else
						{
							// Default playlist is not allowed - abort process
							requestInProgress = false;
							return;
						}
					}
					
					// Clears the list of 'denied' contents
					deniedContents = '';
					
					// Runs through the contents performing the add
					
					for(var i=0;i<contentList.length;i++)
					{
						AjaxMedias_ContentParse(contentList[i], false, defaultPlaylist, startplay)
					}	
					
					// Checks if startplay was ordered
					var startplay = eval(GetNodeValue(SelectSingleNode(root,'startplay')));
					
					if(deniedContents!='')
					{
						// Opens the login page, if there was any 'denied' contents
						AjaxMedias_OpenLogin(deniedContents,startplay);
					}
					else
					{
						// Only uses startplay if there was no error adding the contents
						if(startplay)
						{
							if(GetPlayerType())
							{
								if(CheckPlayer())
								{
									if(contentList.length>0)
									{
										try
										{
											playerIg.playItem(0);
											scrollTo(0,0);
										}
										catch(e) {}
									}
								}
							}
						}
						else
						{
							//if (! defaultPlaylist)
							//	CreateNotify ("Conteúdo adicionado à playlist.");
						}
					}
					// Clears the control flag
					requestInProgress = false;
				}
			}
			
		}
		
	}
}

function AjaxMedias_ContentParse(node, isadvert, defaultPlaylist, startplay)
{
	// Sees if the current content was allowed
	var allowed = eval(GetNodeValue(SelectSingleNode(node,'allowed')));
	//alert (allowed);
	if(allowed)
	{
		// Creates the new playlist item
		var mi = new MediaItem;
		mi.contentId = parseInt(GetNodeValue(SelectSingleNode(node,'id')));
		mi.title = GetNodeValue(SelectSingleNode(node,'title'));
		mi.imgUrl = GetNodeValue(SelectSingleNode(node,'image'));
		mi.bannerUrl = GetNodeValue(SelectSingleNode(node,'banner'));
		mi.duration = GetNodeValue(SelectSingleNode(node,'duration'));
		mi.rating = GetNodeValue(SelectSingleNode(node,'rating'));
		mi.canBuy = GetNodeValue(SelectSingleNode(node,'canBuy'));
		mi.canAccess = GetNodeValue(SelectSingleNode(node,'canAccess'));
		mi.isPreview = GetNodeValue(SelectSingleNode(node,'isPreview'));
		
		
		if ((typeof(preview) != 'undefined') )
		{
		//	mi.preview = preview;
			if(preview)//if(mi.isPreview == 'true')
			{
				mi.setUrl(0,GetNodeValue(SelectSingleNode(node,'urlPreview')));
				mi.setUrl(1,GetNodeValue(SelectSingleNode(node,'urlPreview')));
			}
			else
			{
				mi.setUrl(0,GetNodeValue(SelectSingleNode(node,'urlLow')));
				mi.setUrl(1,GetNodeValue(SelectSingleNode(node,'urlHigh')));
			}
		
		}
		else
		{
			mi.setUrl(0,GetNodeValue(SelectSingleNode(node,'urlLow')));
			mi.setUrl(1,GetNodeValue(SelectSingleNode(node,'urlHigh')));
		}
		

		// Stores the "defaultPlaylist" parameter
		mi.defaultPlaylist = defaultPlaylist;
		
		// Adds the advertisements, if they exist		
		mi.ads = new Array();
		if(!isadvert)
		{
			// Gets the list of advertisement nodes
			var advertList = SelectNodes(node,'content');
			
			// Runs through the contents performing the add
			for(var i=0;i<advertList.length;i++)
			{
				var adv = AjaxMedias_ContentParse(advertList[i], true, defaultPlaylist)
				mi.ads[mi.ads.length] = adv;
			}

			// Adds the item to the playlist
			
			plIg.add(mi);
			
			//if (!defaultPlaylist && !startplay) CreateNotify ("Conteúdo adicionado à playlist.");
		}
	}
	else
	{
		var id = parseInt(GetNodeValue(SelectSingleNode(node,'id')));
		if(deniedContents!='') deniedContents += ',';
		deniedContents += id;
	}
	return(mi);
}

function AjaxMedias_OpenLogin(contents,startplay)
{
	var action = 'addcontents';
	if(startplay) action = 'playcontents';
	
	//Pega o valor da pagOrigem que armazena o valor guardado na Session
	var origem = parent.document.getElementById("pagOrigem").value;
	
	window.open("popupLogin.aspx?contentId=" + contents + '&action=' + action+'&origem=' + origem , 'login', "top=20, width=290, height=340, toolbar=no, resizable=0");
}

function AbrePopUp2(contents)
{
	var origem = document.getElementById('hiddenOrigem').value;
	parent.document.getElementById('movieLibrary').src = origem+"&post=1&contentid="+contents;
}

	