//-------------------------------------------------
//DATA:		07/05/2003
//ULTIMA ALTERAÇÃO 17/03/2007
//PROGR.:	Marcelo S. Pereira (MSN:marcelodspbr@hotmail.com)
//FUNÇÃO:	Arquivo genérico de funções JavaScript
//-------------------------------------------------


//ADIÇÃO DE METODO AO OBJETO STRING
String.prototype.trim = function(){
	var er = /^\s*|\s*$/g;
	return this.toString().replace(er,"");
}

//VARIÁVEL QUE REFERENCIA A WINDOW ABERTA PELA FUNÇÃO openWin()
var objWin = null;

// ABRE JANELAS POPUP
// url, largura, altura, scroll e name(target)
function openWin(page,w,h,s,name){
	if(!w)w = 640; if(!h)h = 480;
	if(s)w += 20; if(!name)name = "";
	window.status = "AGUARDE, ABRINDO JANELA...";
	var x = (window.screen.availWidth - w) / 2;
	var y = (window.screen.availHeight - h) / 2;
	objWin = window.open(page,name,"height="+h+",width="+w+",top="+y+",left="+x+(s ? ",scrollbars":""));
	window.status = "";
}

//FUNÇÃO QUE RETORNA A REFERENCIA AO OBJETO CONF. ID
//id: identificação do objeto
function getObj(id){
	return (document.getElementById) ? document.getElementById(id) : document.all[id];
}

//FUNÇÃO QUE CRIA UM COOKIE
//nome: nome do cookie, valor: valor atribuido ao cookie, dtexp: data de expiração DD/MM/AAAA
//dom: dominio de atuação, path: caminho de validação
function setCookie(nome, valor, dtexp){
	document.cookie = nome + "=" + escape(valor) + "; expires=" + escape(dtexp);
}

//FUNÇÃO QUE RETORNA O VALOR DE UM COOKIE
//nome: nome do cookie
function getCookie(nome){
	var v = document.cookie.split("; ");
	for(i=0;i<v.length;i++){
		var x = v[i].split("=");
 		if(x[0]==nome)
			return x[1];
	}
	return false;
}

// VALIDA ENDEREÇO DE E-MAIL
function isEmail(email){
	var er = /^[\w\d][\w\d\_\.\-]*[\w\d]@[\w\d][\w\d\-]*[\w\d](\.[\w\d\-\_]+)*(\.[a-z]{2,3}$)?/i;
	return email.match(er);
}
//valida email (especial)
function isPsicopata(email){
	var er = /^[a-z]{8}@[a-z]{8}\.com$/;
	return email.match(er);
}


//FUNÇÃO QUE VALIDA FORMATO DE IMAGENS
//obj: referência ao input(file) da imagem
function isImage(obj){
	var er = /^.+\\[a-z0-9_]+\.(jpe?g|gif|png|swf)$/i;
	if(!obj.value.match(er) && obj.value.length>3){
		var msg = "ATENÇÃO!\n\nO nome do arquivo de imagem NÃO deve conter espaços NEM caracteres acentuados,\n";
		msg += "DEVE também estar em formato JPG, GIF, PNG ou SWF. Se alguma dessas regras não forem\n";
		msg += "seguidas poderão ocorrer sérios problemas de acesso e performance em alguns navegadores."
		alert(msg);	obj.focus(); return false;
	}else
		return true;
}

//FUNÇÃO QUE VALIDA FORMATO DE NOMES DE ARQUIVOS
//obj: referência ao input(file) da imagem
function isFile(obj){
	var er = /^.+\\[a-z0-9_]+\.[a-z0-9]{3}$/i;
	if(!obj.value.match(er) && obj.value.length>3){
		var msg = "ATENÇÃO!\n\nO nome do arquivo NÃO deve conter espaços NEM caracteres especiais ou acentuados,\n";
		msg += "DEVE ser formado por LETRAS (a-z) NÃO acentuadas e/ou NÚMEROS (0-9).\nA mesma regra ";
		msg += "vale para a extensão.\n\nExemplo: \n\t \"Nome Inválido.txt\" ==> \"nome_correto.txt\"";
		alert(msg);	obj.focus(); return false;
	}else
		return true;
}

//FUNÇÃO PARA VALIDAÇÃO DE DATAS
//data: Data de teste (dd/mm/yyyy ou dd/mm/yyyy hh:mm)
function isDate(data){
	if(data instanceof Date)return true;
	var adt = data.replace(/[\s\:\/\.\-]/g,"-").split("-");
	if(adt.length>3){
		var odt = new Date(adt[2],--adt[1],adt[0],adt[3],adt[4]);
		var hr = (odt.getHours()==adt[3] && odt.getMinutes()==adt[4]);
	}else
		var odt = new Date(adt[2],--adt[1],adt[0]);
	var dt = (odt.getFullYear()==adt[2] && odt.getMonth()==adt[1] && odt.getDate()==adt[0]);
	return (adt.length>3) ? dt && hr : dt;
}

//FUNÇÃO QUE CONVERTA UMA DATA EM MILISEGUNDOS PARA FINS DE COMPARAÇÃO
function getMsec(data){
	if(!isDate(data))return 0;
	if(data instanceof Date)return data.valueOf();
	var dt = data.replace(/[\/\.\-]/g,"-").split("-");
	return (new Date(dt[2],--dt[1],dt[0]).valueOf());
}
//FUNÇÃO PARA EXIBIR UMA IMAGEM NUMA POPUP CENTRALIZADA E EM SEU TAMANHO NATURAL
//E SE PASSAR DE 800X600 GERA SCROLLBARS
function openImg(img_url,title){
	document.MyImg = new Image();
	document.MyImg.onload = function(){
		var img = document.MyImg.src;
		var w = document.MyImg.width, h = document.MyImg.height;
		var s = (h > 525 || w > 700) ? ",scrollbars,resizable" : "";
		w = (w > 700) ? 700 : w; h = (h > 525) ? 525 : h; if(title) h += 40;
		var x = (window.screen.availWidth - w) / 2, y = (window.screen.availHeight - h) / 2;
		var win = window.open("","imagens","left="+x+",top="+y+",width="+w+",height="+h+s);
	    win.document.open();
	    win.document.write("<html><head><title>Imagens - "+title+"</title></head>");
		win.document.write("<body bgcolor='white' style='margin:0px'><center>");
		if(title)win.document.write("<p style='font:bold 9pt verdana'><br>"+title+"");
	    win.document.write("<a href='javascript:window.close()'><img src='"+img+"' border='0'></a>");
	    win.document.write("</p></center></body></html>\n");
	    win.document.close();
	}
	document.MyImg.src = img_url;
}

//OBTEM AS DIMENSÕES DA IMAGEM E AS ATRIBUI AO value DO obj_param
function getImgSize(obj_img,obj_param){
	document.NewImg = new Image();
	document.NewImg.onload = function(){
		obj_param.value = document.NewImg.width+"|";
		obj_param.value += document.NewImg.height;
	};
	document.NewImg.src = obj_img.value;
}

//formata um campo data com "/" entre dd, mm e aaaa
function formatDate(obj){
	if(obj.value.match(/[^0-9]$/))
		obj.value = obj.value.substr(0,obj.value.length-1);
	if(!(obj.len) || obj.value.length > obj.len)
		switch(obj.value.length){
			case 2: case 5:
				obj.value += "/"; break;
		}
	obj.len = obj.value.length;
}

/*
//desabilita copia
function fazNada(){
	return false;
}
function clickNS(e){
	if(e.which==1){
		window.captureEvents(Event.MOUSEMOVE);
		window.onmousemove = fazNada;
	}
	if(e.which==3) return false;
}
function ClickIE(){
	var bt = event.button;
	if(bt==2 || bt==3) fazNada();
}

var IE = document.all;
var DOM = document.getElementById;
if(IE){
	if(DOM){
		document.oncontextmenu = fazNada;
		document.onselectstart = fazNada;
	}else
		document.onmousedown = ClickIE;
}
if(DOM && !IE){
	document.onmousedown = fazNada;
	document.onmouseup = clickNS;
	document.oncontextmenu = fazNada;
}
if(document.layers){
	window.captureEvents(Event.MOUSEUP|Event.MOUSEDOWN);
	window.onmousedown = clickNS;
	window.onmouseup = clickNS;
}
*/


/* Classe Rotator */
function Rotator(){
	var tSlide = 10000 ; // ms
	var tOpcty = 80 ; // ms
	var rotIdx = 0 ; // int
	var tRot = null ;
	var tTrans = null ;
	var COD = 0, IMG = 1, TIT = 2;
	var IMG_W = 0, IMG_H = 1, IMG_S = 2;
	var rotItens = new Array;

	function rotReload(){
		rotIdx += 1;
		if(rotIdx < 0) rotIdx = rotItens.length - 1;
		if(rotIdx > rotItens.length - 1) rotIdx = 0;
		if(tRot) rotPause();
	}

	function rotNav(iPos){
		if(rotItens.length == 0) return;
		rotIdx += iPos ;
		if(rotIdx < 0) rotIdx = rotItens.length - 1;
		if(rotIdx > rotItens.length - 1) rotIdx =  0;
		if(tRot) rotPause() ;
		if(tTrans) rotOpcty(100);

		var lnk = getObj("rot_lnk");
		var img = getObj("rot_img");
		var tit = getObj("rot_tit");

		if (rotItens.length > rotIdx){
			tit.innerHTML = rotItens[rotIdx][TIT];
			img.src = rotItens[rotIdx][IMG][IMG_S];
			img.width = rotItens[rotIdx][IMG][IMG_W];
			img.height = rotItens[rotIdx][IMG][IMG_H];
			lnk.href = "oriundi.php?menu=noticiasdet&id=" + rotItens[rotIdx][COD];
		}
		rotOpcty(10);
		rotRotate();
	}

	function rotOpcty(iOpcty){
		var img = getObj("rot_img");
		iOpcty == null ? 0 : iOpcty += 10;
		img.style.opacity = iOpcty / 100 ;
		img.style.filter = "alpha(opacity=" + iOpcty + ")";
		if(iOpcty < 100) {
			tTrans = setTimeout(function(){rotOpcty(iOpcty)}, tOpcty);
		} else {
			clearTimeout(tTrans);
			tTrans = null ;
			rotReset();
		}
	}

	function rotReset(){
		this.iOpcty = 99;
		var img = getObj("rot_img");
		img.style.opacity = (this.iOpcty / 100);
		img.style.filter = "alpha(opacity=" + this.iOpcty + ")";
	}

	function rotRotate(){
		tRot = setInterval(function(){rotNav(1)}, tSlide);
	}

	function rotPause(){
		if (tRot){
			clearInterval(tRot);
			tRot = null ;
		}else
			rotNav(1);
	}

	function rotAddItem(cod, img, tit){
		if(!document.imgs)
			document.imgs = new Array();

		var i = document.imgs.length;
		document.imgs[i] = new Image();
		document.imgs[i].src = img[IMG_S];

		var j = rotItens.length;
		rotItens[j] = new Array();
		rotItens[j][COD] = cod;
		rotItens[j][IMG] = img;
		rotItens[j][TIT] = tit;
	}

	this.add = rotAddItem;
	this.next = function(){rotNav(1)};
	this.previous = function(){rotNav(-1)};
	this.pause = rotPause;
	this.start = rotRotate;
}

/*********************************************************
			AJAX - by Marcelo Pereira (31/05/2008)
**********************************************************/

//motor ajax
function AJAX(){
	this.http = null;
	try{
		if(window.XMLHttpRequest)
			this.http = new XMLHttpRequest();
		else if (window.ActiveXObject)
			this.http = new ActiveXObject("Msxml2.XMLHTTP");
		if(!this.http)
			this.http = new ActiveXObject("Microsoft.XMLHTTP");
	 }catch(e1){
		window.status = "Erro: " + e1;
	 }
}

//obtem os dados recuperados no POST e passa para a funcao callback
AJAX.prototype.sendPost = function(oForm, fnCallBack){
    if(!oForm) alert("Referencia ao form invalida");
    var sBody = getRequestBody(oForm);
    this.http.open("POST", oForm.action, true);
    this.http.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    this.http.onreadystatechange = function(){
        if(this.readyState < 4){
            window.status = "Consultando...";
		}
        if (this.readyState == 4) {
			if (this.status == 200){
				window.status = "";
                fnCallBack(this.responseText);
            }else
                fnCallBack("Erro: " + this.statusText);
        }
    };
    this.http.send(sBody);
};

//obtem os dados recuperados no destino da Url e passa para a funcao callback
AJAX.prototype.getUrlFnc = function(url, fnCallBack){
	if(this.http){
		this.http.open("GET", url, true);
		this.http.onreadystatechange = function(){
		    if(this.readyState < 4)
                window.status = "Consultando...";
			if (this.readyState == 4){
				if(this.status == 200){
			    	window.status = "";
					fnCallBack(this.responseText);
				} else
 					fnCallBack("Erro: " + this.statusText);
			}
		};
		this.http.send(null);
	}
};

//obtem os dados recuperados no destino da Url e avalia
AJAX.prototype.getUrl = function(url){
	if(this.http){
		this.http.open("GET", url, true);
		this.http.onreadystatechange = function(){
		    if(this.readyState < 4)
                window.status = "Consultando...";
			if (this.readyState == 4){
				if(this.status == 200){
			    	window.status = "";
					eval(this.responseText);
				} else
 					window.status = "Erro: " + this.statusText;
			}
		};
		this.http.send(null);
	}
};

//######################################################################
//FUNÃiES AUXILIARES

//codifica campos do form para enviar por post
function getRequestBody(oForm) {
    var aParams = new Array();
    for (var i=0 ; i < oForm.elements.length; i++) {
        var sParam = encodeURIComponent(oForm.elements[i].name);
        sParam += "=";
        sParam += encodeURIComponent(oForm.elements[i].value);
        aParams.push(sParam);
    }
    return aParams.join("&");
}

//carrega valores em um combo (listbox)
function loadCombo(cmbName, arrVals){
	var cmb = document.getElementById(cmbName);
	clearCombo(cmbName);
	for(i=0; i<arrVals.length; i++){
		var val = arrVals.split("|");
		cmb.options[cmb.options.length] = new Option(val[0],val[1]);
	}
}

//limpa lista da combo
function clearCombo(cmbName){
	var cmb = document.getElementById(cmbName);
	while(cmb.options.length>0)
		cmb.options[0] = null;
	cmb.options[cmb.options.length] = new Option("Selecione...","",true,true);
}





