function sack(file){
	this.AjaxFailedAlert = "Seu navegador não suporta as funcionalidades deste site.\n";
	this.requestFile = file;
	this.method = "POST";
	this.URLString = "";
	this.encodeURIString = true;
	this.execute = false;

	this.onLoading = function() { };
	this.onLoaded = function() { };
	this.onInteractive = function() { };
	this.onCompletion = function() { };

	this.createAJAX = function() {
		try {
			this.xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				this.xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (err) {
				this.xmlhttp = null;
			}
		}
		if(!this.xmlhttp && typeof XMLHttpRequest != "undefined")
			this.xmlhttp = new XMLHttpRequest();
		if (!this.xmlhttp){
			this.failed = true; 
		}
	};
	
	this.setVar = function(name, value){
		if (this.URLString.length < 3){
			this.URLString = name + "=" + value;
		} else {
			this.URLString += "&" + name + "=" + value;
		}
	}
	
	this.encVar = function(name, value){
		var varString = encodeURIComponent(name) + "=" + encodeURIComponent(value);
	return varString;
	}
	
	this.encodeURLString = function(string){
		varArray = string.split('&');
		for (i = 0; i < varArray.length; i++){
			urlVars = varArray[i].split('=');
			if (urlVars[0].indexOf('amp;') != -1){
				urlVars[0] = urlVars[0].substring(4);
			}
			varArray[i] = this.encVar(urlVars[0],urlVars[1]);
		}
	return varArray.join('&');
	}
	
	this.runResponse = function(){
		eval(this.response);
	}
	
	this.runAJAX = function(urlstring){
		this.responseStatus = new Array(2);
		if(this.failed && this.AjaxFailedAlert){ 
			alert(this.AjaxFailedAlert); 
		} else {
			if (urlstring){ 
				if (this.URLString.length){
					this.URLString = this.URLString + "&" + urlstring; 
				} else {
					this.URLString = urlstring; 
				}
			}
			if (this.encodeURIString){
				var timeval = new Date().getTime(); 
				this.URLString = this.encodeURLString(this.URLString);
				this.setVar("rndval", timeval);
			}
			if (this.element) { this.elementObj = document.getElementById(this.element); }
			if (this.xmlhttp) {
				var self = this;
				if (this.method == "GET") {
					var totalurlstring = this.requestFile + "?" + this.URLString;
					this.xmlhttp.open(this.method, totalurlstring, true);
				} else {
					this.xmlhttp.open(this.method, this.requestFile, true);
				}
				if (this.method == "POST"){
  					try {
						this.xmlhttp.setRequestHeader('Content-Type','application/x-www-form-urlencoded')  
					} catch (e) {}
				}

				this.xmlhttp.send(this.URLString);
				this.xmlhttp.onreadystatechange = function() {
					switch (self.xmlhttp.readyState){
						case 1:
							self.onLoading();
						break;
						case 2:
							self.onLoaded();
						break;
						case 3:
							self.onInteractive();
						break;
						case 4:
							self.response = self.xmlhttp.responseText;
							self.responseXML = self.xmlhttp.responseXML;
							self.responseStatus[0] = self.xmlhttp.status;
							self.responseStatus[1] = self.xmlhttp.statusText;
							self.onCompletion();
							if(self.execute){ self.runResponse(); }
							if (self.elementObj) {
								var elemNodeName = self.elementObj.nodeName;
								elemNodeName.toLowerCase();
								if (elemNodeName == "input" || elemNodeName == "select" || elemNodeName == "option" || elemNodeName == "textarea"){
									self.elementObj.value = self.response;
								} else {
									self.elementObj.innerHTML = self.response;
								}
							}
							self.URLString = "";
						break;
					}
				};
			}
		}
	};
this.createAJAX();
}

// retorno dos dados pesquisados
function retorno(xmlhttp) {
	dados = pegarConteudo(xmlhttp.responseText);
	for (i = 1; i < dados[0].length; i++)
	{
		if(document.getElementById(dados[0][i])){
			if(!document.getElementById(dados[0][i]).type){
				document.getElementById(dados[0][i]).innerHTML = dados[1][i];
			}else if (document.getElementById(dados[0][i]).type=="radio") {
			      setaValor(document.getElementById(dados[0][i]), dados[0][i], dados[1][i]);
			}else{
				document.getElementById(dados[0][i]).value = dados[1][i];
			}
		}
	}
}

function setaValor(radioObj, campo, newValue) {
	if(!radioObj)
		return;
   var radioObj = document.forms[document.getElementById(campo).form.name][campo];
	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;
         break;			
		}
	}
}



function pegarConteudo(str){
	var rows = new Array();       // Matriz com a linhas dos registros 
	str = retiraEnds(str);
	rows = str.split('<ROW>');  // Cria matriz com as linhas retornadas
	dados = extraiConteudo(rows[1]);
	return dados;
}

function retiraEnds(str) {
	while (str.indexOf("<ROOT/>")!=-1){str = str.replace("<ROOT/>","");}  // Retira o end da tag root
	while (str.indexOf("<ROW/>")!=-1){str = str.replace("<ROW/>","");}	 // Retira os ends das tags ROWS
	while (str.indexOf("/")!=-1){str = str.replace("/","");}              // Retira os ends das tags dos campos
	return str;
}

function extraiConteudo(regs) {
	var campo = new Array();      // Matriz dos nomes dos campos
	var conteudo = new Array();   // Matriz com os conteudos dos campos
	regs = regs.split('\n');      // Cria matriz com campos/conteudos

	for (i = 1; i < regs.length-1; i++){
		x = regs[i].substr(3,regs[i].length-1).split('>');	  // Separa nome do campo do conteudo
		campo[i] = x[0];
		conteudo[i] = x[1].split('<')[0];
	}
	return Array(campo, conteudo);
}

///////////////////////////////////////////////////////////////////////////////
// AJAX with Stripes sample JavaScript library. Provides functions to use an
// XMLHttpRequest to invoke a Stripes action (or other server side component)
// using the contents of a HTML form or a JavaScript object as parameters.
//
// Author: Tim Fennell
// (C) Copyright Tim Fennell, 2005.
///////////////////////////////////////////////////////////////////////////////

/**
 * Invokes a Stripes action using the contents of the supplied form. The named
 * event will be invoked on the server, and the retornoFunction will be
 * invoked. The retorno function will only be invoked when the request is
 * completed, and (unlike when using the XMLHttpRequest directly) the
 * XMLHttpRequest will be supplied as the first parameter to the retorno
 * function.
 *
 * @param form - a reference to a form object to be "submitted" using AJAX
 * @param event - the String name of the event to be fired when invoking the
 *                ActionBean. To invoke the default event pass either null or ""
 * @param retornoFunction - a function that takes a single parameter, the
 *        XMLHttpRequest, and will be invoked when the request has been processed
 * @return a reference to the XMLHttpRequest in case the caller would like to be
 *         able to manipulate it between sending the request and receive the
 *         retorno (e.g. cancelling it before re-invoking).
 */
function invokeActionForm(form, event, retornoFunction) {
    var url = form.action;
    if (event) {
        url += "?acao=" + event + getFormValuesAsQueryString(form);
		//document.write(url);
	}else{
        url += "?" + getFormValuesAsQueryString(form).slice(1);
    }

    return fetchFromUrl(url, retornoFunction);
}


/**
 * Invokes a Stripes action bound to the specified URL. May specify a named
 * event, or if an event name is not supplied, will invoke the default event
 * handler.
 *
 * @param url - the URL for the http request, which will be accessed asynchronously
 * @param event - the String name of the event to be fired when invoking the
 *                ActionBean. To invoke the default event pass either null or ""
 * @param params - a JavaScript object. Each property on the object will be
 *        in the query string sent to the server. If a property is an array each
 *        value will be included, otherwise the property will be treated as a
 *        single value.
 * @param retornoFunction - a function that takes a single parameter, the
 *        XMLHttpRequest, and will be invoked when the request has been processed
 * @return a reference to the XMLHttpRequest in case the caller would like to be
 *         able to manipulate it between sending the request and receive the
 *         retorno (e.g. cancelling it before re-invoking).
 */
function invokeActionUrl(url, event, params, retornoFunction) {
    var composedUrl = url;
    var linkChar = "?";

    if (event) {
        composedUrl += linkChar + event + "=";
        linkChar = "&";
    }

    if (params) {
        for (var key in params) {
            value = params[key];
            if (value instanceof Array) {
                for (var i=0; i<value.length; i++) {
                    composedUrl += linkChar + key + "=" + escape(value[i]);
                    linkChar = "&";
                }
            }
            else {
                composedUrl += linkChar + key + "=" + escape(value);
                linkChar = "&";
            }
        }
    }

    return fetchFromUrl(composedUrl, retornoFunction);
}


/**
 * Takes a form object and returns a JavaScript object containing the form field
 * names and values as would be submitted to the server.  Correctly handles
 * radio, checkboxes, single and multi selects - including them in the request
 * only if one or more values has been specified. Excludes button types
 * (submit, reset, button)
 *
 * @return a JavaScript object with a property for each form field to be
 *         submitted. The value of each property is an Array containing one or
 *         more values to be submitted.
 */
function getFormValuesAsMap(form) {
	var params = new Object();
	var inputs = form.elements;
	for (var i=0; i<inputs.length; i++) {
		var input = inputs[i];

		if (input.type == "radio" || input.type == "checkbox") {
			// For radios and checkboxes, include them only if checked
			if (input.checked == true) {
                if (params[input.name] == null) params[input.name] = new Array();
                params[input.name].push(input.value);
			}
		}
		else if (input.type == "select-multiple") {
			// For multi-selects we have to check each value
			for (var j=0; j<input.options.length; j++) {
				if (input.options[j].selected == true) {
                    if (params[input.name] == null) params[input.name] = new Array();
                    params[input.name].push(input.options[j].value);
				}
			}
		}
		else if (input.type == "submit" || input.type == "button" || input.type == "reset") {
			// Don't include button types in the submit
		}
		else {
			// Include any other type as a straight name=value
            if (params[input.name] == null) params[input.name] = new Array();
            params[input.name].push(input.value);
		}
	}

    return params;
}

/**
 * Takes a form object and returns a query string containing all the fields
 * that would be submitted to the server. See getFormValuesAsMap(form) for more
 * details on what's included. Each value is escaped before being included in
 * the query string.
 *
 * @return a query string. The query string will always start with an ampersand.
 */
function getFormValuesAsQueryString(form) {
    var params = getFormValuesAsMap(form);
    var queryString = "";

    for (var name in params) {
        var values = params[name];
        for (var i=0; i<values.length; i++) {
            queryString += "&" + name + "=" + escape(values[i]);
        }
    }

    return queryString;
}

/**
 * Gets a new XMLHttpRequest object.
 */
function getXmlHttpRequest() {
    try { return new XMLHttpRequest(); }
    catch (ex) { try {  return new ActiveXObject('Msxml2.XMLHTTP'); }
        catch (ex1) { try { return new ActiveXObject('Microsoft.XMLHTTP'); }
            catch(ex1) {       return new ActiveXObject('Msxml2.XMLHTTP.4.0'); }
        }
    }
}

/**
 * Utility method to make a request to the supplied URL and invoked hte retorno
 * function, passing it the XMLHttpRequest.
 */
// retorno padrao de dados

function fetchFromUrl(url, retornoFunction) {
    var xmlHttpRequest = getXmlHttpRequest();
    xmlHttpRequest.onreadystatechange = function() {
		if(xmlHttpRequest.readyState != 4){
			document.getElementById('carregando').className='mostra';
		}else if (xmlHttpRequest.readyState == 4 && retornoFunction != null) {
			document.getElementById('carregando').className='esconde';			
            retornoFunction(xmlHttpRequest);
        }
    }
    xmlHttpRequest.open("GET", url, true, "", "");
    xmlHttpRequest.send("");
    return xmlHttpRequest;
}