/* PNG TRANSPARENTE */
var blank = new Image();
blank.src = '/imgs/pix.gif';
function fixPng(png) {
	// get src
	var src = png.src;
	// set width and height
	if (!png.style.width) { png.style.width = $(png).width(); }
	if (!png.style.height) { png.style.height = $(png).height(); }
	// replace by blank image
	png.onload = function() { };
	png.src = blank.src;
	// set filter (display original image)
	png.runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + src + "',sizingMethod='scale')";
}

$(document).ready(function() {
	/* PNGs */
	var badBrowser = (/MSIE ((5\.5)|6)/.test(navigator.userAgent) && navigator.platform == "Win32");
	if (badBrowser) $('img[src$=.png]').each(function() {
		if (!this.complete) this.onload = function() { fixPng(this) };
		else fixPng(this);
	});
});

/*

Enquete

*/
function enqueteVotar(vCod,vArea,objCodOpcao) {
	for (i=0;i<objCodOpcao.length;i++) {
		if (objCodOpcao[i].checked) vCodOpcao = objCodOpcao[i].value;
	}
	var url="ajax/enquetes.asp?sid=" + Math.random() + "&vCod=" + vCod + "&vArea=" + vArea + "&vCodOpcao=" + vCodOpcao
	document.getElementById("enqueteVotos").innerHTML = "<span class=\"carregando\">Carregando...</span>";
	xmlHttpEnquete=GetXmlHttpObject(enqueteChegou)
	xmlHttpEnquete.open("GET", url , true)
	xmlHttpEnquete.send(null)
} 

function enqueteChegou() {
	if (xmlHttpEnquete.readyState==4 || xmlHttpEnquete.readyState=="complete") { 
		if (xmlHttpEnquete.responseText != "") {
			document.getElementById("enqueteVotos").innerHTML = xmlHttpEnquete.responseText;
		} else {
			document.getElementById("enqueteVotos").innerHTML = "<span class=\"carregando\">Falha no carregamento.</span>";
		}
	}
}

function muda(campo, q, m, total){
	clearInterval(eval(campo));
	eval("qtd" + campo + " =  1");
	for (i=0;i<total;i++){
		try{
			document.getElementById(campo + (i+1)).style.display = "none";
		}catch(e){}
	}
	for (i=m;i<m+eval("qtd" + campo);i++){
		for (j = 0; j < q; j++){
			try{
				document.getElementById(campo + (i+j+1)).style.display = "";
			}catch(e){}
		}
	}
	m += q;
	if(m>=total)
		m = 0;
	eval(campo + "= setInterval(\"muda('"+campo+"', "+q+","+m+", "+total+")\",5000)");
}

lefttime=null;
posicao = 0;
velocidade = 9;
iedom=document.all||document.getElementById;

function moveDiv(id,direcao,tamanho){
	//clearInterval(destaqueTimer);
	cross_slide=document.getElementById? document.getElementById(id) : document.all.imovel
	larg = cross_slide.style.width.replace("px","");

	if ((posicao+velocidade <= 0 && direcao > 0) || (posicao-velocidade >= larg*-1 && direcao < 0 && posicao-velocidade >= (parseInt(larg) - parseInt(tamanho * parseFloat((larg/tamanho)-parseInt(larg/tamanho)))) * -1) && posicao-tamanho > larg*-1) {
		if (lefttime==null)
			lefttime=setInterval("moveDiv('"+id+"',"+direcao+","+tamanho+")",30);
		if (direcao < 0) {
			posicao -= velocidade;
		} else if (direcao > 0) {
			posicao += velocidade;
		}
		if (iedom){
			cross_slide.style.left=posicao+"px";
		}
		if ((posicao % tamanho == 0)) {
			clearInterval(lefttime);
			lefttime = null;
		}
	}else{
		clearInterval(lefttime);
		lefttime = null;
	}
}

function adicionaAoEventoLoad(fn) {
	if (window.attachEvent) {
		window.attachEvent("onload", fn);
	} else {
		window.addEventListener("load", fn, false);
	}
}

function removeTodosOsFilhos(el) {
	for (i = el.childNodes.length-1;i >= 0;i--) {
		el.removeChild(el.childNodes[i]);
	}
}

// Youtube Functions
var delayLoadRegistry=[];
var delayLoadCompleted=[];
function delayLoad(id,img,src){
	delayLoadRegistry[delayLoadRegistry.length]=[id,img,src];
	delayLoadCompleted[id]=false;
}

function performDelayLoad(id){
	if(!delayLoadCompleted[id]){
		delayLoadCompleted[id]=true;
		for(var i=0;i<delayLoadRegistry.length;i++){
			if(delayLoadRegistry[i][0]==id){
				delayLoadRegistry[i][1].onload="";
				delayLoadRegistry[i][1].src=delayLoadRegistry[i][2];
			}
		}
	}
}

// Youtube Functions

var xmlHttp;
var xmlHttpPrimeiroVideo;
var qpp;
var queryBusca;
function buscarVideos(start,quant,query){
	qpp = quant;
	queryBusca = query;
	removeTodosOsFilhos(document.getElementById("more_channel_videos"));
	img = document.createElement("img");
	img.src = "imgs/loading.gif";
	img.alt = "carregando";
	img.className = "loading";
	document.getElementById("more_channel_videos").appendChild(img);
	var url = "videos/videos.asp?a="+Math.floor(Math.random()*1000000)+"&user="+user;
	if(parseInt(start) == 0){
		url = url + "&s=1";
	}else if(parseInt(start) > 0){
		url = url + "&s="+parseInt(start);
	}

	if(parseInt(quant) > 0){
		url = url + "&q="+parseInt(quant);
	}else{
		url = url + "&q=20";
	}

	if(query != ""){
		url = url + "&qr="+query;
	}
	xmlHttp=GetXmlHttpObject(chegouVideos);
	xmlHttp.open("GET", url , true);
	xmlHttp.send(null);
}

var quantToWrite;
var carregar;
var f;
var ondeEscrever;

function carregaTopVideos(start,quant,query,top,carrega,onde,fc){
	quantToWrite = top;
	carregar = carrega;
	ondeEscrever = onde;
	f = fc;
	var url = "videos/videos.asp?a="+Math.floor(Math.random()*1000000)+"&user="+user;
	if(parseInt(start) == 0){
		url = url + "&s=1";
	}else if(parseInt(start) > 0){
		url = url + "&s="+parseInt(start);
	}

	if(parseInt(quant) > 0){
		url = url + "&q="+parseInt(quant);
	}else{
		url = url + "&q=20";
	}

	if(query != ""){
		url = url + "&qr="+query;
	}
	xmlHttpPrimeiroVideo=GetXmlHttpObject(chegouTopVideos);
	xmlHttpPrimeiroVideo.open("GET", url , true);
	xmlHttpPrimeiroVideo.send(null);
}

function chegouTopVideos() {
	// Coloca o primeiro vídeo pra tocar.
	if (xmlHttpPrimeiroVideo.readyState==4 || xmlHttpPrimeiroVideo.readyState=="complete") { 
		if (xmlHttpPrimeiroVideo.responseXML != null) {
			xmlDoc = xmlHttpPrimeiroVideo.responseXML;
			var root = xmlDoc.getElementsByTagName('entry');
			if (f != ""){
				removeTodosOsFilhos(document.getElementById(ondeEscrever));
			}
			for(k=0;k<quantToWrite;k++){
				var node = root.item(k);
				if (f != ""){
					f(node);
				}
				if (carregar){
					
					try {
						var descricao = escape(node.getElementsByTagName("description")[0].childNodes[0].nodeValue);	
					}catch(e){
						var descricao = "";
					}
					
					carregaVideo(node.getElementsByTagName('content')[1].getAttribute('url'),escape(node.getElementsByTagName("title")[0].childNodes[0].nodeValue),descricao);
				}
			}
		}
	}
}

var encN=1;

// ENCODES, IN UNICODE FORMAT, ALL TEXT AND THEN ESCAPES THE OUTPUT
function encodeTxt(s){
	s=escape(s);
	var ta=new Array();
	for(i=0;i<s.length;i++)ta[i]=s.charCodeAt(i)+encN;
	return ""+escape(eval("String.fromCharCode("+ta+")"))+encN;
}

// DENCODES, IN UNICODE FORMAT, ALL TEXT AND THEN UNESCAPES THE OUTPUT
function dF(s){
	var s1=unescape(s.substr(0,s.length-1)); var t='';
	for(i=0;i<s1.length;i++)t+=String.fromCharCode(s1.charCodeAt(i)-s.substr(s.length-1,1));
		str = unescape(t);
	return str;
}

function separaString(str,pos){
	var novaStr = dF(str);
	var arrStr = novaStr.split("/////");
	return arrStr[pos];
}

function preencheInicial(no){
	ul = document.getElementById("videos");
	li = document.createElement("li");

	// CRIAR IMAGEM
	img = document.createElement("img");
	img.src = no.getElementsByTagName("thumbnail")[0].getAttribute('url');
	img.border = "0";
	img.width = 72;
	img.height = 52;

	a = document.createElement("a");
	a.href = "videos/?vVideo=" + encodeTxt(no.getElementsByTagName("content")[1].getAttribute('url')+"/////"+no.getElementsByTagName("title")[0].childNodes[0].nodeValue);
	a.appendChild(img);
	
	div = document.createElement("div");
	div.className = "imagem";
	div.appendChild(a);
	
	li.appendChild(div);

	// CRIAR TEXTO

	a = document.createElement("a");
	a.href = "videos/?vVideo=" + encodeTxt(no.getElementsByTagName("content")[1].getAttribute('url')+"/////"+no.getElementsByTagName("title")[0].childNodes[0].nodeValue+"/////"+no.getElementsByTagName("description")[0].childNodes[0].nodeValue);
	a.appendChild(document.createTextNode(no.getElementsByTagName("title")[0].childNodes[0].nodeValue));
	
	li.appendChild(a);
	li.appendChild(document.createElement("br"));
	li.appendChild(document.createTextNode(no.getElementsByTagName("description")[0].childNodes[0].nodeValue));
	
	div = document.createElement("div");
	div.className = "final";
	
	li.appendChild(div);

	ul.appendChild(li);
}

function chegouVideos() {
	keys = "";
	if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete") { 
		if (xmlHttp.responseXML != null) {
			xmlDoc = xmlHttp.responseXML
			start = 0;
			end = 0;
			quant = 0;
			start = parseInt(xmlDoc.getElementsByTagName('startIndex').item(0).childNodes[0].nodeValue);
			end = parseInt(xmlDoc.getElementsByTagName('startIndex').item(0).childNodes[0].nodeValue) + parseInt(xmlDoc.getElementsByTagName('itemsPerPage').item(0).childNodes[0].nodeValue) - 1;
			quant = xmlDoc.getElementsByTagName('totalResults').item(0).childNodes[0].nodeValue;
			var root = xmlDoc.getElementsByTagName('entry');
			removeTodosOsFilhos(document.getElementById("more_channel_videos"));
			divExterno = document.getElementById("more_channel_videos");
			div = document.createElement("div");
			div.id = "palavrasChave";
			divExterno.appendChild(div);
			div = document.createElement("div");
			div.id = "paginaAtual";
			div.appendChild(document.createTextNode("Mostrando de "));
			strong = document.createElement("strong");
			strong.appendChild(document.createTextNode(start));
			div.appendChild(strong);
			div.appendChild(document.createTextNode(" até "));
			strong = document.createElement("strong");
			strong.appendChild(document.createTextNode(end));
			div.appendChild(strong);
			divExterno.appendChild(div);
			for(i=0;i<root.length;i++){
				var node = root.item(i);

				keys = keys + node.getElementsByTagName("keywords")[0].childNodes[0].nodeValue + ", ";

				// CRIAR IMAGEM
				img = document.createElement("img");
				img.alt = node.getElementsByTagName("title")[0].childNodes[0].nodeValue;
				img.src= node.getElementsByTagName("thumbnail")[0].getAttribute('url');
				img.className = "vimg90";
				img.width = node.getElementsByTagName("thumbnail")[0].getAttribute('width');
				img.height = node.getElementsByTagName("thumbnail")[0].getAttribute('height');

				a = document.createElement("a");
				
				try {
					var descricao = escape(node.getElementsByTagName("description")[0].childNodes[0].nodeValue);	
				}catch(e){
					var descricao = ""
				}
				
				a.href = "javascript:carregaVideo('"+node.getElementsByTagName("content")[1].getAttribute('url')+"','"+escape(node.getElementsByTagName("title")[0].childNodes[0].nodeValue)+"','" + descricao + "')";
				a.rel = "nofollow";
				a.appendChild(img);

				div = new Array();
				div[0] = document.createElement("div");
				div[0].className = "v90WrapperInner";
				div[0].appendChild(a);

				div[1] = document.createElement("div");
				div[1].className = "v90WrapperOuter";
				div[1].appendChild(div[0]);

				div[2] = document.createElement("div");
				div[2].className = "v90WideEntry";
				div[2].appendChild(div[1]);

				div[3] = document.createElement("div");
				div[3].className = "flutuante";
				div[3].appendChild(div[2]);

				divExterno.appendChild(div[3]);

				// CRIAR LINKS E INFORMAÇÕES

				a = document.createElement("a");
				
				try {
					var descricao = escape(node.getElementsByTagName("description")[0].childNodes[0].nodeValue);	
				}catch(e){
					var descricao = ""
				}
				
				a.href = "javascript:carregaVideo('"+node.getElementsByTagName("content")[1].getAttribute('url')+"','"+escape(node.getElementsByTagName("title")[0].childNodes[0].nodeValue)+"','" + descricao + "')";
				a.className = "hLink";
				a.appendChild(document.createTextNode(node.getElementsByTagName("title")[0].childNodes[0].nodeValue));

				div0 = document.createElement("div");
				div0.style.marginLeft = "100px";
				div0.style.marginRight = "5px";

				div = new Array();
				div[0] = document.createElement("div");
				div[0].className = "vtitle";
				div[0].appendChild(a);

				div0.appendChild(div[0]);

				span = document.createElement("span");
				span.className = "smallText";
				seconds = node.getElementsByTagName("duration")[0].getAttribute('seconds');
				tempo = Math.floor(seconds / 60) + ":" + (seconds % 60).toFixed().pad(2, "0"); 
				span.appendChild(document.createTextNode(tempo));

				div = new Array();
				div[0] = document.createElement("div");
				div[0].appendChild(span);
				div[0].appendChild(document.createElement("br"));

				span = document.createElement("span");
				span.className = "smallLabel";
				span.appendChild(document.createTextNode("De: "));

				div[0].appendChild(span);

				a = document.createElement("a");
				a.href = "javascript:buscarVideos(1,20,'');";
				a.appendChild(document.createTextNode(node.getElementsByTagName("author")[0].getElementsByTagName("name")[0].childNodes[0].nodeValue));

				span = document.createElement("span");
				span.appendChild(a);

				div[0].appendChild(span);
				div0.appendChild(div[0]);
				divExterno.appendChild(div0);

				span = document.createElement("span");
				span.className = "smallLabel";
				span.appendChild(document.createTextNode("Exibições: "));

				div = new Array();
				div[0] = document.createElement("div");
				div[0].appendChild(span);

				span = document.createElement("span");
				span.className = "smallText";
				try{
					span.appendChild(document.createTextNode(node.getElementsByTagName("statistics")[0].getAttribute("viewCount")));
				}catch(e){
					span.appendChild(document.createTextNode("0"));
				}

				div[0].appendChild(span);
				div0.appendChild(div[0]);

				div = new Array();
				div[0] = document.createElement("div");
				div[0].className = "final";
				div0.appendChild(div[0]);
				divExterno.appendChild(div0);
			}
		}
		paginaVideos(quant);
		trataKeyWords(keys);
	}
}

String.prototype.pad = function(l, s){
	return (l -= this.length) > 0 ? (s = new Array(Math.ceil(l / s.length) + 1).join(s)).substr(0, s.length) + this + s.substr(0, l - s.length) : this;
};

function paginaVideos(q){
	var pag;
	q = parseInt(q);
	if (q > 950){
		q = 950;
	}
	qp = parseFloat(q / qpp);
	if(qp > parseInt(qp)){
		qp = parseInt(qp) + 1;
	}else{
		qp = parseInt(qp);
	}
	// limitação do youtube a resultados.
	ul = document.createElement("ul");
	ul.className = "subMenu";
	ul.style.margin = 0;
	ul.style.textAlign = "justify";
	removeTodosOsFilhos(document.getElementById("videoCorpo"));
	divExterno = document.getElementById("videoCorpo");
	for (i=0;i<qp;i++){
		a = document.createElement("a");
		pag = (i*qpp)+1;
		a.href = "javascript:buscarVideos("+ pag +"," +qpp+ ",'"+queryBusca+"');";
		a.appendChild(document.createTextNode(i+1));
		li = document.createElement("li");
		li.appendChild(a);
		li.appendChild(document.createTextNode(" "));
		ul.appendChild(li);
	}
	divExterno.appendChild(ul);
}

function trataKeyWords(palavras){
	var arrPalavrasDistinct = new Array();
	var arrPalavras = palavras.split(", ");
	j = 0;
	for(i = 0;i<arrPalavras.length;i++){
		if(!arrPalavrasDistinct.inArray(arrPalavras[i]) && arrPalavras[i] != "" && arrPalavras[i] != null){
			arrPalavrasDistinct[j] = arrPalavras[i];
			j++;
		}
	}
	divKeys = document.getElementById("palavrasChave");
	strong = document.createElement("strong");
	strong.appendChild(document.createTextNode("Filtrar por palavra-chave: "));
	divKeys.appendChild(strong);
	for(i = 0;i<arrPalavrasDistinct.length;i++){
		a = document.createElement("a");
		a.appendChild(document.createTextNode(arrPalavrasDistinct[i]));
		a.href = "javascript:buscarVideos(1,20,'"+arrPalavrasDistinct[i]+"');";
		divKeys.appendChild(a);
		divKeys.appendChild(document.createTextNode(" "));
	}
}

Array.prototype.inArray = function (value){
	// Returns true if the passed value is found in the
	// array. Returns false if it is not.
	var i;
	for (i=0; i < this.length; i++) {
		// Matches identical (===), not just similar (==).
		if (this[i].toLowerCase() === value.toLowerCase()) {
			return true;
		}
	}
	return false;
};

function carregaVideo(url,titulo, descricao){
	removeTodosOsFilhos(document.getElementById("titulo"));
	document.getElementById("titulo").appendChild(document.createTextNode(unescape(titulo)));
	var so = new SWFObject(url, "fvideo", "400", "324", "8", "");
	so.useExpressInstall('swf/expressinstall.swf');
	so.addParam("wmode", "transparent");
	so.addParam("scale", "noscale");
	so.write("video");
	p = document.createElement("p");
	p.className = "noindent";
	p.style.marginLeft = "0";
	p.style.marginRight = "0";
	p.appendChild(document.createTextNode(unescape(descricao)));
	document.getElementById("video").appendChild(p);
}

/*
	Função GetXmlHttpObject
*/

function GetXmlHttpObject(handler) { 
	var objXmlHttp=null;

	if (navigator.userAgent.indexOf("MSIE")>=0) { 
		var strName="Msxml2.XMLHTTP";
		if (navigator.appVersion.indexOf("MSIE 5.5")>=0) {
			strName="Microsoft.XMLHTTP";
		} 
		try { 
			objXmlHttp=new ActiveXObject(strName);
			objXmlHttp.onreadystatechange=handler;
			return objXmlHttp;
		} catch(e) { 
			alert("Erro. \"Scripting for ActiveX\" provavelmente está desabilitado.");
			return;
		}
	}
	if (navigator.userAgent.indexOf("Mozilla")>=0) {
		objXmlHttp=new XMLHttpRequest();
		objXmlHttp.onload=handler;
		objXmlHttp.onerror=handler;
		return objXmlHttp;
	}
}

$(function(){
	$("a[rel='lightbox']").colorbox({transition:"fade"});
});
