// variavel global que serve para consultar se o player está tocando algo ou não
var playerOn = false;
var autoPlayerStart = true;

function playFLV(divName,id,cod){
	flashembed(divName, 
		{
		   src: 'inc/player18.swf',
		   width: '512',  
		   height: 382,
		   bgcolor: '#000000'
		},
		{config: fpConf}
	);
	playerOn = true;
	if(cod !='')
		buscaVideoInfo(id, cod);
	
}
//TODO=reescrever usando jquery
function playWMV(divName, id, cod){
	document.getElementById('divPlayer').innerHTML = '';
	newIframe = document.createElement('iframe');
	newIframe.setAttribute('width', '100%');
	newIframe.setAttribute('height', '100%');
	newIframe.setAttribute('frameBorder', '0');
	newIframe.setAttribute('scrolling', 'No');
	url = './v7/video/?lar=512&alt=382&id='+id;
	if(cod != '') url += '&cod='+cod;
	newIframe.setAttribute('src', url);
	document.getElementById('divPlayer').appendChild(newIframe); 
	playerOn = true;
	
	buscaVideoInfo(id, cod);
	
	
}
function showPlayerPlay(){
	if(!playerOn){
		document.getElementById('divPlayerPlay').style.visibility='visible';
	}
}

//function dhtmlLoadScript(url){
//  var e = document.createElement("script");
//   e.src = url;
//   e.type="text/javascript";
//   document.getElementsByTagName("head")[0].appendChild(e); 
//}

function dhtmlLoadScript2(scriptUrl,idCanal,codV){
	$.ajax({ type: "POST", 
                     url: scriptUrl, 
                     data: "" , 
                     dataType: "script", 
                     success: function(data){ 
                        playFLV('divPlayer',idCanal,codV); 
                     } 
                   }); 
}
function dhtmlLoadScript(scriptUrl){
	$.ajax({ type: "POST", 
                     url: scriptUrl, 
                     data: "" , 
                     dataType: "script", 
                     success: function(data){ 

                     } 
                   }); 
}
function aleatorio(inferior,superior){
    numPossibilidades = superior - inferior
    aleat = Math.random() * numPossibilidades
    aleat = Math.floor(aleat)
    return parseInt(inferior) + aleat
}
function reduzTexto(texto,numero) {
	if (texto.length > numero)
		texto = texto.substring(0,numero-2)+"[...]";
	return texto;
}
function trocaImg(a,img) {
	b = document.getElementById(a);
	b.src = img;
}
function addEvent(objId,evType,fn,useCapture){
	var ret=false;
	obj = document.getElementById(objId);
	if(obj!=null){
		if(obj.addEventListener){
			obj.addEventListener(evType,fn,useCapture);
			ret=true;
		}
		else if(obj.attachEvent){
			obj.attachEvent('on'+evType,fn);
			ret=true;
		}
	}
	return ret;
}


function buscaVideoInfo(id, cod){
	var url = "./lib/getVideoDetalhes/?cod="+cod+"&id="+id;
	var pars = ''	
	//var myAjax = new Ajax.Request(urlBlogFeed,{method: 'get', parameters: pars, onComplete: escreveSiteNews});
	 $.ajax({
	   type: "GET",
	   url: url,
	   data: "",
	   success: function(msg){
	     escreveVideoInfo(msg);
	   }
	 });
}
function escreveVideoInfo(originalRequest){

	var v = originalRequest.getElementsByTagName("channel");
	var urlPonto = "";
	for(i=0; i < v.length; i++) {
		for (j=0;j<v[i].childNodes.length;j++) {
			if (v[i].childNodes[j].nodeName == "title") {
				titulo = v[i].childNodes[j].firstChild.nodeValue
			}
			if (v[i].childNodes[j].nodeName == "shortdesc") {
				sinopse = v[i].childNodes[j].firstChild.nodeValue
			}
			if (v[i].childNodes[j].nodeName == "tags") {
				tags = v[i].childNodes[j].firstChild.nodeValue
			}
			if (v[i].childNodes[j].nodeName == "pubDate") {
				publicacao = v[i].childNodes[j].firstChild.nodeValue
			}
		}
	}

	document.getElementById('divTituloVid').innerHTML = titulo;
//	document.getElementById('divTimeVid').innerHTML = publicacao;
	document.getElementById('divDescriptionVid').innerHTML = sinopse;	
	//document.getElementById('divTagsVid').innerHTML = "<b>Tags:</b> &nbsp;"+tags;
}


function initPlay(id){
	buscaPontoExecInfo(id);
}
function buscaPontoExecInfo(id){
	var url = "./lib/getXML/getPontoexec.php?id="+id;
	var pars = ''	
	//var myAjax = new Ajax.Request(urlBlogFeed,{method: 'get', parameters: pars, onComplete: escreveSiteNews});
	 $.ajax({
	   type: "GET",
	   url: url,
	   data: "",
	   success: function(msg){
	     escrevePontoexec(msg);
	   }
	 });
}
function escrevePontoexec(originalRequest){
	var v = originalRequest.getElementsByTagName("pontoexec");
	var urlPonto = "";
	for(i=0; i < v.length; i++) {
		for (j=0;j<v[i].childNodes.length;j++) {
			if (v[i].childNodes[j].nodeName == "code") {
				codigoPonto = v[i].childNodes[j].firstChild.nodeValue
			}
			if (v[i].childNodes[j].nodeName == "name") {
				nomePonto = v[i].childNodes[j].firstChild.nodeValue
			}
			if (v[i].childNodes[j].nodeName == "url") {
				urlPonto = v[i].childNodes[j].firstChild.nodeValue;
				if(urlPonto != "n/d" && urlPonto != "") urlPonto = "<a href=\""+urlPonto+"\" target=\"_blank\">"+urlPonto+"</a>";
			}
			if (v[i].childNodes[j].nodeName == "client") {
				for (k=0;k<v[i].childNodes[j].childNodes.length;k++) {
					if(v[i].childNodes[j].childNodes[k].nodeName == "code"){
						codigoCliente = v[i].childNodes[j].childNodes[k].firstChild.nodeValue;
					}
					if(v[i].childNodes[j].childNodes[k].nodeName == "name"){
						nomeCliente = v[i].childNodes[j].childNodes[k].firstChild.nodeValue;
					}
				}
			}
			if (v[i].childNodes[j].nodeName == "media_format") {
				for (k=0;k<v[i].childNodes[j].childNodes.length;k++) {
					if(v[i].childNodes[j].childNodes[k].nodeName == "name"){
						nomeFormato = v[i].childNodes[j].childNodes[k].firstChild.nodeValue;
					}
					if(v[i].childNodes[j].childNodes[k].nodeName == "ext"){
						ext = v[i].childNodes[j].childNodes[k].firstChild.nodeValue;
					}
					if(v[i].childNodes[j].childNodes[k].nodeName == "bitrate"){
						bitrate = v[i].childNodes[j].childNodes[k].firstChild.nodeValue;
					}
				}
			}
		}
	}
	if(ext == "flv" || ext == "mp4"){
		tipoPlayer = "flash";
	}
	else{
		tipoPlayer = "wm";
	}
	document.getElementById('divInfoCanal').innerHTML = "Canal: <b>" + nomePonto + "</b>";
	buscaPlaylist(codigoPonto, tipoPlayer, 0);
}


function buscaPlaylist(id, tipo_player, start) {
	var urlPlaylistFeed = "./lib/getXML/?id="+id+"&s="+start+"&i=4";
	var pars = ''	
	//var myAjax = new Ajax.Request(urlBlogFeed,{method: 'get', parameters: pars, onComplete: escreveSiteNews});
	 $.ajax({
	   type: "GET",
	   url: urlPlaylistFeed,
	   data: "",
	   success: function(msg){
	     escrevePlaylist(msg, id, tipo_player);
	   }
	 });
}
function escrevePlaylist(originalRequest, idCanal, tipo_player){
	//tree = originalRequest.responseXML;
	var v = originalRequest.getElementsByTagName("item");
	var zli = ""
	var cntItm = 0;
	var firstVid = "";

	// Pega informacoes sobre a lista de resultados
	var tmp = originalRequest.getElementsByTagName("qtdItens");
	qtd_itens = tmp[0].firstChild.nodeValue;
	var tmp = originalRequest.getElementsByTagName("listItensStart");
	itens_start = tmp[0].firstChild.nodeValue;
	var tmp = originalRequest.getElementsByTagName("listItensLimit");
	itens_limit = tmp[0].firstChild.nodeValue;

	for(i=0; i < v.length; i++) {
		x = "";
		if(v[i].getAttribute("tp") != "institucional"){ // exclui os institucionais
			for (j=0;j<v[i].childNodes.length;j++) {
				if (v[i].childNodes[j].nodeType != 1) continue;
				if (v[i].childNodes[j].nodeName == "cod") {
					var cod = v[i].childNodes[j].firstChild.nodeValue
					if(firstVid == "") firstVid = cod; // SALVA O PRIMEIRO VÍDEO PARA CARREGAR OS DADOS NA ÁREA DE DESCRIÇÃO
				}
				if (v[i].childNodes[j].nodeName == "title") {
					var titulo = v[i].childNodes[j].firstChild.nodeValue
				}
				if (v[i].childNodes[j].nodeName == "link") {
					var imagem = v[i].childNodes[j].firstChild.nodeValue
				}
				if (v[i].childNodes[j].nodeName == "pubDate") {
					var datapub = v[i].childNodes[j].firstChild.nodeValue
				}
				if (v[i].childNodes[j].nodeName == "description") {
				    try{
					   var descricao = v[i].childNodes[j].firstChild.nodeValue
					} catch(e){
					   var descricao = "&nbsp;"
					}
				}
				if (v[i].childNodes[j].nodeName == "link") {
					var linke = v[i].childNodes[j].firstChild.nodeValue
				}
			}
//			if (cntItm<=4){
				if(tipo_player == 'flash'){
					var funcaoClique = "dhtmlLoadScript2('lib/getVideoUrl/index.php?id="+idCanal+"&cod="+cod+"', "+idCanal+" ,"+cod+")";
				}else{
					var funcaoClique = "playWMV('divPlayer', "+idCanal+", "+cod+")";
				}
				zli += "<div class=\"divPlaylistItem\" onclick=\""+funcaoClique+"\" onMouseOver=\"this.style.backgroundColor='#677E94';document.getElementById('imgvid_"+idCanal+"_"+cod+"').style.visibility='visible';\" onMouseOut=\"this.style.backgroundColor='#677E94';document.getElementById('imgvid_"+idCanal+"_"+cod+"').style.visibility='hidden';\">";
				zli += "	<div class=\"imagem\" style=\"background-image:url('"+imagem+"'); background-repeat: no-repeat; background-position: center; background-color:#313131;\" title=\"Clique para assistir\">";
				zli += "	   <img src=\"img/h_play.png\" id=\"imgvid_"+idCanal+"_"+cod+"\" alt=\"\" style=\"margin-left:15px; margin-top:3px; visibility:hidden;\" />";
				zli += "	</div>";
				zli += "	<div class=\"titulo txtbold\">"+titulo+"</div>";
//				zli += "	<div class=\"data\">"+datapub+"</div>";
				zli += "	<div class=\"descricao\">"+reduzTexto(descricao,120)+"</div>";
				zli += "</div>";
//			}
//			cntItm++;
		}
	} 

	/*****************************
	  Paginador JS
	 */
	zli += "<div id=\"paginacao\" class=\"descricao\">";
    var total = Math.ceil(qtd_itens/itens_limit);
	var	inimostra = (Math.ceil(itens_start/itens_limit));
    var maxmostra = 3;
 	if (total > maxmostra+1) {
	    maxmostra = maxmostra+(inimostra*1);
	    if (maxmostra > total) {
	 	   maxmostra = total;
	    }
    } else{
 	    maxmostra = total;
	}
	if(inimostra != 0) {
		zli +=  "<span onClick=\"buscaPlaylist("+idCanal+", '"+tipo_player+"', 0);\")\" title=\"primeira\">&lt;&lt;</span>&nbsp;&nbsp;&nbsp;";
		zli +=  "<span onClick=\"buscaPlaylist("+idCanal+", '"+tipo_player+"', "+((inimostra-1)*4)+");\")\" title=\"anterior\">&lt;</span>&nbsp;&nbsp;";
	}	
	for (i = inimostra+1; i<=maxmostra; i++) {
		if(i == inimostra+1){
			var classSelected = "class=\"activePage\"";
		} else
			var classSelected = "";
		zli +=  " <span "+classSelected+" onClick=\"buscaPlaylist("+idCanal+", '"+tipo_player+"', "+((i-1) * 4)+");\")\" title=\"ir para página "+i+"\">"+i+"</span> |" ;
	}
	if(maxmostra != total){
		zli +=  "&nbsp;&nbsp;<span onClick=\"buscaPlaylist("+idCanal+", '"+tipo_player+"', "+((inimostra+1)*itens_limit)+");\")\" title=\"próxima\">&gt;</span> ";
		zli +=  "&nbsp;&nbsp;&nbsp;<span onClick=\"buscaPlaylist("+idCanal+", '"+tipo_player+"', "+idCanal+", "+((total-1)*4)+")\" title=\"última\">&gt;&gt;</span> ";
	}
	zli += "</div>"

	var d = document.getElementById('divPlaylistList');
	d.innerHTML = zli;
	
	// APÓS CARREGAR O PLAYLIST, CARREGA AS INFORMAÇÕES DO PRIMEIRO VÍDEO	
	if(tipo_player == "flash"){
		if(autoPlayerStart){
			dhtmlLoadScript('lib/getVideoUrl/index.php?ap=1&loop=1&id='+idCanal);
		} else{
			dhtmlLoadScript('lib/getVideoUrl/index.php?id='+idCanal+'&cod='+firstVid);
			dplay = "<div style=\"width:100%; height:100%;\" onClick=\"playFLV('divPlayer',"+idCanal+","+cod+")\" onMouseOut=\"document.getElementById('divPlayerPlay').style.visibility='hidden';\"></div>";
	//		addEvent('divPlayerPlay','click', playFLV('divPlayer'));
			document.getElementById("divPlayer").style.height = "384px";
			document.getElementById("divPlayerFora").style.height = "384px";
	//		document.getElementById("divPlayerFora").style.backgroundImage = "url('./img/bagualismotv-fundo_flash.jpg')";
			document.getElementById("divPlayerFora").style.backgroundColor = "black";
			document.getElementById("divDescription").style.top = "20px";
			document.getElementById("divDescription").style.height = "196px";
			var d = document.getElementById('divPlayerPlay');
			d.innerHTML = dplay;			
		}
	}
	else{
		dplay = "<div style=\"width:100%; height:100%;\" onClick=\"playWMV('divPlayer', "+idCanal+", "+cod+")\" onMouseOut=\"document.getElementById('divPlayerPlay').style.visibility='hidden';\"></div>";
//		document.getElementById("divPlayer").style.height = "341px";
//		document.getElementById("divPlayer").style.backgroundImage = "url('./img/fundo512z_2a.jpg')";
//		document.getElementById("divDescription").style.top = "354px";
//		document.getElementById("divPlaylist").style.height = "453px";
		
//		addEvent('divPlayerPlay','click', playWMV('divPlayer', idCanal, ''));
		var d = document.getElementById('divPlayerPlay');
		d.innerHTML = dplay;
	}
}


/*************************
     Hotmedia API
*************************/
HotAPI = {
	 resizeDiv: function(){
	
		var firefox = false;
		var myHeight = 0, myWidth = 0; 
		var containerAcoesHeight = 0;
	
		// Obtém a largura de altura da janela
		if( typeof( window.innerWidth ) == "number" ) {
			//Non-IE
			myWidth = window.innerWidth;
			myHeight = window.innerHeight;
			firefox = true;
		} else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
			//IE 6+ in 'standards compliant mode'
			myWidth = document.documentElement.clientWidth;
			myHeight = document.documentElement.clientHeight;
		} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
			//IE 4 compatible
			myWidth = document.body.clientWidth;
			myHeight = document.body.clientHeight;
		}
	
		var el = document.getElementById('midintesq');
		if (firefox) {
			//containerAcoesHeight = containerAcoesHeight + 15;
			el.style.height = (myHeight - containerAcoesHeight - 140) + 'px';
		} else {
			el.style.height = (myHeight - containerAcoesHeight -140) + 'px';
		}
	 	
	 },
	 log: function(msg) {

	 },
	 abreJanelaPlayer: function(nomejanela, pagina, largura, altura, barra){
		eval('janela = window.open("'+pagina+'","' + nomejanela + '","width='+largura+',height='+altura+',top=50,left=150' +
			  ',scrollbars=no,hscroll=0,dependent=no,toolbar='+barra+'")');
		janela.focus();	 
	 }
}

function openAjuda() {
   var url = 'ajuda.html';
   window.open(url, 'wnd', 'width=900, height=450, toolbar=no, copyhistory=no, location=no, status=yes, menubar=no, scrollbars=yes, resizable=no, top=0, left=0');
}