/*
.
.       RPC - Rede Paranaense de Comunicacao
.       Projeto: Framework AJAX
.       Modulo: ajax.js
.       Criado em: 16/01/2007
.       Autor: pauloh@rpc.com.br
.       Revisado por: ...
.       Ultima alteracao em:

*/

/* objeto Loader */
function Loader(id_loader, src_loader) {
	this.id_loader = id_loader || "";
	this.src_loader = src_loader || "/ajax_rpc/img/loader_default.gif";
	this.init = function() {
		if (id_loader == "") return; //retorna se nao tem objeto pra por o loader
		//$(this.id_loader).innerHTML = '<img src="'+this.src_loader+'" alt="loading" title= "loading" />';
	}
	this.stop = function() {
		if (id_loader == "") return; //retorna se nao tem objeto pra por o loader
		//$(this.id_loader).innerHTML = "";
	}
}

/* Retorna o elemento em forma de objeto pelo ID */
function $(element) {
	if (arguments.length > 1) {
		for (var i = 0, elements = [], length = arguments.length; i < length; i++)
		elements.push($(arguments[i]));
		return elements;
	}
	if (typeof element == 'string')
		element = document.getElementById(element);
	return element;
}

/* Retorna o elemento em forma de objeto pela TAG */
function $TAG(tag, escopo) {
	if (arguments.length == 1) {
		escopo = document;
	}
	if (typeof tag == 'string')
		element = escopo.getElementsByTagName(tag);
	return element;
}

/* Retorna o objeto target do evento */
function $target(evt) {
        if(evt.target) {
                return evt.target;
        } else {
                return evt.srcElement;
        }
}   

/* Adiciona eventos a uma colecao de elementos */
function addEventCollection (elementos, evento, funcao, useCapture) {
	for (var i = 0, length = elementos.length; i < length; i++) {
		addEvent(elementos[i], evento, funcao, useCapture);
	}
}

/* Adiciona evento a um elemento */
function addEvent(elemento, evento, funcao, useCapture) {
	if (elemento.addEventListener) {
		elemento.addEventListener(evento, funcao, useCapture);
	} else if (elemento.attachEvent) {
		elemento.attachEvent('on' + evento, funcao);
	}
}

/* Cria o Objeto HttpXmlRequest */
function createAjaxObj(isXML){
	var httprequest=false
	if (window.XMLHttpRequest){ // if Mozilla, Safari etc
		httprequest=new XMLHttpRequest()
		if(isXML) {
			if (httprequest.overrideMimeType)
				httprequest.overrideMimeType('text/xml')
		}
	}
	else if (window.ActiveXObject){ // if IE
		try {
			httprequest=new ActiveXObject("Msxml2.XMLHTTP");
		}
		catch (e){
			try{
			httprequest=new ActiveXObject("Microsoft.XMLHTTP");
			}
			catch (e){}
		}
	}
	return httprequest
}

/* Envia a requisicao para o servidor e manipula seu retorno */
function ajax_send(pagina_php, parameters, funcao_retorno, isXML, method, assync){
	xmlHttp=createAjaxObj(isXML)

	//define o que fazer com o resultado da transacao
	xmlHttp.onreadystatechange = function () {
		if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete") { 
			var result = xmlHttp.responseText;
			//chama a funcao de retorno enviando result como parametro;
			funcao_retorno.call(this, result);
		} 
	}

	if(typeof method != 'string') {
		method = 'GET'
	}
        if(typeof assync != 'string') {
		assync = true
	}
	xmlHttp.open(method, pagina_php+"?"+parameters, assync)
	xmlHttp.send(null)
}

/* Envia a requisicao e se tiver uma area de loader coloca um gif animado durante a transacao */
function ajax_do(pagina_php, parameters, funcao_retorno, loader, isXML, method, assync) {
	if(typeof loader == 'object') {
		loader.init();
		ajax_send(pagina_php, parameters, funcao_retorno, isXML, method, assync);
		loader.stop();
	} else {
		ajax_send(pagina_php, parameters, funcao_retorno, isXML, method, assync);
	}
}

/* Trata o resultado do xmlRequest com JSON */
function montaResultadoXmlRequest(result) {
	if(result != null && result != '')
		return result.parseJSON();
	else
		return false;
}

/* adiciona um elemento na arvore DOM */
function addElement(id, escopo) {

    var elem = $(id)
	if (arguments.length == 1) {
		escopo = document;
	} else {
		escopo = $(escopo);
	} 

    escopo.appendChild(elem);
}

/* remove um elemento da arvore DOM */
function removeElement(id) {
	var elem = $(id)
	elem.parentNode.removeChild(elem)
}

/* Remove todos os options de um select */
function cleanSelect(select) {

	var obj = null;
	if(typeof select == 'string') { //foi passado um id
		obj = $(select);
	} else { //foi passado um objeto select
		obj = select;
	}

	// apaga os itens existentes
	for (i = obj.options.length; i >= 0; i--) {
		obj.options[i] = null; 
	}
}

/* preenche um select a partir de um array de valores[valor][texto] */
function fillSelect(id_select, arrayItens, txt, check) {
	var i, j;
	var select = $(id_select);

	//remove os objetos existentes
	cleanSelect(select);

	//verifica se tem txt, se tiver adiciona no inicio um option com ele;
	if(txt == null) {
		j = 0;
	}
	else {
		select.options[0] = new Option(txt);
		select.options[0].value = 0;
		j = 1;
	}

	//Verifica se o check nao e nulo
	if(check == null) {
		check = 0;
	}

	if (arrayItens != null) {
		// add new items
		for (i = 0; i < arrayItens.length; i++) {

			//verifica se o array so tem um nivel
			if(typeof arrayItens[i] == "string") {
				//cria um novo objeto Option com o texto
				select.options[j] = new Option(arrayItens[i]);

				//insere o valor do option com o indice dele
				select.options[j].value = i;
			}
			//array tem 2 niveis
			else {
				//cria um novo objeto Option com o texto
				select.options[j] = new Option(arrayItens[i][1]);

				//verifica se há valores para esse texto
				if (arrayItens[i][0] != null) {
				select.options[j].value = arrayItens[i][0]; 
				}

				//verifica se e o elemento selecionado
				if(arrayItens[i][0] == check) {
					select.options[j].selected = true;
				}
			}
			j++;
		}
	}
}

/* Exibe item de uma colecao */
function showItens(itens, hide) {
        
        //Esconde os itens enviados
        if(hide) {
                hideItens(hide);
        }

        //exibe os itens enviados
        if(typeof itens == 'string') { //e um id em string
                 $(itens).style.display = "block";
        } else { //e um objeto
                if( itens.length > 1) { //e uma colecao
                        for(i = 0; i < itens.length; i++) {
                                $(itens[i]).style.display = "block";
                        }
                } else { // e um item so
                         $(itens).style.display = "block";
                }
        }
}

/* Oculta um ou mais itens de uma colecao */
function hideItens(colecao) {
        if(typeof colecao == 'string') { //foi passado um id
                $(colecao).style.display = 'none';
        } else { //foi passado um objeto
                if(colecao.length) { //e uma colecao
                        for(i = 0; i < colecao.length; i++) {
                                $(colecao[i]).style.display = "none";
                        }
                } else { // e um item so
                         colecao.style.display = "none";
                }
        }
}

/* Mostra ou oculta um elemento na pagina */
function showHide(id) {
	if(arguments.length > 1) {
		showHideItens(arguments);
	} else {
		if( $(arguments[i]).style.display == 'none' ) {
			showItens($(arguments[i]));
		} else {
			hideItens($(arguments[i]));
		}
        }
}

/* Mostra ou oculta um ou mais elementos na pagina */
function showHideItens(itens) {
        for(i=0; i < arguments.length; i++) {
                if (typeof arguments[i] == 'string') {
			showHide(arguments[i]);
	       } else {
                        if(arguments[i].length) { //e uma colecao
				for(i = 0; i < arguments.length; i++) {
					showHide(arguments[i]);
				}
                        } else {// e um item so
				showHide(arguments);
                        }
                }
        }
}

/*TODO: cria um menu dropdown abaixo do campo id com os valores do array itens[texto][onclick] */
function createDropDown(id, itens) {

	$(id).parentNode.style.position = 'relative';
	var div = null;
	//cria um div dropdown
	if(!document.getElementById('dropdown')) {
		div = document.createElement("DIV");
		div.id = 'dropdown';
	} else {
		div = $('dropdown'); //recupera o dropdown existente
		div.innerHTML = ''; //apaga o conteudo do dropdown
	}
	
	div.style.position = 'absolute';
	div.style.top = $(id).style.height;
	div.style.right = '0px';
	div.style.background = '#eaeaea';
	div.style.border = '1px solid black';
	div.style.zIndex = '999';
	div.style.width = $(id).style.width;

	//adiciona o dropdown na pagina
	$(id).parentNode.appendChild(div);

	for(i = 0; i < itens.length; i++) {
		var span = document.createElement("SPAN");
		var txt = document.createTextNode(itens[i][0]);
		span.id = "spn"+i;
		span.style.display="block";
		span.style.width="100%";
		span.appendChild(txt);
		div.appendChild(span);

//		$('spn'+i).onclick = alert("CLICK: "+itens[i][1]);		 	
		//adiciona o clique na linha
		addEvent($('spn'+i), 'click', function() { alert("Click"); }, false);
		//pinta a linha qdo o mouse estiver por cima
		addEvent($('spn'+i), 'mouseover', function() { $target(arguments[0]).style.background='#83c6a3';}, false);
		//volta a cor normal da linha qdo o mouse sai
		addEvent($('spn'+i), 'mouseout', function() { $target(arguments[0]).style.background='#eaeaea';}, false);

	}

}


