var ACTION_OVER 	= 0;
var ACTION_OUT  	= 1;

function showItemMenu(parent){
	var element = document.getElementById(parent  + "_items");
	if(document.all)
		element.style.display = (element.style.display =="none")?"block":"none";
	else
		element.style.display  = (element.style.display =="none")?"table":"none";
}
function manageEffectMenu(element,showing, action){
	if ((action == ACTION_OVER ) || (showing))
		element.className = "highLightedMenu";
	else
		element.className = "normalMenu";
}

function selectThis(form, itemName){
	var objSelectedName = "originalClass_" + getObjSelected(form);		
	var obj = form.elements[itemName];

	if (obj.checked == true){
		obj.checked = false;
		document.getElementById(obj.name).className = form[objSelectedName].value;			
	} else if (obj.name == itemName){
		obj.checked = true;
		document.getElementById(itemName).className = 'selectedRow';
	}
		
}
 
function select(form, itemName){
	var objSelectedName = "originalClass_" + getObjSelected(form);
	for (var i = 0; i < form.elements.length;i++){
		var obj = form.elements[i];
		if (((obj.name != itemName) || (obj.name == itemName)) && (obj.checked == true)){
			obj.checked = false;
			document.getElementById(obj.name).className = form[objSelectedName].value;			
		} else if (obj.name == itemName){
			obj.checked = true;
			document.getElementById(itemName).className = 'selectedRow';
		}
	}	
}
function getObjSelected(form){
	for (var i = 0; i < form.elements.length;i++){
		if (form.elements[i].checked== true){
				//return form.elements[i].name.replace("_","");
				return form.elements[i].name;
		}
	}
	return "";
}
function changeRowColor(element, className, form){
	var form2= (form!= null)?form:document.defaultForm;
	if (form2[element.id].checked) 
		return;
	element.className = className;
}
/* Fim fun??es tabela de listagem */


var CONTEXTO = "/crm";
var SERVLET = "CrmServlet/";
var UPLOAD_SERVLET = "UploadServlet/";

function submitForm(aForm) {
	var action = createAction(aForm);
	
	var param = "";

	for(var i=0;i < aForm.length;i++){			 
		param += aForm.elements[i].name + "="; 
		param += escape(aForm.elements[i].value) + "&";			 
	} 
	var url = action + "?" + param.substring(param.length - 1,0);

	document.location.replace(url);
}

function windowOpen(action, width, height){	
	var url = CONTEXTO + "/" + SERVLET + action;
	if (width == null) width = 420;
	if (height == null) height = 400;
	var top = (screen.availHeight - height) / 2;
	var left = (screen.availWidth - width) / 2;
	var wnd = window.open(url, "wnd", "width=" + width + ",height=" + height + ",scrollbars=no,dependent=yes,left=" + left +",top="+top+",toolbar=no");
	wnd.focus();
}

/*
 * Forma uma url levando em considera??o o contexto o servlet e a action que ser? executada.
 */
function createAction(aForm, servletToCall){
	var servlet = (servletToCall == null || servletToCall == "")?SERVLET:servletToCall;
	if (document.all){
		return CONTEXTO + "/" + servlet + aForm.action;
	}else {
		var idx = aForm.action.lastIndexOf("/");
		if (idx < 0)
			return CONTEXTO + "/" + servlet + aForm.action;
			
		return CONTEXTO + "/" + servlet + aForm.action.substring(idx + 1, aForm.action.length);
	}	
}

function setTextValue(obj, value){
	if (obj != null)
		obj.value = value;
	return true;
}

function goServlet(url) {
  document.location.replace(CONTEXTO + "/" + SERVLET + url);
}

function setOptionValue(obj, value){
	if ((obj != null) && (obj.options != null))	{
		for (var i=0; i<obj.options.length; i++)
			if (obj.options[i].value == value)
				obj.options[i].selected = true;
			else
				obj.options[i].selected = false;
	}
	return true;
}

function setPage(numberPage){
	if (numberPage != -1)
		refresh(null, null, numberPage);
	return true;
}

function sort(orderField, order){
	refresh(orderField, order);
	return true;
}

function filter(filterField, value)
{
	if (value != "")
	{
		//value = "%" + value + "%";
		refresh(null, null, 0, filterField, value);
	}
	return true;
}

function clearFilter(url){
	var otherFilters	="";
	var desc 			="";
	
	for (var i = 0; i < advancedFilters.length;i++){
		if (advancedFilters[i]!="")	
			otherFilters += advancedFilters[i] + "&"
	}
	for (var i = 0; i < filterDesc.length;i++){
		if (filterDesc[i]!="")	
			desc += filterDesc[i] + "&"
	}
	document.location.href=url + "?" + otherFilters + desc;
}

function refresh(pOrderField, pOrder, pPage){
	var desc 			    = "";

	if (pOrderField != null)
		orderField = pOrderField;

	if (pOrder != null)
		order = pOrder;

	if (pPage != null)
		page = pPage;

	if (url.lastIndexOf("?") < 0)	url += "?";
	document.location.replace(url + "orderField=" + orderField + "&order=" + order + "&page=" + page );
	return true;
}

function go(url) {
  document.location.replace(CONTEXTO+"/"+url);
}



function createUrl(url) {
	return url;
}

function createUrlParam(url,name,value) {
	return createUrl(url)+"?"+name+"="+value;
}

function abreSelecao(field, campo1, campo2,url,paramName, paramValue){
		campo1.value="";
		campo2.value="";		
		janela = window.open(createUrlParam(url,paramName,paramValue),field,'status=no,resizable=no,scrollbars=yes,menubar=no,width=400,height=420') ;
		janela.moveBy = ((screen.width-400)/2,(screen.height-420) /2);
}



function sortCombo(combo)
{
	for (var i=0; i<(combo.options.length-1); i++)
		for (var j=i; j<combo.options.length; j++)
			if (combo.options[j].text < combo.options[i].text)
			{
				var tmp = combo.options[j].value;
				combo.options[j].value = combo.options[i].value;
				combo.options[i].value = tmp;
				tmp = combo.options[j].text;
				combo.options[j].text = combo.options[i].text;
				combo.options[i].text = tmp;
			}
}

function addCombo(combo, text, value)
{
	combo.options[combo.options.length] = new Option(text, value);
}

function removeSelectedCombo(combo)
{
	var j=0;
	for (var i=0; i<combo.length; i++)
	{
		combo.options[j].value = combo.options[i].value;
		combo.options[j].text  = combo.options[i].text;
		if (!combo.options[i].selected)
			j++;
		combo.options[i].selected = false;
	}
	combo.length = j;
}

function selectAllCombo(combo) {
	for(i= 0; i < combo.options.length ; i++) {
		combo.options[i].selected = true;
	}	
}

function valuesCombo(combo)
{
	var ret = "";
	for (var i=0; i<combo.length; i++)
	{
		if (ret.length != "") 
			ret += "|";
		ret += combo.options[i].value;
	}
	return ret;
}

function getTitleAndSubTitle(titulo, subTitulo)
{
	var title = "title=" + (titulo? titulo: (titleDefault? titleDefault: ""));
	var subtitle = "&subTitle="+ (subTitulo? subTitulo: (subTitleDefault? subTitleDefault: ""));
	return title + subtitle;
}

function openSelect(action, obj, width, height)
{
	
	var url = escape(CONTEXTO+"/"+SERVLET+action);
	var frmSelect = CONTEXTO + "/jsp/selecao.jsp?url=" + url + "&object=" + obj;
	if (width == null) width = 420;
	if (height == null) height = 400;
	var top = (screen.availHeight-400) /2;
	var left = (screen.availWidth-380)/2;
	var wndSelect = window.open(frmSelect, "wndSelect", "width=" + width + ",height=" + height + ",scrollbars=no,dependent=yes,left=" + left +",top="+top+",toolbar=no");
	wndSelect.focus();
}

/**
 * Defini??o das Action's default
 *  Para Action personalizada, ? s? criar no corpo do JSP
 **/
function cancelAction(){
    go("jsp/includes/stackPop.jsp");
}

function filterAction()
{
	if(document.formFilter.filterValue.value==""){
		alert("O filtro deve possuir um valor.");
		document.forms[0].filterValue.focus();
	}else{
		filter(document.formFilter.filterField[document.formFilter.filterField.selectedIndex].value, document.formFilter.filterValue.value);
	}
}

function clearFilterAction(){
	clearFilter(url);
}

function formataData(Campo,teclapres, formulario) {

	var form;
	var tecla =(document.all)?teclapres.keyCode:teclapres.which;
	if (formulario != null)
		form = document.forms[formulario];
	else
		form = document.form;
	if (form[Campo].maxLength == form[Campo].value.length)
		return;
	vr = form[Campo].value;
	vr = vr.replace( ".", "" );
	vr = vr.replace( "/", "" );
	vr = vr.replace( "/", "" );
	tam = vr.length ;

	if ( tecla >= 48 && tecla <= 57){
		if(tam == 2){
			form[Campo].value = vr.substr( 0, tam) +"/";
		}else if(tam ==4 ){
			form[Campo].value = vr.substr( 0, tam-2) + "/" + vr.substr( 2, tam) + "/";
		}
		return;
	}else if( tecla!=46 &&  tecla!=8 && tecla!=36){
		if(document.all){
			teclapres.keyCode=0;
		}else{
			teclapres.charKey=0;
		}
	}
}
/* Essa fun??o formata a hora no pattern HH:mm
 * deve ser passado o nome do campo e o event
 */
function formataHora(Campo,teclapres) {

	var tecla =(document.all)?teclapres.keyCode:teclapres.which;

	vr = document.form[Campo].value;
	vr = vr.replace( ".", "" );
	vr = vr.replace( ":", "" );
	vr = vr.replace( ":", "" );
	tam = vr.length ;

	if ( tecla >= 48 && tecla <= 57){
		if(tam == 2){
			document.form[Campo].value = vr.substr( 0, tam) +":";
		}
	}else if( tecla!=46 &&  tecla!=8 && tecla!=36){
		if(document.all){
			teclapres.keyCode=0;
		}else{
			teclapres.charKey=0;
		}
	}
}

/* Essa fun??o valida a hora digitada
 * deve ser passado o nome do campo
 */
 function validaHora(campo){
 	var value = document.form[campo].value;
 	
 	if ((value.length > 0)&&(value.length == 5)){
 		var hora 	= parseInt(value.substring(0,2));
 		var minutos = parseInt(value.substring(3,5));
 		
 		if ((hora > 24)||(minutos >60)){
 			alert("Hora inv\u00E1lida.");
 			document.form[campo].value="";
 			document.form[campo].focus();
 			return;
 		}
 	}else if((value.length < 5)&&(value.length != 0)){
 		alert("Hora inv\u00E1lida.");
 		document.form[campo].value="";
 		document.form[campo].focus();
 		return;
 	}
 	return true;
 }
 
 
/* Esta funcao valida a data digitada.
 * deve ser passado como parametro o nome do campo 
 */
function  validaData(campo, formulario){
	var form;
	if (formulario != null)
		form = document.forms[formulario];
	else
		form = document.form;

	var data = form[campo].value;
	if (data.length > 0){
	
		var dia = parseInt(data.substring(0,2),10);
		var mes = parseInt(data.substring(3,5),10);
		var ano = parseInt(data.substring(6,10),10);
		
		if (dia <= 31 && mes <=12 && ano >= 1000){
			if (data.substring(0,1)=='0' && data.substring(1,2) != '0' || data.substring(0,1)!='0'){
				if (data.substring(2,3)=="/"){
					if (data.substring(3,4)=='0' && data.substring(4,5)!='0' || data.substring(3,4)!='0'){
						if (data.substring(5,6)=="/"){
							if (data.substring(6,7)== '0' || data.substring(6,7)=='' && data.substring(7,8)!='0'){
								window.alert('O ano que você digitou não existe!');
								form[campo].value="";
								ocument.form[campo].focus();
								return;
							}
							else {
								if (mes == 2){
									if ((dia > 0 ) && (dia <= 29)){
										if (dia == 29){
											if ((ano % 4) == 0){
												return true;
											}
											else{
												window.alert('Data inválida.');
												form[campo].value="";
												form[campo].focus();
												return;
											}
										}
									}
									else {
										window.alert('Data inválida.');
										form[campo].value="";
										form[campo].focus();
										return;
									}
								}
								if ((mes == 4)||(mes == 6)||(mes == 9)||(mes == 11)){
									if ((dia > 0 ) && (dia <= 30)){
										return true;
									}
									else{
										window.alert('Data inválida.');
										form[campo].value="";
										form[campo].focus();
										return;
									}
								}
								if ((mes == 1)||(mes == 3)||(mes == 5)||(mes ==7)||(mes == 8)||(mes == 10)||(mes == 12)) {
									if ((dia > 0) && (dia <= 31)) {
										return;
									}
									else{
										window.alert('Data inválida.');
										form[campo].value="";
										form[campo].focus();
										return;
									}
								}
							}
						}
						else{
							window.alert('Data inválida.');
							form[campo].value="";
							form[campo].focus();
							return;
						}
					}
					else{
						window.alert('Data inválida.');
						form[campo].value="";
						form[campo].focus();
						
						return;
					}
				}
				else{
					window.alert('Data inválida.');
					form[campo].value="";
					form[campo].focus();
					return;
				}
			}
			else{
				window.alert('Data inválida.');
				form[campo].value="";
				form[campo].focus();
				return;
			}
		}
		else{
			window.alert('Data inválida.');
			form[campo].value="";
			form[campo].focus();
			return;
		}
		return true;
	}
	return true;
}


/* Esta funcao substritui a 'virgula' de um campo decimal por um 'ponto'.
 * Deve ser passado como parametro o nome do campo 
 */
function tiraVirgula(campo){    
	if (document.form[campo].value.length > 0){
       conteudo = new String(document.form[campo].value);
       rExp = /,/gi;
       document.form[campo].value = conteudo.replace(rExp, new String("."));
    }
}

function PontoToVirgula(campo){
	if (document.form[campo].value.length > 0){
       conteudo = new String(document.form[campo].value);
       document.form[campo].value = conteudo.replace(".", new String(","));
       document.form[campo].select();
       document.form[campo].focus();
    }
}
function VirgulaToPonto(campo){
	if (document.form[campo].value.length > 0){
       conteudo = new String(document.form[campo].value);
       rExp = /,/gi;
       document.form[campo].value = conteudo.replace(rExp, new String("."));
    }
}
/*Esta funcao valida se o campo eh numerico ou nao. 
 * Deve ser passado como parametro o nome do campo  
 */
function isNumber(campo){
	if (campo != ''){	
		valor = document.form[campo].value;			
		tam = document.form[campo].value.length

	   if (tam > 0){
			tiraVirgula(campo)
			valor = document.form[campo].value
			if (isNaN(valor)) {
				alert ("Valor digitado inválido.");
				document.form[campo].value = "";
				document.form[campo].focus();
				return false;
			}else{
				return true;
			}
		}else{
			return true;
		}
	}else{
		return true;
	}
}

/* Esta funcao formata e o CEP. 
 * Deve ser passado como parametro o nome do campo 
 */
function Formata_CEP(campo) {
	vr = document.form[campo].value;
	vr = vr.replace( "-", "" );
	tam = vr.length;

	if (tam == 8) {
	  document.form[campo].value = vr.substr(0, 5) +"-"+ vr.substr(5,3);
	 }
	else if ((tam < 8 && tam > 0)||(tam > 8)) {
	  alert ("Tamanho inválido de CEP");
	  document.form[campo].focus();
	  document.form[campo].select();
	}
}

/* Esta funcao valida o e-mail digitado. 
 * Deve ser passado como parametro o nome do campo 
 */
function verificaEmail(campo){
	var email = document.form[campo].value;
	if (email != ''){
		var arroba = false;
		var ponto = false;
		for (var i = 0; i < email.length; i++){
			if (email.substring(i-1,i) == "@"){
				arroba = true;
			}
			if (email.substring(i-1,i) == "."){
				ponto = true;
			}
		}
		if ((arroba == false) || (ponto == false)){
			alert("E-mail inválido.");
			document.form[campo].focus();
			document.form[campo].select();
		}
	}
}

function crypt(pwd){
	var strKey = "SENHADOUSUARIO1";
	var i, j;
	var s1,s2;
	var s4;
	var s5= new Array(pwd.length);
	var s6 ="";
	s1 = new String("QWERTYUIOPASDFGHJKLZXCVBNM1234567890[];',./-=\\`{}:<>?_+|~!@#$%^&*() \"");
	s2 = new String("!1QAZ@2WSX#3EDC$4RFV%5TGB^6YHN&7UJM*8IK,<(9OL.>)0P;:/?_-[{'\"+=}]|\\`~ ");
	pwd = pwd.toUpperCase()  + strKey.substring(pwd.length, strKey.length);

	
	for (i = 0; i < pwd.length; i++){
		s4 = pwd.charAt(i);
		s5[i] = s4;
		for (j = 0; j < s1.length; j++){
			if (s1.charAt(j) == s4){
				var chr= s2.charCodeAt(j);
				s5[i] =String.fromCharCode(chr + i);
				s6 += s5[i];
				break;					
			}
		}
	}
	return new String(s6);
	
}
function login(form){
//	alert(form.action + "?senha=" + crypt(form.senha.value) + "&uid=" + form.uid.value);
//	alert(form.action + "?senha=" + crypt(form.senha.value) + "&uid=" + form.uid.value);
	document.location.replace(form.action + "?senha=" + form.senha.value + "&uid=" + form.uid.value);
}

function showHelp(){
	var tela = document.location.pathname;
	tela = tela.substring(tela.lastIndexOf("/")+ 1,tela.length);	
	var url = escape(CONTEXTO+"/"+SERVLET) + "HelpViewAction?tela=" + tela;
	var width = screen.availWidth - 10;	
	var height = screen.availHeight -20;
	var top = 0;
	var left = 0;
	var wndHelp = window.open(url, "wndHelp", "width=" + width + ",height=" + height + ",resizable=yes,scrollbars=yes,dependent=yes,left=" + left +",top="+top+",menubar=no");
	wndHelp.focus();
}

function showMenuOptions(){
	var oDiv	= document.getElementById("layer");
	var oTable	= document.getElementById("tableTitle");
	oDiv.style.left = (oTable.offsetWidth - parseInt(oDiv.style.width)+2)+ "px";
	var visible = (oDiv.style.visibility == "visible")?"hidden":"visible";
	oDiv.style.visibility = visible;
}
function changePosition(){
	var oDiv	= document.getElementById("layer");
	var oTable	= document.getElementById("tableTitle");
	oDiv.style.left = (oTable.offsetWidth - parseInt(oDiv.style.width))+ "px";
}
function printMainFrame(){
	if (top.window.frames.length > 1){
			top.frames['mainFrame'].focus();
	}
	var button = document.getElementById("tableButton");
	var navigation = document.getElementById("tableNavigation");
	if (button)
		button.style.display="none"
	 if (navigation)
		navigation.style.visibility = "hidden";
	window.print();
	if (button)
		button.style.display=""
	 if (navigation)
		navigation.style.visibility = "visible";
}

function limpar(object, teclapres, sufixo){
		//alert(object);
		//alert(teclapres);
		var tecla =(document.all)?teclapres.keyCode:teclapres.which;
		if (tecla != 46)return;
		if (object==null){
			for(var i=0; i < document.form.length;i++){
				document.form.elements[i].value = "";
			}
			document.form.elements[0].focus();
		}else{
			if (sufixo==null){
				document.form[object + "Desc"].value="";
			}else{
				document.form[object + sufixo].value="";
			}
			document.form[object].value="";
		}
	}
function 	setStatusBarMessage(){
	window.status='Criterium Business Mobile';
	return true;
}




var mouseOver = false;
var objRetorno ="";
var frameRetorno = "";
function showCalendar(obj, evento, frame){
	var oImg = document.getElementById(obj);
	var left  = evento.clientX;
	var top= evento.clientY;
	oCalendar = document.getElementById("calendar");
	oCalendar.style.left = left + "px";
	oCalendar.style.top = top + "px";
	oCalendar.style.visibility = 'visible';
	setTimeout("hide()",900);
	oFrame = window.frames['frameCalendar'];	
	oFrame.start();
	objRetorno = obj;
	if (frame)
		frameRetorno = frame;
}

function hide(){
		oCalendar = document.getElementById("calendar");
		if (mouseOver){
			setTimeout("hide()",2000);
		}else{
			oCalendar.style.visibility = 'hidden';
		}
}	
function setMouseOver(){
	mouseOver = true;
}
function setMouseOut(){
	mouseOver = false;
}
function showPanel(name){
   if (selectedTab){
      selectedTab.style.backgroundColor = '';
      selectedTab.style.paddingTop = '';
      selectedTab.style.paddingBottom = '';
		  selectedTab.style.fontWeight = '';
   }
   selectedTab = document.getElementById("bt_" + name);
   selectedTab.style.backgroundColor = '#FFFFFF';
   selectedTab.style.paddingTop = '2px';
   for(i = 0; i < panels.length; i++){
      document.getElementById(panels[i]).style.display = (name == panels[i]) ? 'block':'none';
      document.getElementById(panels[i]).style.visibility = (name == panels[i]) ? 'visible':'hidden';
			if(document.all){
				document.getElementById("bt_" + panels[i]).style.borderBottomStyle = (name == panels[i]) ? 'none':'solid';			
			}else{
				document.getElementById("bt_" + panels[i]).style.borderBottomColor = (name == panels[i]) ? '#FFFFFF':'#A6C2FF';			
			}
			document.getElementById("bt_" + panels[i]).style.height = (name == panels[i]) ? '20px':'15px';
			document.getElementById("bt_" + panels[i]).style.fontWeight = (name == panels[i]) ? 'bold':'normal';
			document.getElementById(panels[i]).style.top = (document.all) ? '1px':'5px';
   }
}
/**
 * Compara duas datas verificando se a data inicial ? inferior a data final.
 */
function comparaDatas(data1,data2){
	
		var dtIni = data1.split("/");
		var dtFim = data2.split("/");
		
		var dataIni = new Date(dtIni[2],dtIni[1],dtIni[0]);
		var dataFim = new Date(dtFim[2],dtFim[1],dtFim[0]);
		return (dataIni <= dataFim);
}

function formatNumber (Val)  {
	OutString="";
	len=Val.length;
	centpos=Val.lastIndexOf(".")
	if (centpos != -1){
		cent="," + Val.substring(centpos+1,len) + "00"
		cent=cent.substring(0,3)
		Val=Val.substring(0,centpos)
		len=Val.length;
		}
	else {
		cent=",00"
	}
	if (len>=1) {
		while (len>0) {
			TempString=Val.substring(len-3, len)
			if (TempString.length==3) {
				OutString=TempString+OutString
				len=len-3;
			} else {
				OutString=TempString+OutString
				len=0
			}
		}
		if (OutString.substring(0, 1)==".") 
			Val=OutString.substring(1,OutString.length)+cent
		else
			Val=OutString + cent
	} 
	return Val;
}

function mover(obj, color) {
    if (color == undefined) {
      obj.style.backgroundColor = '#F6F6F6';
    } else {
      obj.style.backgroundColor = color;
    }
  }

  // ----------------------------------------------------------------------

  function mout(obj, color) {
    if (color == undefined) {
      obj.style.backgroundColor = '#DFDFDF';
    } else {
      obj.style.backgroundColor = color;
    }
  }
  function  closeWindow(){
	window.close();
	opener.focus();
  }
  
  
  // Compartilhamento de Arquivos --------------------------------
  function getUrlUpload(action){
	return 'javascript:goUploadServlet("'+ action + '");' ;
}

function goUploadServlet(url) {  
  document.location.replace(CONTEXTO + "/" + UPLOAD_SERVLET + url); 
}

function getUrl(action){	
	return 'javascript:goServlet("'+ action + '");' ;
}
