/*
Copyright (c) 2005 JSON.org

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The Software shall be used for Good, not Evil.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

Array.prototype.______array = '______array';

var JSON = {
  org: 'http://www.JSON.org',
  copyright: '(c)2005 JSON.org',
  license: 'http://www.crockford.com/JSON/license.html',

  stringify: function (arg) {
    var c, i, l, s = '', v;
    var numeric = true;

    switch (typeof arg) {
    case 'object':
      if (arg) {
        if (arg.______array == '______array') {
          // do a test whether all array keys are numeric
          for (i in arg) {
            if (i != '______array'
              && (isNaN(i)
                || !isFinite(i))) {
              numeric = false;
              break;
            }
          }

          if (numeric == true) {
            for (i = 0; i < arg.length; ++i) {
              if (typeof arg[i] != 'undefined') {
                v = this.stringify(arg[i]);
                if (s) {
                  s += ',';
                }
                s += v;
              } else {
                s += ',null';
              }
            }
            return '[' + s + ']';
          } else {
            for (i in arg) {
              if (i != '______array') {
                v = arg[i];
                if (typeof v != 'undefined' && typeof v != 'function') {
                  v = this.stringify(v);
                  if (s) {
                    s += ',';
                  }
                  s += this.stringify(i) + ':' + v;
                }
              }
            }
            // return as object
            return '{' + s + '}';
          }
        } else if (typeof arg.toString != 'undefined') {
          for (i in arg) {
            v = arg[i];
            if (typeof v != 'undefined' && typeof v != 'function') {
              v = this.stringify(v);
              if (s) {
                s += ',';
              }
              s += this.stringify(i) + ':' + v;
            }
          }
          return '{' + s + '}';
        }
      }
      return 'null';
    case 'number':
      return isFinite(arg) ? String(arg) : 'null';
    case 'string':
      l = arg.length;
      s = '"';
      for (i = 0; i < l; i += 1) {
        c = arg.charAt(i);
        if (c >= ' ') {
          if (c == '\\' || c == '"') {
            s += '\\';
          }
          s += c;
        } else {
          switch (c) {
            case '\b':
              s += '\\b';
              break;
            case '\f':
              s += '\\f';
              break;
            case '\n':
              s += '\\n';
              break;
            case '\r':
              s += '\\r';
              break;
            case '\t':
              s += '\\t';
              break;
            default:
              c = c.charCodeAt();
              s += '\\u00' + Math.floor(c / 16).toString(16) +
                (c % 16).toString(16);
          }
        }
      }
      return s + '"';
    case 'boolean':
      return String(arg);
    default:
      return 'null';
    }
  },
  parse: function (text) {
    var at = 0;
    var ch = ' ';

    function error(m) {
      throw {
        name: 'JSONError',
        message: m,
        at: at - 1,
        text: text
      };
    }

    function next() {
      ch = text.charAt(at);
      at += 1;
      return ch;
    }

    function white() {
      while (ch != '' && ch <= ' ') {
        next();
      }
    }

    function str() {
      var i, s = '', t, u;

      if (ch == '"') {
outer:      while (next()) {
          if (ch == '"') {
            next();
            return s;
          } else if (ch == '\\') {
            switch (next()) {
            case 'b':
              s += '\b';
              break;
            case 'f':
              s += '\f';
              break;
            case 'n':
              s += '\n';
              break;
            case 'r':
              s += '\r';
              break;
            case 't':
              s += '\t';
              break;
            case 'u':
              u = 0;
              for (i = 0; i < 4; i += 1) {
                t = parseInt(next(), 16);
                if (!isFinite(t)) {
                  break outer;
                }
                u = u * 16 + t;
              }
              s += String.fromCharCode(u);
              break;
            default:
              s += ch;
            }
          } else {
            s += ch;
          }
        }
      }
      error("Bad string");
    }

    function arr() {
      var a = [];

      if (ch == '[') {
        next();
        white();
        if (ch == ']') {
          next();
          return a;
        }
        while (ch) {
          a.push(val());
          white();
          if (ch == ']') {
            next();
            return a;
          } else if (ch != ',') {
            break;
          }
          next();
          white();
        }
      }
      error("Bad array");
    }

    function obj() {
      var k, o = {};

      if (ch == '{') {
        next();
        white();
        if (ch == '}') {
          next();
          return o;
        }
        while (ch) {
          k = str();
          white();
          if (ch != ':') {
            break;
          }
          next();
          o[k] = val();
          white();
          if (ch == '}') {
            next();
            return o;
          } else if (ch != ',') {
            break;
          }
          next();
          white();
        }
      }
      error("Bad object");
    }

    function assoc() {
      var k, a = [];

      if (ch == '<') {
        next();
        white();
        if (ch == '>') {
          next();
          return a;
        }
        while (ch) {
          k = str();
          white();
          if (ch != ':') {
            break;
          }
          next();
          a[k] = val();
          white();
          if (ch == '>') {
            next();
            return a;
          } else if (ch != ',') {
            break;
          }
          next();
          white();
        }
      }
      error("Bad associative array");
    }

    function num() {
      var n = '', v;
      if (ch == '-') {
        n = '-';
        next();
      }
      while (ch >= '0' && ch <= '9') {
        n += ch;
        next();
      }
      if (ch == '.') {
        n += '.';
        while (next() && ch >= '0' && ch <= '9') {
          n += ch;
        }
      }
      if (ch == 'e' || ch == 'E') {
        n += 'e';
        next();
        if (ch == '-' || ch == '+') {
          n += ch;
          next();
        }
        while (ch >= '0' && ch <= '9') {
          n += ch;
          next();
        }
      }
      v = +n;
      if (!isFinite(v)) {
        error("Bad number");
      } else {
        return v;
      }
    }

    function word() {
      switch (ch) {
        case 't':
          if (next() == 'r' && next() == 'u' && next() == 'e') {
            next();
            return true;
          }
          break;
        case 'f':
          if (next() == 'a' && next() == 'l' && next() == 's' &&
              next() == 'e') {
            next();
            return false;
          }
          break;
        case 'n':
          if (next() == 'u' && next() == 'l' && next() == 'l') {
            next();
            return null;
          }
          break;
      }
      error("Syntax error");
    }

    function val() {
      white();
      switch (ch) {
        case '{':
          return obj();
        case '[':
          return arr();
        case '<':
          return assoc();
        case '"':
          return str();
        case '-':
          return num();
        default:
          return ch >= '0' && ch <= '9' ? num() : word();
      }
    }

    return val();
  }
};

<!-- FIM FUNCÕES DE AJAX-->
var arrObject = new Array();
var count_ajax_erros = 0; //erros de não existir páginas de requisição de ajax
function createObjRequest(x){
 try {
	arrObject[x] = new ActiveXObject("Microsoft.XMLHTTP");
  }catch(e) {
	 try {
	   arrObject[x]  = new ActiveXObject("Msxml2.XMLHTTP");
	 }
	 catch(ex) {
		try {
		   arrObject[x]  = new XMLHttpRequest();
		}
		catch(exc) {
		   alert("Esse browser não tem recursos para uso de Ajax");
		   arrObject[x] = null;
		}
	 }
  }
}
function getEmptyObjectKey(){
	var key = false;
	for(x=0;x<arrObject.length;x++){
		if(arrObject[x].readyState == 0){
			key = x;
			break;
		}else if(arrObject[x].readyState == 4){
			createObjRequest(x);
			key = x
			break;
		}else{
			key = false;
		}
	}

	if(key === false){
		createObjRequest(arrObject.length);
		return arrObject.length-1;
	}else{
		return key;
	}
}
function getObjectResponseText(arrObjectsKey){
	object = arrObject[arrObjectsKey];
	if(object.readyState == 4 && object.responseText != "" && object.responseText.length > 0 && object.status == 200){
		var text = object.responseText;
		return url_decode(text);
	}else{
		return '';
	}
}

function getObjectResponseArray(arrObjectsKey){
	object = arrObject[arrObjectsKey];
	if(object.readyState == 4 && object.responseText != ' ' && object.responseText != '' && object.status == 200){		
		var text = object.responseText;
		if(!(text.search(/ajaxHtmlContent/i)>0)){
			var arrReturn = JSON.parse(url_decode(text));
			//var arrReturn = url_decode(text);
			if(arrReturn['ajaxError']){
				alert(arrReturn['ajaxError']['msg']);
				return false;
			}
			return arrReturn;
		}
	}else{
		return false;
	}
}

function getObjectResponseHtml(arrObjectsKey){
	object = arrObject[arrObjectsKey];
	if(object.readyState == 4 && object.responseText != ' ' && object.responseText != '' && object.status == 200){
		texto = object.responseText;
		
		if(!(texto.search(/ajaxHtmlContent/)>0)){
			if(arr = getObjectResponseArray(arrObjectsKey))
				return arr;
			else
				return '';
		}else{
			var arrReturn = texto;
		}
		
		return arrReturn;
		
	}else{
		return false;
	}
}

function fnDebugAjax(){

	var strr = '<b>Quantidade de objetos: '+arrObject.length+'<br><br>';

	for(x=0;x<arrObject.length;x++){
		if(arrObject[x].readyState == 1 || arrObject[x].readyState == 2 || arrObject[x].readyState == 3){
			strStatus="<font color='red'>Ocupado</font>";
		//}else if (object.status != 200){
			//strStatus="<font color='red'>ERRO com o arquivo de servidor</font>";
		}else{
			strStatus="<font color='green'>Disponível</font>";
		}
		strr += '<b>'+(x+1)+'-<b>' +strStatus +"<br>";
	}

	$('divDebugObjetos').innerHTML = strr;
	t=setTimeout("fnDebugAjax()",100)

}

/**
INCLUINDO A BIBLIOTECA PROTOTYPE
**/
document.write("<script src='"+URL_JS+"prototype.js'></script>");


function fnAjaxSendHtml(arquivo_php,param_php,func_retorno_js,param_js){
	
	var cont = getEmptyObjectKey();
	if(obj_aj = arrObject[cont]){
		if(obj_aj && (obj_aj.readyState == 0 || obj_aj.readyState == 0)) {
			DisplayLoading();
			obj_aj.open("POST", URL_ACTION + arquivo_php, true);
			obj_aj.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=iso-8859-1");

			obj_aj.onreadystatechange = function (){
				DisplayLoading();
				if(arrObject[cont].readyState == 4){
					if(arrObject[cont].status != 200){
						if(count_ajax_erros < 50){
							count_ajax_erros++;
							fnAjaxSendHtml(arquivo_php,param_php,func_retorno_js,param_js);
						}else{
							count_ajax_erros++;
							alert('Problemas com o arquivo no servidor , favor tente novamente dentro de alguns minutos.');
						}
					}

					var retorno = getObjectResponseHtml(cont);
					
					eval(func_retorno_js+"(retorno"+param_js+")");
				}
			}
			obj_aj.send('&ajax=1'+param_php);
		}
	}
}

function fnAjaxSend(arquivo_php,param_php,func_retorno_js,param_js){
	var cont = getEmptyObjectKey();
	if(obj_aj = arrObject[cont]){
		if(obj_aj && (obj_aj.readyState == 0 || obj_aj.readyState == 0)) {
			DisplayLoading(true);
			obj_aj.open("POST", URL_ACTION + arquivo_php, true);
			obj_aj.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=iso-8859-1");			
			obj_aj.onreadystatechange = function (){
				
				if(arrObject[cont].readyState == 4){
					if(arrObject[cont].status != 200){
						if(count_ajax_erros < 50){
							count_ajax_erros++;
							fnAjaxSend(arquivo_php,param_php,func_retorno_js,param_js);
						}else{
							count_ajax_erros++;
							alert('Problemas com o arquivo no servidor , favor tente novamente dentro de alguns minutos.');
						}
					}

					var retorno = getObjectResponseArray(cont);
					
					eval(func_retorno_js+"(retorno"+param_js+")");
					DisplayLoading(false);
				}
			}
			obj_aj.send('&ajax=1'+param_php);
		}
	}
}

function getError(retorno){
	if(retorno && retorno.length && retorno['ajaxError']){
		alert(retorno['ajaxError']['msg']);
	}
}

function url_decode(str) {
	if(str !== false && str!= "" && str){
		var n, strCode, strDecode = "";
		str = str.replace(/\+/g," ");
		for (n = 0; n < str.length; n++) {
			if (str.charAt(n) == "%") {
				strCode = str.charAt(n + 1) + str.charAt(n + 2);
				strDecode += String.fromCharCode(parseInt(strCode, 16));
				n += 2;
			} else {
				strDecode += str.charAt(n);
			}
		}
		return strDecode;
	}else{
		return "";
	}
}
function setScriptAjax(texto, obj){
	var ini, pos_src, fim, codigo;
	var objScript = null;
	ini = texto.indexOf("<script", 0)
	while (ini!=-1){
		var objScript = document.createElement("script");
		//Busca se tem algum src a partir do inicio do script
		pos_src = texto.indexOf(" src", ini)
		ini = texto.indexOf(">", ini) + 1;

		//Verifica se este e um bloco de script ou include para um arquivo de scripts
		if (pos_src < ini && pos_src >=0){//Se encontrou um "src" dentro da tag script, esta e um include de um arquivo script
			//Marca como sendo o inicio do nome do arquivo para depois do src
			ini = pos_src + 4;
			//Procura pelo ponto do nome da extencao do arquivo e marca para depois dele
			fim = texto.indexOf(".", ini)+4;
			//Pega o nome do arquivo
			codigo = texto.substring(ini,fim);
			//Elimina do nome do arquivo os caracteres que possam ter sido pegos por engano
			codigo = codigo.replace("=","").replace(" ","").replace("\"","").replace("\"","").replace("\"","").replace("\"","").replace(">","");
			// Adiciona o arquivo de script ao objeto que sera adicionado ao documento
			objScript.src = codigo;
		}else{//Se nao encontrou um "src" dentro da tag script, esta e um bloco de codigo script
			// Procura o final do script
			fim = texto.indexOf("</script>", ini);
			// Extrai apenas o script
			codigo = texto.substring(ini,fim);
			// Adiciona o bloco de script ao objeto que sera adicionado ao documento
			objScript.text = codigo;
		}
		//Adiciona o script ao documento
		obj.appendChild(objScript);
		// Procura a proxima tag de <script
		ini = texto.indexOf("<script", fim);

		//Limpa o objeto de script
		objScript = null;
	}
}
function url_encode(str) {
    var hex_chars = "0123456789ABCDEF";
    var noEncode = /^([a-zA-Z0-9\_\-\.])$/;
    var n, strCode, hex1, hex2, strEncode = "";

    for(n = 0; n < str.length; n++) {
        if (noEncode.test(str.charAt(n))) {
            strEncode += str.charAt(n);
        } else {
            strCode = str.charCodeAt(n);
            hex1 = hex_chars.charAt(Math.floor(strCode / 16));
            hex2 = hex_chars.charAt(strCode % 16);
            strEncode += "%" + (hex1 + hex2);
        }
    }
    return strEncode;
}
function zeraOptions(objSelect){
	objSelect.options.length = 1;

	//objSelect.options[0]= new Option('-- Selecione --', '');
	
}

function arrayToOptions(array , objSelect , arrayFieldNameToOptionValue , arrayFieldNameToOptionText , selectedValue){
	objSelect.options.length = 1;
	for(var x = 0 ; x < array.length; x++){
			eval('objSelect.options[x+1]= new Option(array[x].' + arrayFieldNameToOptionText + ', array[x].' + arrayFieldNameToOptionValue +')');
			if(selectedValue && objSelect.options[x+1].value == selectedValue){
				objSelect.options[x+1].selected = true;
			}

	}
	//objSelect.focus();
}

function arrayToOptionsZero(array , objSelect , arrayFieldNameToOptionValue , arrayFieldNameToOptionText , selectedValue){
	objSelect.options.length = 0;
	for(var x = 0 ; x < array.length; x++){
			eval('objSelect.options[x]= new Option(array[x].' + arrayFieldNameToOptionText + ', array[x].' + arrayFieldNameToOptionValue +')');
			if(selectedValue && objSelect.options[x].value == selectedValue){
				objSelect.options[x].selected = true;
			}

	}
	//objSelect.focus();
}

function DisplayLoading(){
	var bool = false;
	for(x=0;x<arrObject.length;x++){
		if(arrObject[x].readyState == 1 || arrObject[x].readyState == 2 || arrObject[x].readyState == 3){
			bool = true;
		}
	}
	if(bool){
		if($('DivDefaultLoading')){
		}else{			
			var divblock=document.createElement("div")
			divblock.setAttribute("id", "DivDefaultLoading")
			divblock.innerHTML = '<div class="loading-indicator"><img src="'+URL_IMG+'loading.gif" style="width:16px;height:16px;" align="absmiddle">&#160;Carregando...</div> </div>';
			$('spnTudo').appendChild(divblock);
			
		}
	}else{
		try{
			$('spnTudo').removeChild($('DivDefaultLoading'));
		}catch(e){}
	}
}

function fnAuxLoading(){
	DisplayLoading();
	t=setTimeout("fnAuxLoading()",1000);
}
fnAuxLoading();
<!-- FIM RETORNO DE AJAX -->
//LZW-compress a stringRNO DE AJAX -->
//LZW-compress a string
