// JavaScript Document

function opnwin(url,width,height,OPENWINDOW) {
	if (OPENWINDOW == "" || OPENWINDOW == undefined) OPENWINDOW = "_blank";
	var left = (screen.availWidth-width)/2;
	var top = (screen.availHeight-height)/2;
	var new_win = window.open(url, OPENWINDOW, "menubar=0,toolbar=0,location=0,directories=0,status=1,scrollbars=1,resizable=0,width="+width+",height="+height+",top="+top+",left="+left);
	
	//return true;
}

/*
tem que ter isso em todas as paginas: <div id="footer_div"></div>
antes da linha </body></html>
*/
function opnDivAjax(url,width,height,namediv) {
	var left = (screen.availWidth-width)/2;
	var top = (screen.availHeight-height)/2;
	var footerPageLeftTop = findPos($('footer_div'));
	var pageH = (footerPageLeftTop[1])+10;
	if (pageH < screen.availHeight) {
		pageH = screen.availHeight;
	}
	if (document.getElementById("div_"+namediv) == null) {
		var p=document.createElement('div');
		var p2=document.createElement('div');
		var i=document.createElement('iframe');
		
		var transp = 70; // alpha
		
		//i.src					= '';
		i.style.filter			= "progid:DXImageTransform.Microsoft.Alpha(opacity = "+transp+");";
		i.style.filter			= "alpha(opacity=" + transp + ")"; // For IE filter to work, obj MUST have layout
		i.style.KHTMLOpacity	= transp / 100; // Safari and Konqueror
		i.style.MozOpacity		= transp / 100; // Old Mozilla and Firefox
		i.style.opacity			= transp / 100; // CSS3 opacity for browsers that support it
		i.id					= "ifr_"+namediv;
		i.style.position		= 'absolute';
		i.style.margin			= 0 + 'px';
		i.style.width			= 100 + '%';
		i.style.height			= pageH + 'px';
		i.style.top				= 0 + 'px';
		i.style.left			= 0 + 'px';
		Element.hide(i);
		document.body.appendChild(i);

		p2.style.filter			= "progid:DXImageTransform.Microsoft.Alpha(opacity = "+transp+");";
		p2.style.filter			= "alpha(opacity=" + transp + ")"; // For IE filter to work, obj MUST have layout
		p2.style.KHTMLOpacity	= transp / 100; // Safari and Konqueror
		p2.style.MozOpacity		= transp / 100; // Old Mozilla and Firefox
		p2.style.opacity		= transp / 100; // CSS3 opacity for browsers that support it
		p2.id					= "div2_"+namediv;
		p2.style.position		= 'absolute';
		p2.style.top			= 0 + 'px';
		p2.style.left			= 0 + 'px';
		p2.style.width			= 100 + '%';
		p2.style.height			= pageH + 'px';
		
		document.body.appendChild(p2);
		
		p.id				= "div_"+namediv;
		p.style.position	= 'absolute';
		p.style.top			= top + 'px';
		p.style.left		= left + 'px';
		p.style.width		= width + 'px';
		p.style.height		= height + 'px';
		
		document.body.appendChild(p);
		
	}
	else {
		p2 = document.getElementById("div2_"+namediv);
		p = document.getElementById("div_"+namediv);
		i = document.getElementById("ifr_"+namediv);
	}
	


	// mostra
	p2.style.display = "block";
	p.style.display = "block";
	i.style.display = "block";

	// coloca camada em profundiade 10
	p2.style.zIndex = "10";
	p2.style.background ='#FFFFFF';
	
	// coloca conteudo em profundiade 11
	p.style.zIndex = "11";
	//p.style.background ='#FFFFFF';
	

	//p.innerHTML = "<div id=''></div>";
	//Loader(url,"div_"+namediv);
	PostWithPrototype(url, "", "div_"+namediv, "get");
}

function CloseDivAjax(namediv) {
	if (document.getElementById("div_"+namediv) == null) {
	}
	else {
		p2 = document.getElementById("div2_"+namediv);
		p = document.getElementById("div_"+namediv);
		i = document.getElementById("ifr_"+namediv);
		p2.style.display = "none";
		p.style.display = "none";
		i.style.display = "none";
		
		p.innerHTML = "";
	}
}



function ChangeCssClass(f, cssClass1, cssClass2) {
	if (f.className == cssClass1) {
		f.className = cssClass2;
	}
	else {
		f.className = cssClass1;
	}
}

function makeSelect(_array, formName, fieldName, selecionado) {
	if (!selecionado) selecionado = "";
	objSel = eval("document." + formName + "." + fieldName);
	objSel.options.length = 0;

	for (i=0;i<_array.length; i++) {
		_array2 = _array[i].split("|");
	 	objSel.options[i] = new Option(_array2[1],_array2[0]);
		if (selecionado && _array2[0] == selecionado) {
			objSel.options[i].selected = true;
		}
	}
	
}

function setSelect(formName, fieldName, value2sel, targ) {
	if(targ && targ != "undefined") targ = targ + "."
	else targ="";

	if('' == value2sel || value2sel.length == 0) return;
	objSelect = eval(targ + "document." + formName + "." + fieldName);
	if(!objSelect) return;

	if(!value2sel) return;
	_values = value2sel.split("|");

	for (var i=0; i < objSelect.options.length; i++)
	{
		objSelect.options[i].selected = false; // Limpa campos
		// Setar os valores
		for(j=0; j < _values.length; j++)
		{
			if (objSelect[i].value == _values[j] || objSelect[i].text == _values[j])
				objSelect.options[i].selected = true;

		}
	}
}

/* Pega o valor de um RADIO */
function getRadioValue(formName,fieldName)
{
	objRadio = eval("document." + formName + "." + fieldName);
	for(i=0; i < objRadio.length; i++)
	{
		if(objRadio[i].checked == true)
		{
			return objRadio[i].value;
		}
	}
	return;
}

function getSelectValue(formName,fieldName) {
	obj = eval("document." + formName + "." + fieldName);
	if(obj.selectedIndex == -1) {return false};
	return obj.options[obj.selectedIndex].value;
}

function getSelectText(formName,fieldName) {
	obj = eval("document." + formName + "." + fieldName);
	if(obj.selectedIndex == -1) {return false};
	return obj.options[obj.selectedIndex].text;
}


function selectAll(formName, fieldName, flag) {
	if(flag == false) sel = false;
	else sel = true;
	obj = eval("document." + formName + "." + fieldName);
	if(obj.options.length == 0) return;
	for (var i=0; i < obj.options.length; i++)
	{
		obj.options[i].selected = sel;
	}
}

function cleanSelect(formName,fieldName) {
	obj = eval("document." + formName + "." + fieldName);
	obj.options.length = 0;
	obj.options[0] = new Option("","");
}

function lista2assoc(lista,sepOption,sepValue)
{
	if(!sepOption) sepOption = ",";
	if(!sepValue) sepValue = "|";
	_a = new Array();
	if(!lista) { _a[""]="" ; return _a; }
	lista = lista.split(sepOption);
	for(k=0; k < lista.length; k++)
	{
		kv = lista[k].split(sepValue);
		if(!kv[1]) _a[kv[0]] = kv[0];
		else _a[kv[0]] = kv[1];
	}
	return _a;
}


function DisEnable(formName,fieldName,flag,targ) {
	flag = flag ? true : false;
	if(targ) targ = targ + ".";
	else targ="";
	obj = eval(targ + "document." + formName + "." + fieldName);
	obj.disabled = flag;
}


function FillAny(FormName,FieldName,FieldValue, debugAlert) {
	if (debugAlert == undefined) {
		debugAlert = 1; // 1 or 0
	}
	formobj = eval('document.forms["' + FormName + '"]');
	fobj = eval("document.forms['" + FormName + "']." + FieldName);
	

	function _type(obj) {
		if (!obj) {
			if (debugAlert) {
				alert("Campo Inexistente: " + FieldName);
			}
			return;
		}
		
		if(obj.type != undefined) return obj.type;
		
		for (var i=0 ; i < formobj.length ; i++) {
			var x = formobj[i];
			if((x.type == 'checkbox' || x.type == 'radio') && FieldName == x.name) {
				return x.type;
			}
		}
	}

	// setar valores para, text, select-one,textarea,password,hidden,submit,reset,button
	function Set() { try { fobj.value = FieldValue; } catch (e) { alert("Field not exist: " + FieldName)} }
	
	// setar valores para, checkbox
	function Set_ckb() {
		_values = FieldValue.split("|");
	
		// Se houver 1 checkbox
		if(fobj.length == undefined && fobj.value == FieldValue) { fobj.checked = true; }
		for(i=0; i < fobj.length ; i++) {
			fobj[i].checked = false; // Limpando todos
			for(j=0; j < _values.length; j++) {
				if (fobj[i].value == _values[j]) { fobj[i].checked = true; }
			}
		}
	}
	
	//setar valores para, radio
	function Set_radio() {
		for(i=0; i < fobj.length; i++) {
			if(fobj[i].value == FieldValue) { fobj[i].checked = true; }
		}
	}
	
	// setar valores para, select-multiple
	function Set_cb(fn,v) {
	}


	//	alert(_type(fobj))
	//alert(document.forms['formulario'].elements);
	switch (_type(fobj)) {
		case 'text':;
		case 'textarea':;
		case 'password':;
		case 'hidden':;
		case 'submit':;
		case 'reset':;
		case 'button':;
		case 'select-one': { Set(); break; }
		case 'select-multiple': { Set_cb(); break; }
		case 'checkbox': { Set_ckb(); break; }
		case 'radio': { Set_radio(); break; }
		default : {}
	}

}

function ShowHideDiv(id) {
	f = document.getElementById(id);
	if (f.style.display == "none") {
		f.style.display = "block";
	}
	else {
		f.style.display = "none";
	}
}

function ShowDiv(id) {
	f = document.getElementById(id);
	f.style.display = "block";
}

function HideDiv(id) {
	f = document.getElementById(id);
	f.style.display = "none";
}

function JSFX_FloatTopDiv(divid)
{
	//Enter "frombottom" or "fromtop"
	//var verticalpos="fromtop"
	
	if (verticalpos == undefined) var verticalpos="fromtop"


	var startX = 0,
	startY = (screen.availHeight)/4;
	var ns = (navigator.appName.indexOf("Netscape") != -1);
	var d = document;
	function ml(id)
	{
		var el=d.getElementById?d.getElementById(id):d.all?d.all[id]:d.layers[id];
		if(d.layers)el.style=el;
		el.sP=function(x,y){this.style.left=x;this.style.top=y;};
		el.x = startX;
		if (verticalpos=="fromtop")
		el.y = startY;
		else{
		el.y = ns ? pageYOffset + innerHeight : document.body.scrollTop + document.body.clientHeight;
		el.y -= startY;
		}
		return el;
	}
	window.stayTopLeft=function()
	{
		if (verticalpos=="fromtop"){
		var pY = ns ? pageYOffset : document.body.scrollTop;
		ftlObj.y += (pY + startY - ftlObj.y)/8;
		}
		else{
		var pY = ns ? pageYOffset + innerHeight : document.body.scrollTop + document.body.clientHeight;
		ftlObj.y += (pY - startY - ftlObj.y)/8;
		}
		ftlObj.sP(ftlObj.x, ftlObj.y);
		setTimeout("stayTopLeft()", 10);
	}
	ftlObj = ml(divid);
	stayTopLeft();

}

// position de um div ou objeto
function findPos(obj) {
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		curleft = obj.offsetLeft
		curtop = obj.offsetTop
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft
			curtop += obj.offsetTop
		}
	}
	return [curleft,curtop];
}


// prototype
function Loader(url,div) {
	new Ajax.Updater(div, url, {
		encoding: 'UTF-8'
	});
}


/* formulario is <form id="formulario">
use like this:
<script type="text/javascript">
function doSubmit() {
	f = document.formulario;
	url = f.action;
	method = f.method;
	_values = Form.serialize($("formulario"));
	Form.disable("formulario"); // deixa todos os campos readonly
	PostWithPrototype(url, _values, "error_msg", method); // submit 
	Form.reset("formulario"); // limpa o formulario
	Form.enable("formulario") ; // tira o readonly de todos os campos
}
</script>
*/


function PostWithPrototype(url, values, div, method) {
	if (method==undefined) {
		method = "post";
	}
	
	new Ajax.Request(url, { 
		onSuccess : function(resp) { 
			//alert("The response from the server is: " + resp.responseText); 
			Element.update(div, resp.responseText);
		}, 
		onFailure : function(resp) { 
			alert("Oops, there's been an error."); 
		}, 
		parameters : values,
		method: method,
		encoding: 'UTF-8' 
	});
}


function RemoveRegistro(url, id, objDiv) {
	if (confirm("Deseja realmente excluir este registro?")) {
		if (!objDiv) var objDiv = "listagem_div";
		PostWithPrototype(url, "id="+id, objDiv, "post"); // submit 
	}
}

function EditRegistro(url, id, objDiv) {
	if (!objDiv) var objDiv = "listagem_div";
	PostWithPrototype(url, "id="+id, objDiv, "post"); // submit 
}


function criarIframe() {
	h = document.body.scrollHeight
	w = document.body.scrollWidth
	o_iframe = document.createElement('iframe')
	o_iframe.id = 'iframeHidden'
	o_iframe.style.width = w + 'px'
	o_iframe.style.height = (h + 10) + 'px'
	o_iframe.className = "iframeH"
	o_iframe.frameBorder = '0px'
	document.body.appendChild(o_iframe)
}

function CreateHiddenIframe(id,debug) {
	if (debug==1) {
		w = "100%";
		h = "300px";
		border = "1px";
	}
	else {
		w = "0px";
		h = "0px";
		border = "0px";
	}

	document.write('<iframe width="'+w+'" height="'+h+'" frameborder="'+border+'" name="'+id+'" id="'+id+'"></iframe>');
}

function removeIFrame() {
	try {
		document.body.removeChild(document.getElementById('iframeHidden'))
	} catch (e) {}
}

// on press enter key press, move cursor to next field..
/*
<form>
<input type="text" onkeypress="return handleEnter(this, event)"><br>
<input type="text" onkeypress="return handleEnter(this, event)"><br>
<textarea>Some text</textarea>
</form>
*/
function handleEnter (field, event) {
	var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
	if (keyCode == 13) {
		var i;
		for (i = 0; i < field.form.elements.length; i++)
			if (field == field.form.elements[i])
				break;
		i = (i + 1) % field.form.elements.length;
		field.form.elements[i].focus();
		return false;
	} 
	else
	return true;
}

// stop return key
// document.onkeypress = stopRKey; 
// <input type="text" onKeypress="return stopRKey();">
function stopRKey(evt) {
	var evt = (evt) ? evt : ((event) ? event : null);
	var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
	if ((evt.keyCode == 13) && (node.type=="text"))  {return false;}
}

// submit on return key
// document.onkeypress = doSubmitOnRKey; 
function doSubmitOnRKey(evt) {
	var evt = (evt) ? evt : ((event) ? event : null);
	var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
	if ((evt.keyCode == 13) && (node.type=="text" || node.type=="password"))  { doSubmit(); }
}

// submit on return key
// document.onkeypress = doPostOnRKey; 
function doPostOnRKey(evt) {
	var evt = (evt) ? evt : ((event) ? event : null);
	var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
	if ((evt.keyCode == 13) && (node.type=="text" || node.type=="password"))  { doPost(); }
}

// search on return key
// document.onkeypress = doSearchOnRKey; 
function doSearchOnRKey(evt) {
	var evt = (evt) ? evt : ((event) ? event : null);
	var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
	if ((evt.keyCode == 13) && (node.type=="text")) { doSearch(); }
}

// Confere e-mail.
function validaEmail(email) {
	try {
		er = /^[0-9a-z][0-9a-zA-Z._-]+@[a-z][-.a-z0-9]+[.][a-z]+$/
		if(!er.test(email))
			return false;
		return true;
	} catch (e) {}
}

// valida data // Ex: valitaData('25/01/2000');
function validaData(data) { 
	dia = (data.substring(0,2));
	mes = (data.substring(3,5));
	ano = (data.substring(6,10));

	// verifica o dia valido para cada mes
	if(isNaN(dia) || (dia < 01) || (dia < 01 || dia > 30) && (mes == 04 || mes == 06 || mes == 9 || mes == 11) || dia > 31) {
		return false;
	}
	// verifica se o mes e valido 
	if(isNaN(mes) || mes < 01 || mes > 12) {
		return false;
	}
	if(isNaN(ano) || ano < 1000) {
		return false;
	}

	// verifica se e ano bissexto 
	if(mes == 2 && (dia < 01 || dia > 29 || (dia > 28 && (parseInt(ano / 4) != ano / 4)))) {
		return false;
	}
	if(data == "") {
		return false;
	}

	// se passou por todos , entao eh valido
	return true;
}

function validaCPF(c){
	var i;

	// tira pontos e traços
	c = c.replace(".", "");
	c = c.replace("-", "");
	c = c.replace(".", "");

	
	s = c;
	var c = s.substr(0,9);
	var dv = s.substr(9,2);
	var d1 = 0;
	for (i = 0; i < 9; i++) {
		d1 += c.charAt(i)*(10-i);
	}
	if (d1 == 0) {
		return false;
	}
	d1 = 11 - (d1 % 11);
	if (d1 > 9) d1 = 0;
	if (dv.charAt(0) != d1) {
		return false;
	} 

	
	d1 *= 2;
	for (i = 0; i < 9; i++) {
		d1 += c.charAt(i)*(11-i);
	}
	d1 = 11 - (d1 % 11);
	if (d1 > 9) d1 = 0;
	if (dv.charAt(1) != d1) {
		return false;
	}
	
	return true;

}


/*
* operadores
* ">"	= maior
* "<"	= menor
* ">="	= maior ou igual
* "<="	= menor ou igual
* "="	= igual
* "=="	= igual
* "!="	= diferente
* "<>"	= diferente
*/
function ComparaDatas(data1, data2, operador) {
	dia1 = (data1.substring(0,2));
	mes1 = (data1.substring(3,5));
	ano1 = (data1.substring(6,10));

	dia2 = (data2.substring(0,2));
	mes2 = (data2.substring(3,5));
	ano2 = (data2.substring(6,10));

	timestamp1 = date2timestamp(ano1, mes1, dia1, 00, 00, 00);
	timestamp2 = date2timestamp(ano2, mes2, dia2, 00, 00, 00);

	if (operador == ">") {
		if (timestamp1 > timestamp2) return true;
	}
	else if (operador == "<") {
		if (timestamp1 < timestamp2) return true;
	}
	if (operador == ">=") {
		if (timestamp1 >= timestamp2) return true;
	}
	else if (operador == "<=") {
		if (timestamp1 <= timestamp2) return true;
	}
	else if (operador == "==") {
		if (timestamp1 == timestamp2) return true;
	}
	else if (operador == "=") {
		if (timestamp1 == timestamp2) return true;
	}
	else if (operador == "!=") {
		if (timestamp1 != timestamp2) return true;
	}
	else if (operador == "<>") {
		if (timestamp1 != timestamp2) return true;
	}
	else {
		return false;
	}
}


function timestamp2date(timestamp) {
	var theDate = new Date(timestamp * 1000);
	return theDate.toGMTString();
}
 
function date2timestamp(year, month, day, hour, min, sec) {
	return (Date.UTC(year, month-1, day, hour, min, sec) / 1000);
} 

function Arredonda(valor, casas) {
	novo = Math.round(valor * Math.pow(10, casas)) / Math.pow(10, casas);
	return novo;
}

function removeOptions(selectbox) {
	for(i = (selectbox.options.length - 1); i >= 0; i--) {
		selectbox.remove(i);
	}
}

function addOption(selectbox, text, value) {
	var optn = document.createElement("OPTION");
	optn.text = text;
	optn.value = value;
	selectbox.options.add(optn);
}

// Controle para campos que devem ter entrada apenas de números.
function autNum(vlr) {
	er = /\D/;
	if(er.test(vlr)) {
		return false;
	}
	return true;
}


// Captura Larguras
function getWindowWidth() {
	try {
		windowWidth = 0;
		if(typeof(window.innerWidth) == 'number') {
			windowWidth = window.innerWidth;
		}
		else {
			if(document.documentElement && document.documentElement.clientWidth) {
				windowWidth = document.documentElement.clientWidth;
			}
			else {
				if(document.body && document.body.clientWidth) {
					windowWidth = document.body.clientWidth;
				}
			}
		}
		return windowWidth;
	} catch (e) {}
}

// Captura Alturas
function scrollTop() {
	scrollYValue = 0;
	if(typeof(window.pageYOffset) == 'number') {
		scrollYValue = window.pageYOffset;
	}
	else if(document.body && document.body.scrollTop) {
		scrollYValue = document.body.scrollTop;
	}
	else if(document.documentElement && document.documentElement.scrollTop) {
		scrollYValue = document.documentElement.scrollTop;
	}
	return scrollYValue;
}