// JavaScript Document
params = getParams();
function getParams() {
	var idx = document.URL.indexOf('?');
	var params = new Array();
	if (idx != -1) {
		var pairs = document.URL.substring(idx+1, document.URL.length).split('&');
		for (var i=0; i<pairs.length; i++) {
			nameVal = pairs[i].split('=');
			params[nameVal[0]] = nameVal[1];
	   }
	}
	return params;
}
 
function activeButton(id){
	document.getElementById(id+'Active').style.display="block"
	document.getElementById(id).style.display="none";
}

function desactiveButton(id){
	document.getElementById(id+'Active').style.display="none"
	document.getElementById(id).style.display="block";
}


function mostra_div(id) {
  //tem que tratar browsers diferentemente

  if (document.getElementById) { // DOM3 = IE5, NS6
    document.getElementById(id).style.display = 'block';
  }
  else {
    if (document.layers) { // Netscape 4
      document.id.display = 'block';
    }
    else { // IE 4
      document.all.id.style.display = 'block';
    }
  }
}

function esconde_div(id) {
  //tem que tratar browsers diferentemente

  if (document.getElementById) { // DOM3 = IE5, NS6
    document.getElementById(id).style.display = 'none';
  }
  else {
    if (document.layers) { // Netscape 4
      document.id.display = 'none';
    }
    else { // IE 4
      document.all.id.style.display = 'none';
    }
  }
}

function closePop(div){
	esconde_div(div);				  
	esconde_div('divMain');				  
}

function openDropDown(div){
	if(document.getElementById(div).style.display == "none"){
		document.getElementById(div).style.display = 'block';	
	}else{
		document.getElementById(div).style.display = 'none';	
	}
}

 
function retira_acentos(palavra) {  
	com_acento = "áàãâäéèêëíìîïóòõôöúùûüçÁÀÃÂÄÉÈÊËÍÌÎÏÓÒÕÖÔÚÙÛÜÇ";  
	sem_acento = "aaaaaeeeeiiiiooooouuuucAAAAAEEEEIIIIOOOOOUUUUC";  
	nova="";  
	for(i=0;i<palavra.length;i++) {  
		if (com_acento.search(palavra.substr(i,1))>=0) {  
		nova+=sem_acento.substr(com_acento.search(palavra.substr(i,1)),1);  
		}  
		else {  
			nova+=palavra.substr(i,1);  
		}  
	}  
	return nova;  
}  


function getPageSize(){
	if (typeof window.innerWidth != 'undefined')
	 {
		  viewportwidth = window.offsetWidth ,
		  viewportheight = window.offsetHeight
	 }
	 
	// IE6 in standards compliant mode (i.e. with a valid doctype as the first line in the document)
	
	 else if (typeof document.documentElement != 'undefined'
		 && typeof document.documentElement.clientWidth !=
		 'undefined' && document.documentElement.clientWidth != 0)
	 {
		   viewportwidth = document.documentElement.clientWidth,
		   viewportheight = document.documentElement.clientHeight
	 }
	 
	 // older versions of IE
	 
	 else
	 {
		   viewportwidth = document.getElementsByTagName('body')[0].clientWidth,
		   viewportheight = document.getElementsByTagName('body')[0].clientHeight
	 }
	
	pageSize =  new Array();
	pageSize[0] = viewportwidth;
	pageSize[1] = viewportheight;
	return pageSize;
}

function mouseCoords(event){
	coords = new Array();
	coords['x'] = event.clientX;
	coords['y'] = event.clientY;
	return coords;
}


function detectBrowse(){
	var browse = null;
	var version = null;
	if (/Firefox[\/\s](\d+\.\d+)/.test(navigator.userAgent)){ //test for Firefox/x.x or Firefox x.x (ignoring remaining digits);
		var ffversion=new Number(RegExp.$1) // capture x.x portion and store as a number
		browse = "FF";
		version = ffversion;
	}

	if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)){ //test for MSIE x.x;
		var ieversion=new Number(RegExp.$1) // capture x.x portion and store as a number
		browse = "IE";
		version = ieversion;
	}

	//Note: userAgent in Opera9.24 WinXP returns: Opera/9.24 (Windows NT 5.1; U; en)
	//         userAgent in Opera 8.5 (identified as IE) returns: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1) Opera 8.50 [en]
	//         userAgent in Opera 8.5 (identified as Opera) returns: Opera/8.50 (Windows NT 5.1; U) [en]
	if (/Opera[\/\s](\d+\.\d+)/.test(navigator.userAgent)){ //test for Opera/x.x or Opera x.x (ignoring remaining decimal places);
		var oprversion=new Number(RegExp.$1) // capture x.x portion and store as a number
		browse = "OP";
		version = oprversion;
	}
	browseConfig = new Array();
	browseConfig['browse'] = browse;
	browseConfig['version'] = version;
	return browseConfig
}


function checkMail(mail){
    var er = new RegExp(/^[A-Za-z0-9_\-\.]+@[A-Za-z0-9_\-\.]{2,}\.[A-Za-z0-9]{2,}(\.[A-Za-z0-9])?/);
    if(typeof(mail) == "string"){
        if(er.test(mail)){ return true; }
    }else if(typeof(mail) == "object"){
        if(er.test(mail.value)){
                    return true;
                }
    }else{
        return false;
        }
}


function mascara(o,f){
    v_obj=o
    v_fun=f
    setTimeout("execmascara()",1)
}

function execmascara(){
    v_obj.value=v_fun(v_obj.value)
}


function cnpj2(v){
	v=v.replace(/\D/g,"") //Remove tudo o que não é dígito
	v=v.replace(/^(\d{2})(\d)/,"$1.$2") //Coloca ponto entre o segundo e o terceiro dígitos
	v=v.replace(/^(\d{2})\.(\d{3})(\d)/,"$1.$2.$3") //Coloca ponto entre o quinto e o sexto dígitos
	v=v.replace(/\.(\d{3})(\d)/,".$1/$2") //Coloca uma barra entre o oitavo e o nono dígitos
	v=v.replace(/(\d{4})(\d)/,"$1-$2") //Coloca um hífen depois do bloco de quatro dígitos
	return v
}

function numero(v){
	v=v.replace(/\D/g,"") //Remove tudo o que não é dígito
	return v
}

//valida o CNPJ digitado
function ValidarCNPJ(ObjCnpj){
    var cnpj = ObjCnpj.value;
    var valida = new Array(6,5,4,3,2,9,8,7,6,5,4,3,2);
    var dig1= new Number;
    var dig2= new Number;
    
    exp = /\.|\-|\//g
    cnpj = cnpj.toString().replace( exp, "" );
    var digito = new Number(eval(cnpj.charAt(12)+cnpj.charAt(13)));
        
    for(i = 0; i<valida.length; i++){
        dig1 += (i>0? (cnpj.charAt(i-1)*valida[i]):0);    
        dig2 += cnpj.charAt(i)*valida[i];    
    }
    dig1 = (((dig1%11)<2)? 0:(11-(dig1%11)));
    dig2 = (((dig2%11)<2)? 0:(11-(dig2%11)));
    
    if(((dig1*10)+dig2) != digito)    
        return false;
        
	return true;
}

function CheckPage(page){
	try {
		pageTracker._trackPageview('/site/requisicoes/'+page,CheckPageReturn); 
		enviaDados('site/requisicoes/'+page,CheckPageReturn);	
	} 
	catch(err)
	{}
}
function CheckPageReturn(){}

function getUF(){
	enviaDados("index.php/controlLocalidade/getUF", popularComboUF);	
	esconde_div('comboCidadeContent');	
	esconde_div('comboCidadeTemplate');

}

function popularComboUF(){
	mostra_div('comboUFContent');	
	mostra_div('comboUFTemplate');
	if (linkReq.readyState == '4') {
		var divContent = document.getElementById("comboUFContent");
		var resXML = linkReq.responseXML.getElementsByTagName("uf");
		
		divContent.innerHTML = "";
		for(i = 0; i < resXML.length; i++) {
			divContent.innerHTML += "<a id=\"comboProduto\" href=\"javascript:populaCampoUF('"+getCDATA(resXML[i].getElementsByTagName("COD_ESTADO"))+"','"+getCDATA(resXML[i].getElementsByTagName("NOM_ESTADO"))+"');getCidades('"+getCDATA(resXML[i].getElementsByTagName("COD_ESTADO"))+"')\">" +  
											getCDATA(resXML[i].getElementsByTagName("NOM_ESTADO")) + 
											"</a><br/>";
		}
		
		document.getElementById("comboCidadeContent").innerHTML = "";
	}
}

function populaCampoUF(sUF,sNomeUF){
	document.getElementById('uf').value = sUF;
	document.getElementById('comboUFTitle').innerHTML = sNomeUF;
	esconde_div('comboUFContent');	
	esconde_div('comboUFTemplate');
}

function getCidades(sUF){
	if(sUF == ''){
		esconde_div('comboUFContent');	
		esconde_div('comboUFTemplate');
	
		mostra_div('comboCidadeContent');	
		mostra_div('comboCidadeTemplate');
	}else{
		mostra_div('imgLoading');	
		enviaDados("index.php/controlLocalidade/index/"+sUF, popularComboCidade);
	}
}

function popularComboCidade(){
	esconde_div('comboUFContent');	
	esconde_div('comboUFTemplate');

	mostra_div('comboCidadeContent');	
	mostra_div('comboCidadeTemplate');
	document.getElementById('comboCidadeTitle').innerHTML = 'Carregando..';

	if (linkReq.readyState == '4') {
		document.getElementById('comboCidadeTitle').innerHTML = 'UF';

		var divContent = document.getElementById("comboCidadeContent");
		var resXML = linkReq.responseXML.getElementsByTagName("cidade");

		divContent.innerHTML = "";
		for(i = 0; i < resXML.length; i++) {
			divContent.innerHTML += "<a id=\"comboProduto\" href=\"javascript:populaCampoCidade('"+getCDATA(resXML[i].getElementsByTagName("NOM_CIDADE")).replace("'","#")+"');\">" +  
											getCDATA(resXML[i].getElementsByTagName("NOM_CIDADE")) + 
											"</a><br/>";
		}
		esconde_div('imgLoading');	
	}
}

function populaCampoCidade(sCidade){
	document.getElementById('cidade').value = sCidade;
	document.getElementById('comboCidadeTitle').innerHTML = sCidade;

	esconde_div('comboCidadeContent');	
	esconde_div('comboCidadeTemplate');
}


function populaComboGrupo() {
	var divContent = document.getElementById("divGrupos");

	if(divContent.style.display == 'none'){
		divContent.style.display = 'block';
	}else{
		divContent.style.display = 'none';
	}
}


function fechaBanner(){
	document.getElementById("divBanner").style.display = 'none';
}

function fechaPop(){
	document.getElementById("divPop").style.display = 'none';
}

 function thickboxResize() {  
     var boundHeight = 500; // minimum height  
     var boundWidth = 690; // minimum width  
   
     var viewportWidth = (self.innerWidth || (document.documentElement.clientWidth || (document.body.clientWidth || 0)))  
     var viewportHeight =(self.innerHeight || (document.documentElement.clientHeight || (document.body.clientHeight || 0)))  
   
     $('a.thickbox').each(function(){  
         var text = $(this).attr("href");  
         if ( viewportHeight < boundHeight  || viewportHeight < boundWidth)  
         {  
             // adjust the height  
             text = text.replace(/height=[0-9]*/,'height=' + Math.round(viewportHeight * .8));  
             // adjust the width  
             text = text.replace(/width=[0-9]*/,'width=' + Math.round(viewportWidth * .8));  
         }  
         else   
         {  
             // constrain the height by defined bounds  
             text = text.replace(/height=[0-9]*/,'height=' + boundHeight);  
             // constrain the width by defined bounds  
             text = text.replace(/width=[0-9]*/,'width=' + boundWidth);  
         }  
   
         $(this).attr("href", text);  
     });  
 }  
 
 
 
function f_clientWidth() {
	return f_filterResults (
		window.innerWidth ? window.innerWidth : 0,
		document.documentElement ? document.documentElement.clientWidth : 0,
		document.body ? document.body.clientWidth : 0
	);
}
function f_clientHeight() {
	return f_filterResults (
		window.innerHeight ? window.innerHeight : 0,
		document.documentElement ? document.documentElement.clientHeight : 0,
		document.body ? document.body.clientHeight : 0
	);
}
function f_scrollLeft() {
	return f_filterResults (
		window.pageXOffset ? window.pageXOffset : 0,
		document.documentElement ? document.documentElement.scrollLeft : 0,
		document.body ? document.body.scrollLeft : 0
	);
}
function f_scrollTop() {
	return f_filterResults (
		window.pageYOffset ? window.pageYOffset : 0,
		document.documentElement ? document.documentElement.scrollTop : 0,
		document.body ? document.body.scrollTop : 0
	);
}
function f_filterResults(n_win, n_docel, n_body) {
	var n_result = n_win ? n_win : 0;
	if (n_docel && (!n_result || (n_result > n_docel)))
		n_result = n_docel;
	return n_body && (!n_result || (n_result > n_body)) ? n_body : n_result;
}

function fixedDiv(posDiv,minTop,divId,divFixed){
	if(!divFixed){
		$(window).scroll(function () { 
			positionScreen = f_scrollTop();
			if(positionScreen > (posDiv -  minTop)){
				$("#"+divId).css( "top", ((positionScreen) + minTop)+'px');
			}else{
				$("#"+divId).css( "top", (posDiv)+'px');
			}
		});
	}else{
		$(document).ready(function(){
			$("#"+divId).css("position","fixed");									   
		});	
	}
}

