Tree = function(arg_arrTree,arg_idx) {
	this.idSecao 				= '';
	this.Nom_Secao				= '';
	this.idSecaoPai 			= '';
	this.Ind_Indisponivel	 	= '';
	this.Cod_Secao	 			= '';
	this.Dsc_ImagemCorpo	 	= '';
	this.Ind_ImportacaoArquivo	= '';
	this.arrTree =  arg_arrTree;
	this.arr_secoes = new Array();
	this.arrIndex = (arg_idx+'').split(',');
	this.url = "";
	this.urlBase = "";
	this.arrTreeResult = new Array();
	this.paramUL = '';
	
	this.init = function() {
		this.arrIndex[2] = this.arrIndex[2]?this.arrIndex[2]:'parentid';
		this.url = (this.arrIndex[0]+'').toLowerCase()+"/[IDPAI]";
		this.url += this.arrIndex[2]?"/"+(this.arrIndex[2]+'').toLowerCase()+"/[IDFILHO]":'';
		
	}
	this.consulta = function() {
		return this.arrTree;
	}
	this.groupById = function () {
		$arr = this.consulta();
		$result = array();
		for($k in $arr) {
				$v = $arr[$k];
				$result[$v[this.arrIndex[0]]] = $v;
			
		}
		unset($arr);
		return $result;
	}
	this.getTree = function() {
		$arr = this.groupById();
		$result = this.get_array_parent($arr);
		for($k in $arr) {
			if(isNaN($k)) break;
			$v = $arr[$k];
			$arr[$k]['lineage'] 		= $result[$k][3];
			$arr[$k]['nivel'] 			= $result[$k][4];
			$arr[$k]['idnivel0']		= $result[$k][5];
			$arr[$k]['possuifilhos']	= $result[$k][6];
			//alert($result[$k][6])
		}
		unset($result);
		this.arrTreeResult = $arr;
		return this.arrTreeResult;
	}
	this.get_array_parent = function($rs,$initLevel,$endLevel) {
		var $rs = !$rs?'':$rs;
		var $initLevel = !$initLevel?0:$initLevel;
		var $endLevel = !$endLevel?'':$endLevel;
		
		$arr_lineage = array();
		$rsSecoes = $rs;
		if(sizeof($rsSecoes)) {
			for($k in $rsSecoes) {
				$v = $rsSecoes[$k];
				this.getDados("",$v);
				
					$lineage = "";
					$idSecao_aux	= str_repeat("0",6-strlen(this.idSecao)) + this.idSecao;
					
					
					
					if(this.idSecaoPai+""!="") {
						$idSecaoPai_aux = str_repeat("0",6-strlen(this.idSecaoPai)) + '' + this.idSecaoPai;
					} else {
						$idSecaoPai_aux = "";
					}
					$lineage = ($idSecaoPai_aux+""!="")?$idSecaoPai_aux + "|" + $idSecao_aux:$idSecao_aux;
					
					
					if(isset($arr_lineage[this.idSecaoPai])) {
						$lineage = ($arr_lineage[this.idSecaoPai]+""!="")?$arr_lineage[this.idSecaoPai] + "|" + $idSecao_aux:$idSecao_aux;
					}
					$arr_lineage[this.idSecao] = $lineage;
					
					this.arr_secoes[this.idSecao+''] = array();
					this.arr_secoes[this.idSecao+''][0] = this.idSecao;
			        this.arr_secoes[this.idSecao+''][1] = this.Nom_Secao;
			        this.arr_secoes[this.idSecao+''][2] = this.idSecaoPai;
			        this.arr_secoes[this.idSecao+''][3] = $lineage;
			        this.arr_secoes[this.idSecao+''][7] = this.Dsc_ImagemCorpo;
					
					
					$size = (parseInt(sizeof(explode('|',$lineage))))-1;
					this.arr_secoes[this.idSecao+''][4] = $size;
			}
		}

		for($key in this.arr_secoes) {
			if(isNaN($key)) break;
			$value = this.arr_secoes[$key];
			$idSecao 	= $value[0]; 
			$Nom_Secao 	= $value[1];
			$idSecaoPai = $value[2];
			$LineAge 	= $value[3];
			$Nivel 		= $value[4];
			
			$arr_lineAge = explode("|",$LineAge);
			
			this.arr_secoes[$idSecao+''][5] = parseInt($arr_lineAge[0]);
			
			$bo_posui_filhos = this.verifica_filhos($idSecao); 
			this.arr_secoes[$idSecao+''][6] = $bo_posui_filhos;
		}
		
	    if($initLevel+''!="0" || $endLevel+''!="") {
	    	$arr_filhos_aux = array();
			for($key in this.arr_secoes) {
				$value = this.arr_secoes[$key];
				$idSecao 		= $value[0]; 
				$Nom_Secao 		= $value[1];
				$idSecaoPai 	= $value[2];
				$LineAge 		= $value[3];
				$Nivel 			= $value[4];
				$idnivel0		= $value[5];
				$possuifilhos	= $value[6];
				
				
				$endLevel_aux = ($endLevel+''=="")?$Nivel:$endLevel;
				if($Nivel>=$initLevel && $Nivel<=$endLevel_aux) {
			        $arr_filhos_aux[$idSecao][0] = $idSecao;
			        $arr_filhos_aux[$idSecao][1] = $Nom_Secao;
			        $arr_filhos_aux[$idSecao][2] = $idSecaoPai;
			        $arr_filhos_aux[$idSecao][3] = $LineAge;
			        $arr_filhos_aux[$idSecao][4] = $Nivel;
			        $arr_filhos_aux[$idSecao][5] = $idnivel0;
			        $arr_filhos_aux[$idSecao][6] = $possuifilhos;
				}
			}
			this.arr_secoes = $arr_filhos_aux;
	    }
	    
	    return this.arr_secoes;
	}
	
	this.verifica_filhos = function($idSecao) {
		var $idSecao = !$idSecao?'':$idSecao;
		$result = 0;
		for($key in this.arr_secoes) {
			$value = this.arr_secoes[$key];
			$idSecaoPai = $value[2];
			if($idSecao+''==$idSecaoPai+'') {
				$result = 1;
				break;
			}
		}
		return $result;
	}
	this.strip_lineage = function($lineage) {
		var $lineage = !$lineage?'':$lineage;
		var $arr = array();
		if($lineage+""!="") {
			$arr = explode("|",$lineage);
			$tam = sizeof($arr);
			for($iLoop=0;$iLoop<$tam;$iLoop++) {
				$arr[$iLoop] = $arr[$iLoop]*1; 
			}
			
		}
		return $arr;
	}	
	this.get_pais = function($idSecao,$cs) {
		var $idSecao = !$idSecao?'':$idSecao;
		var $cs = !$cs?0:$cs;
		$arr_pais = array();
		if($idSecao+""!="") {
			// $arr = this.arrTreeResult;
			$lineage = this.arrTreeResult[$idSecao+""]?this.arrTreeResult[$idSecao+""]['lineage']:'';
			
			$arr_pais = this.strip_lineage($lineage);
			
		}
		return $arr_pais;
	}
	this.getDados = function($idSecao,$rs) {
		var $idSecao = !$idSecao?'':$idSecao;
		var $rs = !$rs?'':$rs;
		
		if($idSecao+""!="" || is_array($rs)) {
			
			this.arrTree = $rs; 
			

			this.idSecao 				= $rs[this.arrIndex[0]];
			this.Nom_Secao				= $rs[this.arrIndex[1]];
			this.idSecaoPai 			= $rs[this.arrIndex[2]]?$rs[this.arrIndex[2]]:'';
			this.Ind_Indisponivel	 	= $rs["Ind_Indisponivel"]?$rs["Ind_Indisponivel"]:'';
			this.Cod_Secao	 			= $rs["Cod_Secao"]?$rs["Cod_Secao"]:'';
			this.Dsc_ImagemCorpo	 	= $rs["Dsc_ImagemCorpo"]?$rs["Dsc_ImagemCorpo"]:'';
			this.Ind_ImportacaoArquivo	= $rs["Ind_ImportacaoArquivo"]?$rs["Ind_ImportacaoArquivo"]:'';
			
			unset($rsSecoes);
		}
	}
	
	this.getHTML = function() {
		var strHTML = this.getHTML2()+'';
		strHTML = strHTML.replace('<ul>',"<ul "+ this.paramUL +">\n");
		return strHTML;
	}
	
	this.getCOMBO = function() {
		var strHTML = this.getCOMBO2()+'';
		//strHTML = strHTML.replace('<ul>',"<ul "+ this.paramUL +">\n");
		return strHTML;
		
	}
	
	this.getCOMBO2 = function(iCurID, iDepth, initLevel, endLevel) {
		var iCurID 		= !iCurID?'':iCurID;
		var iDepth 		= !iDepth?0:iDepth;
		var initLevel 	= !initLevel?0:initLevel;
		var endLevel 	= !endLevel?'':endLevel;
		
		var aCategories = this.arrTreeResult;
		
		var CategoryID = this.arrIndex[0]+'';
		var Name = this.arrIndex[1]+'';
		var ParentID= this.arrIndex[2]?this.arrIndex[2]+'':'';
		var Lineage = 'lineage';
		var Level= 'nivel';
		
		
		
		
		
		var endLevel_aux = (endLevel+""=="")?iDepth:endLevel;
		var iNumRecords = $(aCategories).size();
		
		var strHTML = "\n";
		var pos = 0;
		for(var i in aCategories) {
			var key = i;
			if(is_object(aCategories[i])) {
						aCategories[i][ParentID] = aCategories[i][ParentID] ? aCategories[i][ParentID] : '';
						valor = aCategories[i];
						var vParentID = valor[ParentID]+''!='null' || valor[ParentID]?valor[ParentID]:'';
						//alert(vParentID + " = " + iCurID)
						if(vParentID+"" == iCurID+"") {
							var Link = this.urlBase + this.url+'';
							var strLabel = valor[Name];
							if(Link+''!='') {
								if(valor[ParentID]+""!="") {
								}
								Link = Link.replace('[IDPAI]',valor[CategoryID]);
								Link = Link.replace('[IDFILHO]',valor[ParentID]);
								var str_selected = "";
								strLabel = "<a href=\"" + Link + "\" " + str_selected + ">" + strLabel + "</a>";
							}
							
							if(iDepth>=initLevel && iDepth<=endLevel_aux) {
								strHTML += "<option value='"+valor[CategoryID]+"' rel=\""+valor[ParentID]+"\" class='nivel_" + iDepth + " pos_" + pos + "'>"+strLabel;
								strHTML += this.getCOMBO2(valor[CategoryID], iDepth+1, initLevel, endLevel);
								strHTML += "\n</option>\n";
								strHTML += "";
								
										
								pos++;
							} else {
								strHTML += this.getCOMBO2(valor[CategoryID], iDepth+1, initLevel, endLevel);
								strHTML += "";
							}
						}
			}
		}
		
		strHTML += "\n";
		// strHTML += "\n</ul>";
		// strHTML = this.replaceSubstring(strHTML,'<ul></ul>','');
		// strHTML = this.replaceSubstring(strHTML,'<ul><ul>','<ul>');
		// strHTML = this.replaceSubstring(strHTML,'</ul></ul>','</ul>');
		

		//var strHTML = $(objUL).html();
		return strHTML;
		
	}

	this.getHTML2 = function(iCurID, iDepth, initLevel, endLevel) {
		var iCurID 		= !iCurID?'':iCurID;
		var iDepth 		= !iDepth?0:iDepth;
		var initLevel 	= !initLevel?0:initLevel;
		var endLevel 	= !endLevel?'':endLevel;
		
		var aCategories = this.arrTreeResult;
		
		var CategoryID = this.arrIndex[0]+'';
		var Name = this.arrIndex[1]+'';
		var ParentID= this.arrIndex[2]?this.arrIndex[2]+'':'';
		var Lineage = 'lineage';
		var Level= 'nivel';
		
		
		
		
		
		var endLevel_aux = (endLevel+""=="")?iDepth:endLevel;
		var iNumRecords = $(aCategories).size();
		
		var strHTML = "<ul>\n";
		var pos = 0;
		for(var i in aCategories) {
			var key = i;
			if(is_object(aCategories[i])) {
						aCategories[i][ParentID] = aCategories[i][ParentID] ? aCategories[i][ParentID] : '';
						valor = aCategories[i];
						var vParentID = valor[ParentID]+''!='null' || valor[ParentID]?valor[ParentID]:'';
						//alert(vParentID + " = " + iCurID)
						if(vParentID+"" == iCurID+"") {
							var Link = this.urlBase + this.url+'';
							var strLabel = valor[Name];
							if(Link+''!='') {
								if(valor[ParentID]+""!="") {
								}
								Link = Link.replace('[IDPAI]',valor[CategoryID]);
								Link = Link.replace('[IDFILHO]',valor[ParentID]);
								var str_selected = "";
								strLabel = "<a href=\"" + Link + "\" " + str_selected + ">" + strLabel + "</a>";
							}
							
							if(iDepth>=initLevel && iDepth<=endLevel_aux) {
								strHTML += "<li rel=\""+valor[CategoryID]+"\" class='nivel_" + iDepth + " pos_" + pos + "'>"+strLabel;
								strHTML += this.getHTML2(valor[CategoryID], iDepth+1, initLevel, endLevel);
								strHTML += "\n</li>\n";
								strHTML += "";
								
										
								pos++;
							} else {
								strHTML += this.getHTML2(valor[CategoryID], iDepth+1, initLevel, endLevel);
								strHTML += "";
							}
						}
			}
		}
		
		strHTML += "\n</ul>";
		strHTML = this.replaceSubstring(strHTML,'<ul></ul>','');
		strHTML = this.replaceSubstring(strHTML,'<ul><ul>','<ul>');
		strHTML = this.replaceSubstring(strHTML,'</ul></ul>','</ul>');
		
		var objUL = document.createElement('ul');
		$(objUL).append(strHTML);
		$(objUL).find('ul').each(function(){
			if(!$(this).find('li:eq(0)').size()) {
				$(this).remove();
			}
			$(this).removeAttr('id');
			$(this).removeAttr('class');
		});
		
		var strHTML = $(objUL).html();
		return strHTML;
		
	}
	
	this.replaceSubstring = function(inputString, fromString, toString) {
	   // Goes through the inputString and replaces every occurrence of fromString with toString
	   var temp = inputString;
	   if (fromString == "") {
		  return inputString;
	   }
	   if (toString.indexOf(fromString) == -1) { // If the string being replaced is not a part of the replacement string (normal situation)
		  while (temp.indexOf(fromString) != -1) {
			 var toTheLeft = temp.substring(0, temp.indexOf(fromString));
			 var toTheRight = temp.substring(temp.indexOf(fromString)+fromString.length, temp.length);
			 temp = toTheLeft + toString + toTheRight;
		  }
	   } else { // String being replaced is part of replacement string (like "+" being replaced with "++") - prevent an infinite loop
		  var midStrings = new Array("~", "`", "_", "^", "#");
		  var midStringLen = 1;
		  var midString = "";
		  // Find a string that doesn't exist in the inputString to be used
		  // as an "inbetween" string
		  while (midString == "") {
			 for (var i=0; i < midStrings.length; i++) {
				var tempMidString = "";
				for (var j=0; j < midStringLen; j++) { tempMidString += midStrings[i]; }
				if (fromString.indexOf(tempMidString) == -1) {
				   midString = tempMidString;
				   i = midStrings.length + 1;
				}
			 }
		  } // Keep on going until we build an "inbetween" string that doesn't exist
		  // Now go through and do two replaces - first, replace the "fromString" with the "inbetween" string
		  while (temp.indexOf(fromString) != -1) {
			 var toTheLeft = temp.substring(0, temp.indexOf(fromString));
			 var toTheRight = temp.substring(temp.indexOf(fromString)+fromString.length, temp.length);
			 temp = toTheLeft + midString + toTheRight;
		  }
		  // Next, replace the "inbetween" string with the "toString"
		  while (temp.indexOf(midString) != -1) {
			 var toTheLeft = temp.substring(0, temp.indexOf(midString));
			 var toTheRight = temp.substring(temp.indexOf(midString)+midString.length, temp.length);
			 temp = toTheLeft + toString + toTheRight;
		  }
	   } // Ends the check to see if the string being replaced is part of the replacement string or not
	   return temp; // Send the updated string back to the user
	} // Ends the "replaceSubstring" function
	
	this.init();

}
function sizeof(arg) { return $(arg).size(); }
function array(arg) { return new Array(); }
function is_array(arg) { return (typeof arg == 'array' || typeof arg == 'object' ||  arg.constructor == Array); }
function is_object(arg) { return ( typeof arg == 'object' ); }

function isFunction(arg) { return (typeof arg == 'function'); }
function unset(arg) { arg = null; }
function str_repeat(str, i) { if (isNaN(i) || i <= 0) return ""; return str + str_repeat(str, i-1); }
function strlen(arg) { return $(arg).length; }
function isset(arg) { return arg?true:false; }
function explode(str,arg) { var arg = arg+''; return arg.split(str); }
