﻿function isin_array(a, valor) {
    if (!isArray(a)) {
        return -1;
    }
    for (i = 0; i < a.length; i++) {
        if (a[i] == valor) {
            return i;
        }
    }
    return -1;
}

function is_array(variavel) {
    return isArray(variavel);
}

function isFunction(a) {
    return typeof a == "function";
}

function isDecimal(number) { // positive or negative decimal
	if(!number) return false;
	var decimalRegExp = new RegExp(/^-?(0|[1-9]{1}\d{0,})(\.(\d{1}\d{0,}))?$/);
	return decimalRegExp.test(number);
}

function isObject(a) {
    return a && typeof a == "object" || isFunction(a);
}

function isArray(a) {
    return isObject(a) && a.constructor == Array;
}

function isString(a) {
    return typeof a == "string";
}

function isset(varname) {
    if (typeof window[varname] != "undefined") {
        return true;
    } else {
        return false;
    }
}

function setIZClass(obj, valor) {
    if (!document.all) {
        obj.setAttribute("class", valor);
    } else {
        obj.setAttribute("className", valor);
    }
}

function setIZStyle(obj, nomes, valores) {
    if (!obj) {
        return;
    }
    if (isString(nomes)) {
        if (!document.all) {
            obj.setAttribute("style", nomes);
            return;
        }
        tmp = nomes.split(";");
        if (isArray(tmp) && !window.opera) {
            for (i = 0; i < tmp.length; i++) {
                if (tmp[i] == undefined || tmp[i] == "") {
                    continue;
                }
                var tmpa = tmp[i].split(":");
                if (isArray(tmpa)) {
                    if (tmpa[0] != undefined &&
                        tmpa[1] != undefined &&
                        tmpa[0] != "" && tmpa[1] != "") {
                        obj.style.setAttribute(tmpa[0].replace(/ /, ""), tmpa[1].replace(/ /, ""));
                    }
                }
            }
        } else {
            obj.setAttribute("style", nomes);
            obj.style.cssTex = nomes;
        }
        return;
    }
    if (nomes == null || valores == null) {
        return;
    }
    if (!document.all) {
        var estilo = "";
        for (var i = 0; i < nomes.length; i++) {
            estilo = estilo + nomes[i] + ":" + valores[i] + "; ";
        }
        obj.setAttribute("style", estilo);
    } else {
        for (var i = 0; i < nomes.length; i++) {
            obj.style.setAttribute(nomes[i], valores[i]);
        }
    }
}


//
// getPageScroll()
// Returns array with x,y page scroll values.
// Core code from - quirksmode.com
//
function getPageScroll(){

	var xScroll, yScroll;

	if (self.pageYOffset) {
		yScroll = self.pageYOffset;
		xScroll = self.pageXOffset;
	} else if (document.documentElement && document.documentElement.scrollTop){	 // Explorer 6 Strict
		yScroll = document.documentElement.scrollTop;
		xScroll = document.documentElement.scrollLeft;
	} else if (document.body) {// all other Explorers
		yScroll = document.body.scrollTop;
		xScroll = document.body.scrollLeft;	
	}

	arrayPageScroll = new Array(xScroll,yScroll);
	return arrayPageScroll;
}

// -----------------------------------------------------------------------------------

//
// getPageSize()
// Returns array with page width, height and window width, height
// Core code from - quirksmode.com
// Edit for Firefox by pHaez
//
function getPageSize(){
	
	var xScroll, yScroll;
	
	if (window.innerHeight && window.scrollMaxY) {	
		xScroll = window.innerWidth + window.scrollMaxX;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}
	
	var windowWidth, windowHeight;
	
//	console.log(self.innerWidth);
//	console.log(document.documentElement.clientWidth);

	if (self.innerHeight) {	// all except Explorer
		if(document.documentElement.clientWidth){
			windowWidth = document.documentElement.clientWidth; 
		} else {
			windowWidth = self.innerWidth;
		}
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}	
	
	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else { 
		pageHeight = yScroll;
	}

//	console.log("xScroll " + xScroll)
//	console.log("windowWidth " + windowWidth)

	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){	
		pageWidth = xScroll;		
	} else {
		pageWidth = windowWidth;
	}
//	console.log("pageWidth " + pageWidth)

	arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight) 
	return arrayPageSize;
}

function getElementSize(Elem) {
	if(document.getElementById) {
		var elem = document.getElementById(Elem);
	} else if (document.all){
		var elem = document.all[Elem];
	}
	if (elem.style.pixelWidth) { 
		wPos = elem.style.pixelWidth;
		hPos = elem.style.pixelHeight;
	} else {
		wPos = elem.offsetWidth;
		hPos = elem.offsetHeight;
	}
	arrayElemSize = new Array(wPos,hPos);
	return arrayElemSize;
}


function getElementLeft(Elem) {
	var elem;
	if(document.getElementById) {
		var elem = document.getElementById(Elem);
	} else if (document.all){
		var elem = document.all[Elem];
	}
	xPos = elem.offsetLeft;
	tempEl = elem.offsetParent;
	while (tempEl != null) {
		xPos += tempEl.offsetLeft;
		tempEl = tempEl.offsetParent;
	}
	return xPos;
}


function getElementTop(Elem) {
	if(document.getElementById) {	
		var elem = document.getElementById(Elem);
	} else if (document.all) {
		var elem = document.all[Elem];
	}
	yPos = elem.offsetTop;
	tempEl = elem.offsetParent;
	while (tempEl != null) {
		yPos += tempEl.offsetTop;
		tempEl = tempEl.offsetParent;
	}
	return yPos;
}



function getElementWidth(Elem) {
	var elem;
	if(document.getElementById) {
		var elem = document.getElementById(Elem);
	} else if (document.all){
		var elem = document.all[Elem];
	}
	
	width = elem.offsetWidth;
	
	return width;
}



function multiMudaImg(img_src, img_name, idx) {
	image = document.getElementById("imgMulti");
	image.src = "/images/ajax-loader.gif";
	image.title = "A carregar...";
	
	if ( window.preloadImage === undefined)
		preloadImage = new Image(); 
	preloadImage.src = img_src;
	preloadImage.title = img_name;

	preloadImage.onload = function(){
		image.src = preloadImage.src;
		image.title = preloadImage.title;
	}

	//Obtém os links do menu
	var menu  = document.getElementById("multiBotoes");
	var links = menu.getElementsByTagName("span");

	//Limpa as classes do menu
	for(var i=0; i<links.length; i++)
		links[i].className = "";

	//Marca o selecionado
	links[idx].className = "selected";
}


function URLEncode( texto ) {
	// The Javascript escape and unescape functions do not correspond
	// with what browsers actually do...
	var SAFECHARS = "0123456789" +					// Numeric
					"ABCDEFGHIJKLMNOPQRSTUVWXYZ" +	// Alphabetic
					"abcdefghijklmnopqrstuvwxyz" +
					"-_.!~*'()";					// RFC2396 Mark characters
	var HEX = "0123456789ABCDEF";

	var plaintext = texto;
	var encoded = "";
	for (var i = 0; i < plaintext.length; i++ ) {
		var ch = plaintext.charAt(i);
	    if (ch == " ") {
		    encoded += "+";				// x-www-urlencoded, rather than %20
		} else if (SAFECHARS.indexOf(ch) != -1) {
		    encoded += ch;
		} else {
		    var charCode = ch.charCodeAt(0);
			if (charCode > 255) {
			    alert( "Unicode Character '" 
                        + ch 
                        + "' cannot be encoded using standard URL encoding.\n" +
				          "(URL encoding only supports 8-bit characters.)\n" +
						  "A space (+) will be substituted." );
				encoded += "+";
			} else {
				encoded += "%";
				encoded += HEX.charAt((charCode >> 4) & 0xF);
				encoded += HEX.charAt(charCode & 0xF);
			}
		}
	} // for

	return encoded;
};

function URLDecode( texto ) {
   // Replace + with ' '
   // Replace %xx with equivalent character
   // Put [ERROR] in output if %xx is invalid.
   var HEXCHARS = "0123456789ABCDEFabcdef"; 
   var encoded = texto;
   var plaintext = "";
   var i = 0;
   while (i < encoded.length) {
       var ch = encoded.charAt(i);
	   if (ch == "+") {
	       plaintext += " ";
		   i++;
	   } else if (ch == "%") {
			if (i < (encoded.length-2) 
					&& HEXCHARS.indexOf(encoded.charAt(i+1)) != -1 
					&& HEXCHARS.indexOf(encoded.charAt(i+2)) != -1 ) {
				plaintext += unescape( encoded.substr(i,3) );
				i += 3;
			} else {
				alert( 'Bad escape combination near ...' + encoded.substr(i) );
				plaintext += "%[ERROR]";
				i++;
			}
		} else {
		   plaintext += ch;
		   i++;
		}
	} // while
   return plaintext;
};

function htmlspecialchars_decode(string, quote_style) {
    // http://kevin.vanzonneveld.net
    // +   original by: Mirek Slugen
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Mateusz "loonquawl" Zalega
    // +      input by: ReverseSyntax
    // +      input by: Slawomir Kaniecki
    // +      input by: Scott Cariss
    // +      input by: Francois
    // +   bugfixed by: Onno Marsman
    // +    revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // -    depends on: get_html_translation_table
    // *     example 1: htmlspecialchars_decode("<p>this -&gt; &quot;</p>", 'ENT_NOQUOTES');
    // *     returns 1: '<p>this -> &quot;</p>'
 
    var histogram = {}, symbol = '', tmp_str = '', entity = '';
    tmp_str = string.toString();
    
    if (false === (histogram = get_html_translation_table('HTML_SPECIALCHARS', quote_style))) {
        return false;
    }
 
    // &amp; must be the last character when decoding!
    delete(histogram['&']);
    histogram['&'] = '&amp;';
 
    for (symbol in histogram) {
        entity = histogram[symbol];
        tmp_str = tmp_str.split(entity).join(symbol);
    }
    
    return tmp_str;
}

function get_html_translation_table(table, quote_style) {  
	// Returns the internal translation table used by htmlspecialchars and htmlentities    
	//   
	// version: 901.714  
	// discuss at: http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_get_html_translation_table  

	// +   original by: Philip Peterson  
	// +    revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)  
	// +   bugfixed by: noname  
	// %          note: It has been decided that we're not going to add global  
	// %          note: dependencies to php.js. Meaning the constants are not  
	// %          note: real constants, but strings instead. integers are also supported if someone  
	// %          note: chooses to create the constants themselves.  
	// %          note: Table from http://www.the-art-of-web.com/html/character-codes/  
	// *     example 1: get_html_translation_table('HTML_SPECIALCHARS');  
	// *     returns 1: {'"': '&quot;', '&': '&amp;', '<': '&lt;', '>': '&gt;'}  

	var entities = {}, histogram = {}, decimal = 0, symbol = '';  
	var constMappingTable = {}, constMappingQuoteStyle = {};  
	var useTable = {}, useQuoteStyle = {};  

	useTable      = (table ? table.toUpperCase() : 'HTML_SPECIALCHARS');  
	useQuoteStyle = (quote_style ? quote_style.toUpperCase() : 'ENT_COMPAT');  

	// Translate arguments  
	constMappingTable[0]      = 'HTML_SPECIALCHARS';  
	constMappingTable[1]      = 'HTML_ENTITIES';  
	constMappingQuoteStyle[0] = 'ENT_NOQUOTES';  
	constMappingQuoteStyle[2] = 'ENT_COMPAT';  
	constMappingQuoteStyle[3] = 'ENT_QUOTES';  

	// Map numbers to strings for compatibilty with PHP constants  
	if (!isNaN(useTable)) {  
		useTable = constMappingTable[useTable];  
	}  
	if (!isNaN(useQuoteStyle)) {  
		useQuoteStyle = constMappingQuoteStyle[useQuoteStyle];  
	}  

	if (useQuoteStyle != 'ENT_NOQUOTES') {  
		entities['34'] = '&quot;';  
	}  

	if (useQuoteStyle == 'ENT_QUOTES') {
		entities['39'] = '&#039;';
	}

	if (useTable == 'HTML_SPECIALCHARS') {
		// ascii decimals for better compatibility
		entities['38'] = '&amp;';
		entities['60'] = '&lt;';
		entities['62'] = '&gt;';
	} else if (useTable == 'HTML_ENTITIES') {
		// ascii decimals for better compatibility
		entities['38']  = '&amp;';  
		entities['60']  = '&lt;';  
		entities['62']  = '&gt;';  
		entities['160'] = '&nbsp;';  
		entities['161'] = '&iexcl;';  
		entities['162'] = '&cent;';  
		entities['163'] = '&pound;';  
		entities['164'] = '&curren;';  
		entities['165'] = '&yen;';  
		entities['166'] = '&brvbar;';  
		entities['167'] = '&sect;';  
		entities['168'] = '&uml;';  
		entities['169'] = '&copy;';  
		entities['170'] = '&ordf;';  
		entities['171'] = '&laquo;';  
		entities['172'] = '&not;';  
		entities['173'] = '&shy;';  
		entities['174'] = '&reg;';  
		entities['175'] = '&macr;';  
		entities['176'] = '&deg;';  
		entities['177'] = '&plusmn;';  
		entities['178'] = '&sup2;';  
		entities['179'] = '&sup3;';  
		entities['180'] = '&acute;';  
		entities['181'] = '&micro;';  
		entities['182'] = '&para;';  
		entities['183'] = '&middot;';  
		entities['184'] = '&cedil;';  
		entities['185'] = '&sup1;';  
		entities['186'] = '&ordm;';  
		entities['187'] = '&raquo;';  
		entities['188'] = '&frac14;';  
		entities['189'] = '&frac12;';  
		entities['190'] = '&frac34;';  
		entities['191'] = '&iquest;';  
		entities['192'] = '&Agrave;';  
		entities['193'] = '&Aacute;';  
		entities['194'] = '&Acirc;';  
		entities['195'] = '&Atilde;';  
		entities['196'] = '&Auml;';  
		entities['197'] = '&Aring;';  
		entities['198'] = '&AElig;';  
		entities['199'] = '&Ccedil;';  
		entities['200'] = '&Egrave;';  
		entities['201'] = '&Eacute;';  
		entities['202'] = '&Ecirc;';  
		entities['203'] = '&Euml;';  
		entities['204'] = '&Igrave;';  
		entities['205'] = '&Iacute;';  
		entities['206'] = '&Icirc;';  
		entities['207'] = '&Iuml;';  
		entities['208'] = '&ETH;';  
		entities['209'] = '&Ntilde;';  
		entities['210'] = '&Ograve;';  
		entities['211'] = '&Oacute;';  
		entities['212'] = '&Ocirc;';  
		entities['213'] = '&Otilde;';  
		entities['214'] = '&Ouml;';  
		entities['215'] = '&times;';  
		entities['216'] = '&Oslash;';  
		entities['217'] = '&Ugrave;';  
		entities['218'] = '&Uacute;';  
		entities['219'] = '&Ucirc;';  
		entities['220'] = '&Uuml;';  
		entities['221'] = '&Yacute;';  
		entities['222'] = '&THORN;';  
		entities['223'] = '&szlig;';  
		entities['224'] = '&agrave;';  
		entities['225'] = '&aacute;';  
		entities['226'] = '&acirc;';  
		entities['227'] = '&atilde;';  
		entities['228'] = '&auml;';  
		entities['229'] = '&aring;';  
		entities['230'] = '&aelig;';  
		entities['231'] = '&ccedil;';  
		entities['232'] = '&egrave;';  
		entities['233'] = '&eacute;';  
		entities['234'] = '&ecirc;';  
		entities['235'] = '&euml;';  
		entities['236'] = '&igrave;';  
		entities['237'] = '&iacute;';  
		entities['238'] = '&icirc;';  
		entities['239'] = '&iuml;';  
		entities['240'] = '&eth;';  
		entities['241'] = '&ntilde;';  
		entities['242'] = '&ograve;';  
		entities['243'] = '&oacute;';  
		entities['244'] = '&ocirc;';  
		entities['245'] = '&otilde;';  
		entities['246'] = '&ouml;';  
		entities['247'] = '&divide;';  
		entities['248'] = '&oslash;';  
		entities['249'] = '&ugrave;';  
		entities['250'] = '&uacute;';  
		entities['251'] = '&ucirc;';  
		entities['252'] = '&uuml;';  
		entities['253'] = '&yacute;';  
		entities['254'] = '&thorn;';  
		entities['255'] = '&yuml;';  
	} else {  
		throw Error("Table: "+useTable+' not supported');  
		return false;  
	}  

	// ascii decimals to real symbols  
	for (decimal in entities) {  
		symbol = String.fromCharCode(decimal)  
		histogram[symbol] = entities[decimal];  
	}

	return histogram;  
} 

function escapeHTML (str){
   var div = document.createElement('div');
   var text = document.createTextNode(str);
   div.appendChild(text);
   return div.innerHTML;
}


function selectMenu(mID){
	clearSelectMenu();
	
	makeSelectMenu(mID);
}

function makeSelectMenu(mID){
	//Obtém os links do menu
	var menu  = document.getElementById("mainMenu");
	if (menu === null) return;
	
	var links = menu.getElementsByTagName("a");

    //Atribui o evento
    for(var i=0; i<links.length; i++) {
		//Obtém o número quebrando a url
		n = links[i].getAttribute("href").replace(/.*=/,"");

		if ( n == mID) {  // Adiciona a className  'selected'
			links[i].className  = links[i].className + " selected";
		}
	}
}

function clearSelectMenu(){
    //Obtém os links do menu
    var menu = document.getElementById("mainMenu");
	if (menu === null) return;
	
    var links = menu.getElementsByTagName("a");

    for(var i=0; i<links.length; i++) {
		links[i].className = links[i].className.replace(/selected/g, "");
	}
}

function getParentLI (myElem) {
	parentElem = myElem.parentNode.parentNode.parentNode;
	
	if (parentElem.tagName == "LI") {
		var parentElemLinks = parentElem.getElementsByTagName("a");
		return parentElemLinks[0].getAttribute("href").replace(/.*=/,"");
	} else {
		return false;
	}
}


function selectSubMenu(mID){
    //Obtém os links do menu
    var subMenu = document.getElementById("submenu");
    var links = subMenu.getElementsByTagName("a");

    for(var i=0; i<links.length; i++) {
		links[i].className = links[i].className.replace(/selected/g, "");
		
		//Obtém o número quebrando a url
		n = links[i].getAttribute("href").replace(/.*=/,"");

		if ( n == mID) {  // Adiciona a className  'selected'
			links[i].className  = links[i].className + " selected";
		}
	}
}

function get(key, url){
	if(arguments.length < 2) url = location.href;
	if(arguments.length > 0 && key != ""){
		if(key == "#"){
			var regex = new RegExp("[#]([^$]*)");
		} else if(key == "?"){
			var regex = new RegExp("[?]([^#$]*)");
		} else {
			var regex = new RegExp("[?&]"+key+"=([^&#]*)");
		}
		var results = regex.exec(url);
		return (results == null )? "" : results[1];
	} else {
		url = url.split("?");
		var results = {};
		if(url.length > 1){
			url = url[1].split("#");
			if(url.length > 1) results["hash"] = url[1];
			url[0].split("&").each(function(item,index){
				item = item.split("=");
				results[item[0]] = item[1];
			});
		}
		return results;
	}  
}  


function searchFocus(type) {
	obj = document.getElementById('searchq');
	if (type) {
		if (obj.value == "Procurar...")
			obj.value = "";
	} else {
		if (obj.value == "")
			obj.value = "Procurar...";
	}
}

function getstyle(obj, cAttribute) {
    if (obj.currentStyle) {
        this.getstyle = function (obj, cAttribute) {return obj.currentStyle[cAttribute];};
    } else {
        this.getstyle = function (obj, cAttribute) {return document.defaultView.getComputedStyle(obj, null)[cAttribute];};
    }
    return getstyle(obj, cAttribute);
}


function isEmpty(StringToCheck) {
	var re = /^\s{1,}$/g; //match any white space including space, tab, form-feed, etc.
	if ((StringToCheck.length==0) || (StringToCheck=='') || ((StringToCheck.search(re)) > -1)) {
		return true;
	} else {
		return false;
	}

}

function isEMailAddr(email){
	var result = false;
	var theStr = new String(email);
	var index = theStr.indexOf("@");
	if (index > 0){
		var pindex = theStr.indexOf(".",index);
		if ((pindex > index+1) && (theStr.length > pindex+1))
			result = true;
	}
	return result;
}

function getElementsByClass(theClass, node) {
    var classElements = [];
    var i;
    if ( node == null ) {
    	node = document
    }
    if (node.getElementsByClassName) {
    	var tempCollection = node.getElementsByClassName(theClass);
        for (i = 0; i < tempCollection.length ; i++) {
    		classElements.push(tempCollection[i])
    	}
    }
    else {
    	var els = node.getElementsByTagName("*");
    	var elsLen = els.length;
    	var pattern = new RegExp("(^|\\s)"+theClass+"(\\s|$)");
    	for (i = 0; i < elsLen; i++) {
    		if ( pattern.test(els[i].className) ) {
    			classElements.push(els[i]);
    		}
    	}
    }
    return classElements;
}

function getElementsByRel( className, nodeName, rootnode ) {
	if(!rootnode) rootnode = document;
	if(!rootnode.getElementsByTagName) return;
	var result = [], tag = nodeName||'*', node, seek, i;
	var rightClass = new RegExp( '(^| )'+ className +'( |$)' );
	seek = rootnode.getElementsByTagName( tag );
	for( i=0; i<seek.length; i++ )
		if( rightClass.test( (node = seek[i]).rel ) )
			result.push( seek[i] );
	return result;
}

