function $(e){
    if(typeof e=='string') {
        e=document.getElementById(e);
    }
    return e;
}

function $F(e) {
	return $(e).value;
}

function betterInnerHTML(id, html) {
	var newDiv = document.createElement('div');
	newDiv.innerHTML = html;
	while ($(id).lastChild != null) $(id).removeChild($(id).lastChild);
	$(id).appendChild(newDiv);
}


// Ajax /////////////////////////////////////////////////////////////////////////////////////////////////////////
Ajax.Responders.register({
	onCreate: function() {
		$("ajax-loading").style.visibility = "visible";
	},
	onComplete: function() {
		$("ajax-loading").style.visibility = "hidden";
	}
});

var MyAjax = {
	getMensagem: function(o) {
		try {
			return o.getElementsByTagName('mensagem')[0].firstChild.nodeValue;
		} catch(e) {
			return '';
		}
	},

	getSucesso: function(o) {
		try {
			return o.getElementsByTagName('sucesso')[0].firstChild.nodeValue;
		} catch(e) {
			return '';
		}
	},

	getValor: function(o) {
		try {
			return o.getElementsByTagName('valor')[0].firstChild.nodeValue;
		} catch(e) {
			return '';
		}
	},

	get: function(url,func) {
		new Ajax.Request(url, { method: 'post', onSuccess: function(transport){func(transport.responseXML)}, onFailure: this.mostraAlerta});
	},

	mostraAlerta: function() {
		alert('Ocorreu um erro durante a chamada AJAX');
	},

	atualiza: function(url, el) {
		new Ajax.Updater(el, url, { method: 'post', onFailure: this.mostraAlerta });
	},

	submit: function(url, frm, funcao) {
		new Ajax.Request(url, {
			method: 'post',
			parameters: $(frm).serialize(),
			onSuccess: function(response) {
				funcao(response.responseXML)
			},
			onFailure: this.mostraAlerta
		});
	}
}





// Adiciona eventos //////////////////////////////////////////////////////////////////////////////////////////
function addEvent( obj, type, fn ) {
	if ( obj.attachEvent ) {
		obj['e'+type+fn] = fn;
		obj[type+fn] = function(){obj['e'+type+fn]( window.event );}
		obj.attachEvent( 'on'+type, obj[type+fn] );
	} else
		obj.addEventListener( type, fn, false );
}

// Remove eventos /////////////////////////////////////////////////////////////////////////////////////////////
function removeEvent( obj, type, fn ) {
	if ( obj.detachEvent ) {
		obj.detachEvent( 'on'+type, obj[type+fn] );
		obj[type+fn] = null;
	} else
		obj.removeEventListener( type, fn, false );
}

// textCounter para o TEXTAREA ////////////////////////////////////////////////////////////////////////////////
function textCounter( field, countfield, maxlimit ) {
	var fieldValue = $(field).value;
	if ( fieldValue.length > maxlimit ) {
		fieldValue = fieldValue.substring( 0, maxlimit );
		$(field).value = fieldValue;
		return false;
	} else {
		$(countfield).innerHTML = maxlimit - fieldValue.length;
	}
}

// Popup de LOV ////////////////////////////////////////////////////////////////////////////////////////////////
function lov(paginaLov, nome_campo, largura) {
    if (largura == null) {
        largura = 350;
    }
    newWindow = window.open(paginaLov+'?nome_campo='+nome_campo+'&clear=1','newWin','toolbar=no,location=no,scrollbars=yes,resizable=no,width='+largura+',height=520,top=35,left=25');
}

// Popup de MLOV ///////////////////////////////////////////////////////////////////////////////////////////////
function lovm(paginaLov, largura) {
    if (largura == null) {
        largura = 350;
    }
    newWindow = window.open(paginaLov,'newWin','toolbar=no,location=no,scrollbars=yes,resizable=no,width='+largura+',height=520,top=35,left=25');
}

// Move itens entre 2 SELECTs ////////////////////////////////////////////////////////////////////////////////////
function move(index, to) {
	var list = document.frm.list;
	var total = list.options.length-1;

	if (index == -1) return false;
	if (to == +1 && index == total) return false;
	if (to == -1 && index == 0) return false;

	var items = new Array;
	var values = new Array;
	for (i = total; i >= 0; i--) {
		items[i] = list.options[i].text;
		values[i] = list.options[i].value;
	}
	for (i = total; i >= 0; i--) {
		if (index == i) {
			list.options[i + to] = new Option(items[i],values[i + to], 0, 1);
			list.options[i + to].value = values[i];
			list.options[i] = new Option(items[i + to], values[i]);
			list.options[i].value = values[i + to];
			i--;
		}
		else {
			list.options[i] = new Option(items[i], values[i]);
			list.options[i].value = values[i];
	  }
	}
	list.focus();
}

// Abre uma janela auxiliar (popup) //////////////////////////////////////////////////////////////////////////
function openAuxiliaryWindow(pagenumber){
	eval('auxwindow = window.open("../inc/auxiliar.php?pag=' +  pagenumber +
	     '","auxwindow","width=600,height=500,top=50,left=150' +
		  ',scrollbars=no,hscroll=0,dependent=yes,toolbar=no")');
	auxwindow.focus();
}


// funções pra manipular SELECTs //////////////////////////////////////////////////////////////////////////////
var NS4 = (navigator.appName == "Netscape" && parseInt(navigator.appVersion) < 5);

function addOption(theSel, theText, theValue) {
  var newOpt = new Option(theText, theValue);
  var selLength = theSel.length;
  theSel.options[selLength] = newOpt;
}

function deleteOption(theSel, theIndex) { 
  var selLength = theSel.length;
  if(selLength>0)  {
    theSel.options[theIndex] = null;
  }
}

function moveOptions(theSelFrom, theSelTo){
  
  var selLength = theSelFrom.length;
  var selectedText = new Array();
  var selectedValues = new Array();
  var selectedCount = 0;
  
  var i;
  
  for(i=selLength-1; i>=0; i--) {
    if(theSelFrom.options[i].selected) {
      selectedText[selectedCount] = theSelFrom.options[i].text;
      selectedValues[selectedCount] = theSelFrom.options[i].value;
      deleteOption(theSelFrom, i);
      selectedCount++;
    }
  }
  
  for(i=selectedCount-1; i>=0; i--) {
    addOption(theSelTo, selectedText[i], selectedValues[i]);
  }
  
  if(NS4) history.go(0);
}


// input mask //////////////////////////////////////////////////////////////////////////////////////////////////////
var InputMask = {
	format: function (campo, mascara) {
		if (mascara=='@R$') return this.formataDinheiro(campo);
		if (mascara=='@N') return this.formataNumero(campo);

		var saida, valor, tamCampo, tamMasc, i, nCount, sCod, bolMask;
		valor = this.clearValue($(campo).value);

		tamCampo = valor.length;
		tamMasc = mascara.length;

		i = 0;
		nCount = 0;
		sCod = "";
		tamMasc = tamCampo;
		while (i <= tamMasc) {
			bolMask = ((mascara.charAt(i) == ",") ||(mascara.charAt(i) == ":") || (mascara.charAt(i) == "-") || (mascara.charAt(i) == ".") || (mascara.charAt(i) == "/"));
			bolMask = bolMask || ((mascara.charAt(i) == "(") || (mascara.charAt(i) == ")") || (mascara.charAt(i) == " "));
			if (bolMask) {
				sCod += mascara.charAt(i);
				tamMasc++;
			} else {
				sCod += valor.charAt(nCount);
				nCount++;
			}
			i++;
		}
		$(campo).value = sCod;
	},
	formataDinheiro: function (campo) {
		$(campo).value = this.clearValue($(campo).value);
		vr = $(campo).value;
		tam = vr.length;

		if ( tam <= 2 ){ $(campo).value = vr ; }
		if ( (tam > 2) && (tam <= 5) ){ $(campo).value = vr.substr( 0, tam - 2 ) + ',' + vr.substr( tam - 2, tam ) ; }
 		if ( (tam >= 6) && (tam <= 8) ){ $(campo).value = vr.substr( 0, tam - 5 ) + '.' + vr.substr( tam - 5, 3 ) + ',' + vr.substr( tam - 2, tam ) ; }
 		if ( (tam >= 9) && (tam <= 11) ){ $(campo).value = vr.substr( 0, tam - 8 ) + '.' + vr.substr( tam - 8, 3 ) + '.' + vr.substr( tam - 5, 3 ) + ',' + vr.substr( tam - 2, tam ) ; }
		if ( (tam >= 12) && (tam <= 14) ){ $(campo).value = vr.substr( 0, tam - 11 ) + '.' + vr.substr( tam - 11, 3 ) + '.' + vr.substr( tam - 8, 3 ) + '.' + vr.substr( tam - 5, 3 ) + ',' + vr.substr( tam - 2, tam ) ; }
		if ( (tam >= 15) && (tam <= 18) ){ $(campo).value = vr.substr( 0, tam - 14 ) + '.' + vr.substr( tam - 14, 3 ) + '.' + vr.substr( tam - 11, 3 ) + '.' + vr.substr( tam - 8, 3 ) + '.' + vr.substr( tam - 5, 3 ) + ',' + vr.substr( tam - 2, tam ) ;}
	},
	formataNumero: function (campo) {
		var str = $(campo).value;
		$(campo).value = str;
	},
	clearValue: function (valorCampo) {
		var valor = valorCampo;
		valor = valor.toString().replace( /\-/g, "" );
		valor = valor.toString().replace( /\:/g, "" );
		valor = valor.toString().replace( /\./g, "" );
		valor = valor.toString().replace( /\,/g, "" );
		valor = valor.toString().replace( /\//g, "" );
		valor = valor.toString().replace( /\(/g, "" );
		valor = valor.toString().replace( /\)/g, "" );
		valor = valor.toString().replace( / /g, "" );
		return valor;
	}
	
}

// hint /////////////////////////////////////////////////////////////////////////////////////////////////
var hintcontainer = null;

function showhint(obj, txt) {
	if (hintcontainer == null) {
		hintcontainer = document.createElement("div");
		hintcontainer.className = "hintstyle";
		document.body.appendChild(hintcontainer);
	}
	obj.onmouseout = hidehint;
	obj.onmousemove = movehint;
	hintcontainer.innerHTML = txt;
}
function movehint(e) {
	if (!e) e = event;
	hintcontainer.style.top = (e.clientY+document.documentElement.scrollTop+2)+"px";
	hintcontainer.style.left = (e.clientX+document.documentElement.scrollLeft+10)+"px";
	hintcontainer.style.display = "";
}
function hidehint() {
	hintcontainer.style.display = "none";
}

// innerHTML especial para campos SELECT ////////////////////////////////////////////////////////////////
function innerHTML4Select(objeto,innerHTML) {
	var objeto = $(objeto);
	objeto.innerHTML = ""
	var selTemp = document.createElement("myselect")
	var opt;
	selTemp.id="myselect1"
	document.body.appendChild(selTemp)
	selTemp = document.getElementById("myselect1")
	selTemp.style.display="none"
	if(innerHTML.toLowerCase().indexOf("<option")<0){//se não é option eu converto
		innerHTML = "<option>" + innerHTML + "</option>"
	}
	innerHTML = innerHTML.toLowerCase().replace(/<option/g,"<span").replace(/<\/option/g,"</span")
	selTemp.innerHTML = innerHTML
	
	for(var i=0;i<selTemp.childNodes.length;i++) {
		var spantemp = selTemp.childNodes[i];
		
		if(spantemp.tagName) {
			opt = document.createElement("OPTION")
			
    
   if(document.all){ //IE
    objeto.add(opt)
   }else{
    objeto.appendChild(opt)
   }       
    
   //getting attributes
   for(var j=0; j<spantemp.attributes.length ; j++){
    var attrName = spantemp.attributes[j].nodeName;
    var attrVal = spantemp.attributes[j].nodeValue;
    if(attrVal){
     try{
      opt.setAttribute(attrName,attrVal);
      opt.setAttributeNode(spantemp.attributes[j].cloneNode(true));
     }catch(e){}
    }
   }
   //getting styles
   if(spantemp.style){
    for(var y in spantemp.style){
     try{opt.style[y] = spantemp.style[y];}catch(e){}
    }
   }
   //value and text
   opt.value = spantemp.getAttribute("value")
   opt.text = spantemp.innerHTML
   //IE
   opt.selected = spantemp.getAttribute('selected');
   opt.className = spantemp.className;
  } 
 }    
 document.body.removeChild(selTemp)
 selTemp = null
}


// classe pra manipulação de formulários /////////////////////////////////////////////////////////////////////////////
var FormUtil = {
	// captura lista de opções do SELECT em forma de string
	stringFromSELECT: function(idSelect) {
		var list = $(idSelect);
		var theList = "0";
		for (i = 0; i <= list.options.length-1; i++) {
			theList += "," + list.options[i].value;
		}
		return theList;
	},
	
	// retorna o valor de um radiobutton se estiver checked
	getRadioValue: function(radioObj) {
		if(!radioObj) return "";
		var radioLength = radioObj.length;
		if(radioLength == undefined) if( radioObj.checked) return radioObj.value;
		else return "";
		for(var i = 0; i < radioLength; i++) {
			if(radioObj[i].checked) {
				return radioObj[i].value;
			}
		}
		return "";
	},
	
	// torna um radio checked a partir de um valor dado
	setRadioValue: function(radioObj, newValue) {
		if(!radioObj) return;
		var radioLength = radioObj.length;
		if(radioLength == undefined) {
			radioObj.checked = (radioObj.value == newValue.toString());
			return;
		}
		for(var i = 0; i < radioLength; i++) {
			radioObj[i].checked = false;
			if(radioObj[i].value == newValue.toString()) {
				radioObj[i].checked = true;
			}
		}
	},
	
	// Marca/desmarca todos os checkboxes da tabela
	checkAll: function(id) {
		var val = $(id).checkall.checked;
		for (var i=0; i < $(id).elements.length; i++) {
			if ($(id).elements[i].type=='checkbox') {
				$(id).elements[i].checked = val;
			}
		}
	},
	
	// Seleciona todos os itens do SELECT
	selectAll: function(id) {
		for (x=0; x < $(id).options.length; x++) {
			$(id).options[x].selected = true;
		}
	}	
}

// comportamento global da aplicação /////////////////////////////////////////////////////////////////////////////
var myTime;
var Core = {
	mostraMsg: function (str) {
		jQuery(function() {
			jQuery().message(str);
		});
	},
	
	apagaMsg: function (){
		 $('appmsg-container').style.visibility = "hidden";
	},
	
	mostraLoading: function(){
		$("loadingmsg").style.visibility = "visible";
	},
	
	apagaLoading: function(){
		$("loadingmsg").style.visibility = "hidden";
	},

	arrayMap: function(callback) {
		var argc = arguments.length, argv = arguments;
		var j = argv[1].length, i = 0, k = 1, m = 0;
		var tmp = [], tmp_ar = [];
		
		while (i < j) {
			while (k < argc) {
				tmp[m++] = argv[k++][i];
			}
			
			m = 0;
			k = 1;
			
			if (callback) {
				tmp_ar[i++] = callback.apply(null, tmp);
			} else {
				tmp_ar[i++] = tmp;
			}
			
			tmp = [];
		}
		return tmp_ar;
	}
}
