/**
* Variável para armazenar o caminho absoluto da url
*/
var rootUrl = document.location.href;
rootUrl = rootUrl.substr(0,rootUrl.indexOf('/',8));

/**
* Exibir SWF
*/
function showFlash(swf, width, height,flashAlternative){
		monta_swf = "";
		if ((navigator.appName == "Microsoft Internet Explorer" &&  navigator.appVersion.indexOf("Mac") == -1 &&   navigator.appVersion.indexOf("3.1") == -1) || (navigator.plugins && navigator.plugins["Shockwave Flash"]) || navigator.plugins["Shockwave Flash 2.0"]){
			monta_swf += "<object classid=\"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000\"  width=\""+ width +"\" height=\""+ height +"\" title=\"\">";
			monta_swf += "<param name=\"movie\" value=\""+ swf +"\" />";
			monta_swf += "<param name=\"quality\" value=\"high\" />";
			monta_swf += "<param name=\"menu\" value=\"0\" />";
			monta_swf += "<param name=\"wmode\" value=\"transparent\" />";
			monta_swf += "<embed src=\""+ swf +"\" quality=\"high\" wmode=\"transparent\" type=\"application/x-shockwave-flash\" width=\""+ width +"\" height=\""+ height +"\"></embed>";
			monta_swf += "</object>";
		} else if (flashAlternative!="" && flashAlternative!=null){
			monta_swf += flashAlternative;
		}
		document.write(monta_swf);
}
function showFash(swf, width, height,flashAlternative){ showFlash(swf, width, height,flashAlternative); }

/**
* Abre um popup
* string url, endereço do popup
* int w, largura do popup
* int h, altura do popup
* string conf, configuração do popup: toolbar,location,status,menubar,scrollbars,resizable
* ex:  openPopup('http://www.mkx.com.br','mkx',300,400,'resizable,status');
*/
function openPopup(url,name,w,h,conf) {  
	var winl = (screen.width - w) / 2;
	var wint = ((screen.height - h) / 2);
	newWindow=window.open(url,name,'width='+w+',height='+h+',left='+winl+',top='+wint+','+conf);
	newWindow.window.focus();
}

/**
* Conexão Ajax
*/
function getXmlHttp(){
	try{
		xmlhttp = new XMLHttpRequest();
	}catch(ee){
		try{
			xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
		}catch(e){
			try{
				xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
			}catch(E){
				xmlhttp = false;
			}
		}
	} 
	return xmlhttp;
}

/**
* Monta o combo usando uma consulta no banco via ajax
*/
function setComboAjax(url, target, selectValue, fCallback){
	xmlhttp = getXmlHttp();
	xmlhttp.open("GET", url, true);
	document.getElementById(target).length = 0;
	document.getElementById(target).options[0] = new Option('Loading...','');
	xmlhttp.onreadystatechange=function(){
		if (xmlhttp.readyState==4){
			document.getElementById(target).length = 0;
			document.getElementById(target).options[0] = new Option('Select','');
			if (selectValue==""){
				document.getElementById(target).options[0].selected = true;
			}
			json = eval('(' + xmlhttp.responseText + ')');
			for (i=0; i<json.length; i++){
				document.getElementById(target).options[i+1] = new Option(json[i].name,json[i].id);
				if (selectValue==json[i].id){
					document.getElementById(target).options[i+1].selected = true;
				}
			} 
			if(fCallback!=""){
				getCallback(fCallback);
			}
		}
	}
	xmlhttp.send(null);
}

/**
* Chama a funçao com os parametros informados no fCallback
* @param String fCallback função para chamar após a rotina, exe: testeFuncao,p1,p2 
*/
function getCallback(fCallback){
	if (fCallback!=undefined && fCallback!=""){
		funcoes = fCallback.split(",");
		parametros = "";
		for (i=1;i<funcoes.length;i++){
			parametros += "'"+funcoes[i]+"'";
			if (i<funcoes.length-1) parametros += ",";
		}
		setTimeout(funcoes[0]+"("+parametros+")", 0);				
	}
}

/**
* Troca a tab 
* @param int tab indice da tab de 0 até numero de abas
*/
function goTab(tab, target){
	if (target=="" || target==undefined){
		target = "tab";
	}
	var c = 0;
	var liObj = new Array();
	tabObj = document.getElementById(target);
	for (i=0;i<tabObj.childNodes.length;i++) {
		if (tabObj.childNodes[i].nodeName=="UL"){
			for (j=0;j<tabObj.childNodes[i].childNodes.length;j++){
				  if (tabObj.childNodes[i].childNodes[j].nodeName=="LI"){
					 tabObj.childNodes[i].childNodes[j].attributes["class"].value="";
					 liObj[c] = tabObj.childNodes[i].childNodes[j];
					 c++;
				  }
			}
		}
	}
	n = tabObj.getElementsByTagName('li').length; //numero de tabs
	liObj[tab].attributes["class"].value="current";
	for (i=0;i<n;i++)
		document.getElementById(target+"-"+i).className="invisible tab";
	document.getElementById(target+"-"+tab).className="visible tab";
}

/**
* Aumenta e/ou diminui a fonte da noticia 
* @param 
*/
var tgs = new Array( 'div');
var szs = new Array( 'xx-small','x-small','small','medium','large','x-large','xx-large' );
var startSz = 2;
function ts(trgt,inc) {
	if (!document.getElementById) return
	var d = document,cEl = null,sz = startSz,i,j,cTags;
	
	sz += inc;
	if ( sz < 0 ) sz = 0;
	if ( sz > 4 ) sz = 4;
	startSz = sz;
		
	if ( !( cEl = d.getElementById( trgt ) ) ) cEl = d.getElementsByTagName( trgt )[ 0 ];

	cEl.style.fontSize = szs[ sz ];

	for ( i = 0 ; i < tgs.length ; i++ ) {
		cTags = cEl.getElementsByTagName( tgs[ i ] );
		for ( j = 0 ; j < cTags.length ; j++ ) cTags[ j ].style.fontSize = szs[ sz ];
	}
}

/*
* retorna o numero de elementos dentro de outro elemento (target)
* @param string targetId, ID onde o elemento será adicionado
* @param string elementName, nome do elemento a ser contado
* @param string elementClassName (opcional), conta somente os elementos que tem essa classe, se for null, conta todos
*/
function getNelements(targetId, elementName, elementClassName){
	target = document.getElementById(targetId);
	elements = target.getElementsByTagName(elementName);
	n=0;
	for (i=0;i<elements.length;i++) {
		if (elements[i].className==elementClassName || elementClassName == null){
			n++;
		}
	}
	return n;
}

/*
* Adiciona um novo elemento dentro de outro elemento
* @param string targetId, ID onde o elemento será adicionado
* @param string elementId, ID elemento a ser adicionado
*/
function addElement(targetId,elementId){
	target = document.getElementById(targetId);
	element = document.getElementById(elementId);
	//retorna o número de elementos
	//elementClassName = element.className;
	//elementName = element.nodeName;
	//n = getNelements(targetId, elementName, elementClassName);
	
	//clona o elemento
	var clone = element.cloneNode(true);
	
	//adiciona o elemento clonado	
	target.appendChild(clone);
	
}

/**
* Retorna os elementos com a classe informada
*/
document.getElementsByClassName = function(clsName){
    var retVal = new Array();
    var elements = document.getElementsByTagName("*");
    for(var i = 0;i < elements.length;i++){
        if(elements[i].className.indexOf(" ") >= 0){
            var classes = elements[i].className.split(" ");
            for(var j = 0;j < classes.length;j++){
                if(classes[j] == clsName)
                    retVal.push(elements[i]);
            }
        }
        else if(elements[i].className == clsName)
            retVal.push(elements[i]);
    }
    return retVal;
}

/*
* Tranforma os textares em editor xhtml online
*/
function text2Edit(editorName, w, h, url){
	if (url==null) url = rootUrl + '/scripts/'+editorName+".js";
	if (w==null) w = "100%";
	if (h==null) h = "100%";
	sBasePath = rootUrl + '/libs/javascript/fckeditor/';
	for (i=0;i<editor.length;i++){
		if (editor[i].nodeName=='TEXTAREA'){
			elementName = editor[i].attributes['name'].nodeValue;
			elementValue = editor[i].value;
			oFCKeditor = new FCKeditor(elementName);
			oFCKeditor.BasePath	= sBasePath;
			oFCKeditor.Config["CustomConfigurationsPath"] = url+"?" + ( new Date() * 1 ) ; 
			//oFCKeditor.Value = '<div class="'+editorName+'">\n'+elementValue+'\n</div>';
			oFCKeditor.Width = w ;
			oFCKeditor.Height = h ; 
			oFCKeditor.ReplaceTextarea();
		}
	}
}

/*
* Resolve o problema do target="_blank", pois o xhtml strict não aceita.
*/
function createExternalLinks() {
    if(document.getElementsByTagName) {
        var anchors = document.getElementsByTagName('a');
        for(var i=0; i<anchors.length; i++) {
            var anchor = anchors[i];
            if(anchor.getAttribute("href") && anchor.getAttribute('rel')=='external') { // <-- É necessário inserir rel="externo" no link
                anchor.target = '_blank';
                var title = anchor.title; // <-- Insere este texto no final do Title do link
                anchor.title = title;
            }
        }
    }
}

/**
* Retira o acentos da satring
*/
function stripAccents(str){
	var rExps=[
	{re:/[\xC0-\xC6]/g, ch:'A'},
	{re:/[\xE0-\xE6]/g, ch:'a'},
	{re:/[\xC8-\xCB]/g, ch:'E'},
	{re:/[\xE8-\xEB]/g, ch:'e'},
	{re:/[\xCC-\xCF]/g, ch:'I'},
	{re:/[\xEC-\xEF]/g, ch:'i'},
	{re:/[\xD2-\xD6]/g, ch:'O'},
	{re:/[\xF2-\xF6]/g, ch:'o'},
	{re:/[\xD9-\xDC]/g, ch:'U'},
	{re:/[\xF9-\xFC]/g, ch:'u'},
	{re:/[\xD1]/g, ch:'N'},
	{re:/[\xF1]/g, ch:'n'} ];
	for(var i=0, len=rExps.length; i<len; i++)
			str=str.replace(rExps[i].re, rExps[i].ch);
	return str;
} 

/*
* Substitui a ocorrencia da string token por newtoken
*/
function replaceAll(string, token, newtoken) {
	return (string).split(token).join(newtoken);
}

/*
* Trim
*/
function trim(str){return str.replace(/^\s+|\s+$/g,"");}

/*
* Formata modeda: alert(fmtMoney(1050.6));
*/
fmtMoney = function(n, c, d, t){ //v1.0
    var m = (c = Math.abs(c) + 1 ? c : 2, d = d || ",", t = t || ".",
        /(\d+)(?:(\.\d+)|)/.exec(n + "")), x = m[1].length > 3 ? m[1].length % 3 : 0;
    return (x ? m[1].substr(0, x) + t : "") + m[1].substr(x).replace(/(\d{3})(?=\d)/g,
        "$1" + t) + (c ? d + (+m[2] || 0).toFixed(c).substr(2) : "");
};
