// variavel global que serve para consultar se o player está tocando algo ou não
var playerOn = false;
var mapView = 'padrao';

function loadGoogleMaps(){
	status = document.getElementById('divGMap').style.visibility;
	if(mapView == 'padrao'){
		document.getElementById('divGMap').style.visibility = 'visible';
		document.getElementById('linkGMap').innerHTML = '<img src="img/img_maps.gif" width="27" height="19" alt="" style="vertical-align:top;" />ver mapa padrão'
		mapView = 'gmaps';
	}
	else{ 
		document.getElementById('divGMap').style.visibility = 'hidden';
		document.getElementById('linkGMap').innerHTML = '<img src="img/img_maps.gif" width="27" height="19" alt="" style="vertical-align:top;" />ver no Google Maps'
		mapView = 'padrao';
	}
}
function playFLV(divName){
	flashembed(divName, 
		{
		   src: 'inc/player18.swf',
		   width: '512',  
		   height: 288,
		   bgcolor: '#000000'
		},
		{config: fpConf}
	);
	playerOn = true;
}
//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 = '../eventos/v7/video/?lar=512&alt=288&id='+id;
	if(cod != '') url += '&cod='+cod;
	newIframe.setAttribute('src', url);
	document.getElementById('divPlayer').appendChild(newIframe); 
	playerOn = true;
}
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){
	$.ajax({ type: "POST", 
                     url: scriptUrl, 
                     data: "" , 
                     dataType: "script", 
                     success: function(data){ 
                        playFLV('divPlayer'); 
                     } 
                   }); 
}
function dhtmlLoadScript(scriptUrl){
	$.ajax({ type: "POST", 
                     url: scriptUrl, 
                     data: "" , 
                     dataType: "script", 
                     success: function(data){ 

                     } 
                   }); 
}
function init(){
    var img = "./img/zionhd/h_superbanner_zionhd"+aleatorio(1,6)+".jpg";
	//var img = "./img/zionhd/h_superbanner_zionhd.jpg";
    el = document.getElementById('zionHDarea');
	el.style.background = "url("+img+")";
	buscaNews();
}
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 buscaNews() {
	var urlBlogFeed = "./lib/getFeed/"
	var pars = ''	
	//var myAjax = new Ajax.Request(urlBlogFeed,{method: 'get', parameters: pars, onComplete: escreveSiteNews});
	 $.ajax({
	   type: "GET",
	   url: urlBlogFeed,
	   data: "",
	   success: function(msg){
	     escreveSiteNews(msg);
	   }
	 });
}
function escreveSiteNews(originalRequest){
	//tree = originalRequest.responseXML;
	var v = originalRequest.getElementsByTagName("item");
	var zli = ""
	for(i=0; i < v.length; i++) {
		x = "";
		for (j=0;j<v[i].childNodes.length;j++) {
			if (v[i].childNodes[j].nodeType != 1) continue;
			if (v[i].childNodes[j].nodeName == "title") {
				var titulo = v[i].childNodes[j].firstChild.nodeValue
				x += v[i].childNodes[j].nodeName + ": " + v[i].childNodes[j].firstChild.nodeValue + "\r";
			}
			if (v[i].childNodes[j].nodeName == "description") {
				var descricao = v[i].childNodes[j].firstChild.nodeValue
				x += v[i].childNodes[j].nodeName + ": " + v[i].childNodes[j].firstChild.nodeValue + "\r";				
			}
			if (v[i].childNodes[j].nodeName == "link") {
				var linke = v[i].childNodes[j].firstChild.nodeValue
				x += v[i].childNodes[j].nodeName + ": " + v[i].childNodes[j].firstChild.nodeValue + "\r";				
			}
		}
		if (i<=2){
			var border = "";
			if (i < 2){
				border = "border-right:solid 1px #BABABA;"
			}
			zli += "<div style=\"float:left; width:290px; background-image:url('img/h_rss_bullet"+(i+1)+".gif'); "+border+" background-repeat:no-repeat; background-position:top left; margin-left:15px;\">";
			zli += "	<div style=\"float:right; width:230px; margin-right:15px; margin-top:-8px;\" ><a target=\"_blank\" href=\""+linke+"\" class=\"txtbold\">"+titulo+"</a> - <span>"+reduzTexto(descricao,190)+"</span></div>";
			zli += "</div>";
		}
	} 
	zli += ""
	var d = document.getElementById('newsrss');
	d.innerHTML = zli;
}
function initPlay(id){
	buscaPontoExecInfo(id);
	//HotAPI.resizeDiv();
}
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('divDescriptionCli').innerHTML = "<div class=\"titulo txtbold\">Cliente: "+nomeCliente+"</div>";
	document.getElementById('divUrlPon').innerHTML = "<div class=\"titulo\">Site Oficial: "+urlPonto+"</div>";
	document.getElementById('divDescriptionPon').innerHTML = "<div class=\"data\">Canal: "+nomePonto+"</div>";
	document.getElementById('divDescriptionFor').innerHTML = "<div class=\"data\">Formato: "+nomeFormato+" ("+bitrate+")</div>";
//addEvent(objId,evType,fn,useCapture)
	buscaPlaylist(codigoPonto, tipoPlayer, 5, 0);

}
function buscaPlaylist(id, tipo_player, intervalo, start) {
	if(start && intervalo)
		var urlPlaylistFeed = "./lib/getXML/?id="+id+"&s="+start+"&i="+intervalo;
    else if(intervalo)
		var urlPlaylistFeed = "./lib/getXML/?id="+id+"&s=0&i="+intervalo;
	else
		var urlPlaylistFeed = "./lib/getXML/?id="+id
	var pars = ''	
	 $.ajax({
	   type: "GET",
	   url: urlPlaylistFeed,
	   data: "",
	   success: function(msg){
	     escrevePlaylist(msg, id, tipo_player);
	   }
	 });
}
function escrevePlaylist(originalRequest, idCanal, tipo_player){
	//tree = originalRequest.responseXML;
	
	// Pega informacoes sobre a lista de resultados
	var v = originalRequest.getElementsByTagName("qtdItens");
	qtd_itens = v[0].firstChild.nodeValue;
	var v = originalRequest.getElementsByTagName("listItensStart");
	itens_start = v[0].firstChild.nodeValue;
	var v = originalRequest.getElementsByTagName("listItensLimit");
	itens_limit = v[0].firstChild.nodeValue;
	
	var v = originalRequest.getElementsByTagName("item");
	var zli = ""
	var firstVid = "";

	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(tipo_player == 'flash'){
                var TpClique = "dhtmlLoadScript2('lib/getVideoUrl/index.php?id="+idCanal+"&cod="+cod+"')";
            }else{
                var TpClique = "playWMV('divPlayer', "+idCanal+", "+cod+")";
            }
            zli += "<div class=\"divPlaylistItem\" onClick=\""+TpClique+"\" onMouseOver=\"this.style.backgroundColor='#989898';document.getElementById('imgvid_"+idCanal+"_"+cod+"').style.visibility='visible';\" onMouseOut=\"this.style.backgroundColor='#8E8E8E';document.getElementById('imgvid_"+idCanal+"_"+cod+"').style.visibility='hidden';\" title=\"Clique para assistir\">";
            zli += "    <div class=\"imagem\" style=\"background-image:url('"+imagem+"'); background-repeat: no-repeat; background-position: center; background-color:#313131;\">";
            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,130)+"</div>";
            zli += "</div>";
		}
	}
	/*****************************
	  Paginador JS
	 */
	zli += "<div id=\"paginador\">";
    var total = Math.ceil(qtd_itens/itens_limit);
	var	inimostra = (Math.ceil(itens_start/itens_limit));
    var maxmostra = 4;
 	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+"', 5, 0);\")\" title=\"primeira\">&lt;&lt;</span>&nbsp;&nbsp;&nbsp;";
		zli +=  "<span onClick=\"buscaPlaylist("+idCanal+", '"+tipo_player+"', 5, "+((inimostra-1)*5)+");\")\" 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+"', 5, "+((i-1) * 5)+");\")\" title=\"ir para página "+i+"\">"+i+"</span> |" ;
	}
	if(maxmostra != total){
		zli +=  "&nbsp;&nbsp;<span onClick=\"buscaPlaylist("+idCanal+", '"+tipo_player+"', 5, "+((inimostra+1)*itens_limit)+");\")\" title=\"próxima\">&gt;</span> ";
		zli +=  "&nbsp;&nbsp;&nbsp;<span onClick=\"buscaPlaylist("+idCanal+", '"+tipo_player+"', 5, "+((total-1)*5)+");\")\" title=\"última\">&gt;&gt;</span> ";
	}
	zli += "</div>"
	/***************************/
 
	var d = document.getElementById('divPlaylist');
	d.innerHTML = zli;
	
	// APÓS CARREGAR O PLAYLIST, CARREGA AS INFORMAÇÕES DO CANAL	
	if(tipo_player == "flash"){
//		dhtmlLoadScript('lib/getVideoUrl/index.php?id='+idCanal+'&cod='+firstVid);
		dhtmlLoadScript('lib/getVideoUrl/index.php?id='+idCanal);
		dplay = "<div style=\"width:100%; height:100%;\" onClick=\"playFLV('divPlayer')\" onMouseOut=\"document.getElementById('divPlayerPlay').style.visibility='hidden';\"></div>";
//		addEvent('divPlayerPlay','click', playFLV('divPlayer'));
		document.getElementById("divPlayer").style.height = "288px";
		document.getElementById("divPlayer").style.backgroundImage = "url('./img/fundo512z_2.jpg')";
		document.getElementById("divDescription").style.top = "301px";
		document.getElementById("divDescription").style.height = "203px";
	}
	else{
		dplay = "<div style=\"width:100%; height:100%;\" onClick=\"playWMV('divPlayer', "+idCanal+", '')\" 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) {

	 },
	 openBluesky: function(){
		var ponto = "http://www.hotmedia.com.br/radiobluesky/l2/zplayer.php?"
		this.abreJanelaPlayer('RadioBluesky', ponto, 470, 160, 'no')	 		 
	 },
	 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();	 
	 }
}