var req;
var MQSAUrl = "http://" + document.location.host + "/video/VideoService/TokenQsa.htmx?";//"/video/VideoService/mqsa.htmx?";
//var clipQueue;
//var _baseUrlToken = "rtmpe://ntteurope.fcod.llnwd.net/a1225/r1/mp4:";
//var checkDone=false;
var baseURL = 'http://' + document.location.host;
if (baseURL.indexOf('frontend')>-1)
	_OrderURL = setOrderLanguage(document.location.host,'dev');
else if (baseURL.indexOf('staging')>-1 || baseURL.indexOf('static.dr')>-1)
	_OrderURL = setOrderLanguage(document.location.host,'stag');
else
	_OrderURL = setOrderLanguage(document.location.host,'prod');//'https://secure.video.uefa.com/Selfcare/default.aspx';

function setOrderLanguage(path,environment)
{
	var url = path.substring(0,path.indexOf("."));
	if (environment == 'dev'){
		switch (url)
		{
			case "it" : return "http://frontend.uefa.deltatre.it:21001/op/Lang=IT/";
			case "fr" : return "http://frontend.uefa.deltatre.it:21001/op/Lang=FR/";
			case "de" : return "http://frontend.uefa.deltatre.it:21001/op/Lang=DE/";
			case "es" : return "http://frontend.uefa.deltatre.it:21001/op/Lang=ES/";
			case "pt" : return "http://frontend.uefa.deltatre.it:21001/op/Lang=PT/";
			default: return "http://frontend.uefa.deltatre.it:21001/op/Lang=EN/";
		}	
	}
	else if (environment == 'stag'){
		switch (url)
		{
			case "it" : return "http://orderpath.static.dr.infra.uefa.com/op/Lang=IT/";
			case "fr" : return "http://orderpath.static.dr.infra.uefa.com/op/Lang=FR/";
			case "de" : return "http://orderpath.static.dr.infra.uefa.com/op/Lang=DE/";
			case "es" : return "http://orderpath.static.dr.infra.uefa.com/op/Lang=ES/";
			case "pt" : return "http://orderpath.static.dr.infra.uefa.com/op/Lang=PT/";
			default: return "http://orderpath.static.dr.infra.uefa.com/op/Lang=EN/";
		}		
	}
	else if(environment == 'prod'){
		//return "https://order.matchcentre.com/op/Lang=EN/";
		switch (url)
		{
			case "it" : return "https://order.matchcentre.com/op/Lang=IT/";
			case "fr" : return "https://order.matchcentre.com/op/Lang=FR/";
			case "de" : return "https://order.matchcentre.com/op/Lang=DE/";
			case "es" : return "https://order.matchcentre.com/op/Lang=ES/";
			case "pt" : return "https://order.matchcentre.com/op/Lang=PT/";
			default: return "https://order.matchcentre.com/op/Lang=EN/";
		}		
	}
	//return "http://template.orderpath.infra.uefa.com:21001/op/Lang=EN/";
}

function handleXmlResponseLive(liveRequest)
{//alert(liveRequest.responseXML);return;
	var itemsResult = new mediaItemsResponse(liveRequest.responseXML);
	if(itemsResult.GlobalErrorCode=='500'){
		returnURL = 'http://' + document.location.host + '/video/login.html';
		document.location.href=_OrderURL + "Live/landing.html?r=" + returnURL;
	}	
	else{
		HandleQSAResponseLive(itemsResult);
	}
}

function showError(errormessage)
{
	alert(errormessage);
}

function HandleQSAResponseLive(items)
{//alert("items.Success : " + items.Success);
	var path = window.location.href.toLowerCase();
	var competition;
	if (path.indexOf('/country=')>-1){
		competition =  path.substring(path.indexOf('/video/live/competitions/')+25,path.indexOf('/country='));
	}
	else if (path.indexOf('/landing.html')>-1) {
		competition =  path.substring(path.indexOf('/video/live/competitions/')+25,path.indexOf('/landing.html'));
	}
	else if (path.indexOf('/audiomatchlist')>-1){
		competition =  path.substring(path.indexOf('/video/live/competitions/')+25,path.indexOf('/audiomatchlist'));
	}
	else if (path.indexOf('/mc_landing.html')>-1) {
		if(getArgs().C){
			competition = getArgs().C;
			competition = CompetitionName(competition);
		}
	}
	else {
		competition =  path.substring(path.indexOf('/video/competitions/')+20,path.indexOf('/season='));
	}
	if(items.Success)
	{//alert("items.isAuthorized() : " + items.isAuthorized());
		//user not authorised first check XML to see if the broadcaster capacity is sold out
		var nodeToselect = '//session[match[@code=' + matchToBeLaunched.matchID + ']]/streams/broadcaster[@id=' + matchToBeLaunched.broadcasterID + ']';
		//var matchstatus = selectAttr('/applets/uvs/' + competition + '/UVSLiveStreamsStatus.xml', nodeToselect, 'status');
		var req = new evaluateXPath();
		var res = req.createRequest(competition,"UVSLiveStreamsStatus");
		var matchstatus = req.selectXPath(res,nodeToselect,'status');
		if (matchstatus != 'on') {
			if (items.getnewWin() == 'false') {
				window.location.href = unescape('/video/live/block.html?msg=This stream is unavailable'); 
			}
			else
			{
				fnOpenWindow(unescape('/video/live/block.html?msg=This stream is unavailable'), 'LiveMatch', 'no', 'no', 'no', 'no', 'no', 'no', 'no', 650, 450, '', '');
			}
		}
		else {				
			if(items.isAuthorized())
				{
					if (items.getnewWin() == 'false') {
						//try{
						//	var tokenUrl = items.urlToPlay();
						//	getSwf("LiveVideoPlayer").loadStream(tokenUrl);
						//}
						//catch(e)
						//{
							redirectURL = unescape(items.getReturnURL());//+ "&urlLive=" + items.urlToPlay()
							window.location.href = redirectURL;
						//}
						//redirectURL = unescape(items.getReturnURL());// + "&urlLive=" + items.urlToPlay()
						//window.location.href = redirectURL; 
					}
					else
					{
						fnOpenWindow(unescape(items.getReturnURL()), 'LiveMatch', 'no', 'no', 'no', 'no', 'no', 'no', 'no', 848, 610, '', ''); // + "&urlLive=" + items.urlToPlay()
					}						
				}
			else
				{
					//if(items.getItemErrorCode()=='100' || items.getItemErrorCode()=='110' || items.getItemErrorCode()=='111' || items.getItemErrorCode()=='120' || items.getItemErrorCode()=='130' || items.getItemErrorCode()=='502')
					//	{
					//		//display error - region blocked etc
					//		if (items.getnewWin() == 'false') {
					//			window.location.href = unescape(items.getErrorURL() + items.getItemErrorMessage()); 		
					//		}
					//		else
					//		{
					//			fnOpenWindow(unescape(items.getErrorURL() + items.getItemErrorMessage()), 'LiveMatch', 'no', 'no', 'no', 'no', 'no', 'no', 'no', 650, 450, '', ''); 
					//		}						
					//	}
					//else
					//	{
						//match sale status still on, send user to the Purchase page
						if (matchstatus == 'on') {
							if (items.getnewWin() == 'false') {
								window.location.href = unescape(items.getBuyURL()); 
							}
							else
							{
								fnOpenWindow(unescape(items.getBuyURL()), 'LiveMatch', 'no', 'no', 'no', 'no', 'no', 'no', 'no', 848, 610, '', ''); 
							}
						}
						//match sale status off, send user to a message page
						else {
							if (items.getnewWin() == 'false') {
								window.location.href = unescape(items.getErrorURL() + 'This stream is unavailable'); 
							}
							else
							{
								fnOpenWindow(unescape(items.getErrorURL() + 'This stream is unavailable'), 'LiveMatch', 'no', 'no', 'no', 'no', 'no', 'no', 'no', 848, 610, '', ''); 
							}					
						}
					//}
				}
			}
	}
	else
	{
		if(items.getItemErrorCode()=='100' || items.getItemErrorCode()=='110' || items.getItemErrorCode()=='111' || items.getItemErrorCode()=='120' || items.getItemErrorCode()=='130' || items.getItemErrorCode()=='502')
			{
				//display error
				if (items.getnewWin() == 'false') {
					window.location.href = unescape(items.getErrorURL() + items.getItemErrorMessage()); 		
				}
				else
				{
					fnOpenWindow(unescape(items.getErrorURL() + items.getItemErrorMessage()), 'LiveMatch', 'no', 'no', 'no', 'no', 'no', 'no', 'no', 848, 610, '', ''); 
				}						
			}
		else
			{
				//session expired send to login page return to match page
				if (items.getnewWin() == 'false') {
					window.location.href = unescape(items.getLoginURL()); 
				}
				else
				{
					fnOpenWindow(unescape(items.getLoginURL()), 'LiveMatch', 'no', 'no', 'no', 'no', 'no', 'no', 'no', 848, 610, '', ''); 
				}						
			}
	}

}

function ChkStreamAuth(URL,affiliate,competition,season,matchday,matchID,country,itemID,leadID,channelID,newWin,lang,broadcaster) 
{
	var competitionName;
	var agent = navigator.appName;
	if (!isNaN(parseInt(competition))) { 
		competitionName = CompetitionNameInt(parseInt(competition));
	}
	else { 
		competitionName = competition;	
	}
	var MatchdayOrRound = SetMatchdayRound(competitionName);
	var ReturnParameters = "";
	var returnURL = "";
	var errorURL = escape(baseURL + '/Video/Live/Block.html?msg=')
	var context = encodeURIComponent(document.URL.toLowerCase());
	if (country != "audio"){
		var nodeToselect = "//fixtures/round/matchday/session/match[@code=" + matchID + "]/livevideo[@broadcaster=" + broadcaster + "]/outputCountries/outputCountry[@master = 'true']";
		var req = new evaluateXPath();
		var res = req.createRequest(competitionName,"UVSLiveStreams");
		var masterC = req.selectXPath(res,nodeToselect,'ISOCountryCode');
		var nodeToselect = "//fixtures/round/matchday/session/match[@code=" + matchID + "]/livevideo[@broadcaster=" + broadcaster + "]";
		var player169 = req.selectXPath(res,nodeToselect,'player169');
		//Live popup - live op
		var LoginEntitleCheckURL = escape(_OrderURL + 'Live/landing.html');
		//var is16-9 = player169=="true" ? 'y' : 'n';
		ReturnParameters = 'bc=' + broadcaster + '&16-9=' + ((player169=="true") ? 'y' : 'n') + '&pubpoint=' + URL + '&item=' + itemID;
		returnURL = encodeURIComponent(baseURL + '/Video/Competitions/'+ competitionName +'/Season=' + season + '/' + MatchdayOrRound + '=' + matchday + '/Match=' + matchID + '/ppv_popupFlash.html?' + ReturnParameters);
		var buyURL = escape(_OrderURL + "Live/confirmSelection/index.html?" + "i=" + itemID + "&c=" + competition + "&s=" + season + "&m=" + matchID + "&bc=" + broadcaster + "&aId=" + affiliate + "&affiliation=" + leadID + "&r=" + returnURL);
		var loginURL = LoginEntitleCheckURL;
		/*
		if (readCookie('LiveManSession') == null) {
			if (newWin == 'false') {
				document.location.href= unescape(LoginEntitleCheckURL) + "?i=" + itemID + "&c=" + competition + "&s=" + season + "&m=" + matchID + "&bc=" + broadcaster + "&aId=" + affiliate + "&affiliation=" + leadID + "&r=" + returnURL;
			}
			else{
				fnOpenWindow(unescape(LoginEntitleCheckURL) + "?i=" + itemID + "&c=" + competition + "&s=" + season + "&m=" + matchID + "&bc=" + broadcaster + "&aId=" + affiliate + "&affiliation=" + leadID + "&r=" + returnURL, 'VideoService', 'no', 'no', 'no', 'no', 'no', 'no', 'no', 848, 610, '', ''); 
			}
		} 
		else {
			//alert("itemID :" + itemID + ", _AccountID : " + _AccountID);
			matchToBeLaunched = new match(broadcaster,matchID);
			var item = new mediaItem(_AccountID,'uvs',itemID,returnURL,buyURL,loginURL,errorURL,newWin);
			item.QueryMAN(readCookieParam('LiveManSession','SessionId'),readCookieParam('LiveManSession','Ticket'),handleXmlResponseLive);
		}
		*/
		var lang = "";
		var path = document.location.href.toLowerCase();
		if (path.indexOf('/mc_landing.html')>-1) {
			lang = getArgs().L
		}
		else{
			lang = document.location.host.substring(0,document.location.host.indexOf("."));
		}
		if(lang.length > 2){lang = "en";}
		fnOpenWindow("https://order.matchcentre.com/code/live/content/landingpage/LandingPage.aspx?lang=" + lang + "&i=" + itemID + "&c=" + competition + "&s=" + season + "&m=" + matchID + "&bc=" + broadcaster + "&aId=" + affiliate + (country.toUpperCase() == "IT" ? "&bcCountry=IT" : "") + "&affiliation=" + leadID + "&context=" + context + "&r=" + returnURL, 'VideoService', 'no', 'no', 'no', 'no', 'no', 'no', 'no', 848, 610, '', '');
	}
	else{
		//Audio popup - replay op
		_OrderURL = _OrderURL.replace("order.matchcentre.com","order.uefa.com");
		var LoginEntitleCheckURL = escape(_OrderURL + 'Replay/landing.html');
		ReturnParameters = 'bc=059' + '&pubpoint=' + URL + '&item=' + itemID;
		returnURL = encodeURIComponent(baseURL + '/Video/Competitions/'+ competitionName +'/Season=' + season + '/' + MatchdayOrRound + '=' + matchday + '/Match=' + matchID + '/audio_popupFlash.html?' + ReturnParameters);
		//var buyURL = escape(_OrderURL + "Live/confirmSelection/index.html?" + "i=" + itemID + "&c=" + competition + "&s=" + season + "&m=" + matchID + "&bc=" + broadcaster + "&aId=" + affiliate + "&affiliation=" + leadID + "&r=" + returnURL);
		var buyURL = escape(_OrderURL + "Replay/confirmSelection/index.html?" + "i=" + itemID + "&c=" + competition + "&s=" + season + "&m=" + matchID + "&r=" + returnURL);
		var loginURL = LoginEntitleCheckURL;
		if (readCookie('manSession') == null) {
			if (newWin == 'false') {
				document.location.href= unescape(LoginEntitleCheckURL) + "?i=" + itemID + "&s=" + season + "&m=" + matchID + "&context=" + context + "&r=" + returnURL;
			}
			else{
				fnOpenWindow(unescape(LoginEntitleCheckURL) + "?i=" + itemID + "&s=" + season + "&m=" + matchID + "&context=" + context + "&r=" + returnURL, 'VideoService', 'no', 'no', 'no', 'no', 'no', 'no', 'no', 848, 610, '', ''); 
			}
		} 
		else {
			//alert("itemID :" + itemID + ", _AccountID : " + _AccountID);
			matchToBeLaunched = new match(broadcaster,matchID);
			var item = new mediaItem(_AccountID,'uvs',itemID,returnURL,buyURL,loginURL,errorURL,newWin,'','');
			item.QueryMAN(readCookieParam('manSession','SessionId'),readCookieParam('manSession','Ticket'),handleXmlResponseLive);
		}
	} 
} 

function match(broadcasterID,matchID)
{
	this.broadcasterID = broadcasterID;
	this.matchID = matchID;
	//this.leadID = leadID;
}

function getSwf(name)
{
	if (navigator.appName.indexOf("Microsoft") != -1) {
		return window[name];
	} else {
		return document[name];
	}	
}
