var req;
$(document).ready(function(){
    $("#cep").mask("99.999-999");
});
    function Trim(strTexto)
        {
            return strTexto.replace(/^\s+|\s+$/g, '');
        }

    function IsCEP(strCEP, blnVazio)
        {
            var objER = /^[0-9]{2}\.[0-9]{3}-[0-9]{3}$/;
            strCEP = Trim(strCEP)
            if(strCEP.length > 0)
                {
                    if(objER.test(strCEP)){
                        return true;
                    }else{
                        alert(strCEP+' CEP Inválido.');
                        return false;
                    }
                }
            else
                return blnVazio;
        }
function rrn(){
    if((document.getElementById('estad_uf').value!="PR")){
            if(document.getElementById('cep').value!=''){
                if((IsCEP(document.getElementById('cep').value))&&(document.getElementById('cep').value!='')){calcular();}
            }else{
                alert("Preencha seu CEP.");
            }
    }else{
        if(document.getElementById('cidad_tipo').value=='2'){
            if(document.getElementById('cep').value!=''){
                if((IsCEP(document.getElementById('cep').value))&&(document.getElementById('cep').value!='')){calcular();}
            }else{
                alert("Preencha seu CEP.");
            }
        }
    }
}
function loadXMLDoc( url )
{
    req = null;
    // Procura por um objeto nativo (Mozilla/Safari)
    if (window.XMLHttpRequest) {
        req = new XMLHttpRequest();
        req.onreadystatechange = processReqChange;
        req.open("GET", url, true);
        req.send(null);
    // Procura por uma versao ActiveX (IE)
    } else if (window.ActiveXObject) {
        req = new ActiveXObject("Microsoft.XMLHTTP");
        if (req) {
            req.onreadystatechange = processReqChange;
            req.open("GET", url, true);
            req.send();
        }
    }
}

function processReqChange()
{
    var nada = '';
    var texto = '';
    var i = 0;
    // apenas quando o estado for "completado"
    if (req.readyState == 4) {
        // apenas se o servidor retornar "OK"
        if ( req.status == 200 ) {
            
            str = req.responseText;
            x = str.search("ftipo_id");
            
            if(x!="-1"){
            magicJson = eval("(" + req.responseText + ")");

            for ( i=1; i<=8; i++ ) {
			
				// FRETE SEDEX 10 INDISPONÍVEL
				if ( i != i ) { //if ( i == 8 ) {
			
					texto = 'Não disponível' ;
				
				}else{
				
					try {
						texto = magicJson.ftipo_id[0][i][0]['valor'] ;
					} catch ( nada ) { 
						texto = 'Não disponível' ;
					}
				
				}

                try {
                    aux = eval (document.getElementById('ftipo'+i) );
                    aux.innerHTML = texto ;
                } catch ( nada ) {
                    // nada
                }

            }

            return true;
        }else{
            if(
                (str!="")
                &&
                (str!="    ")
            ){
                    alert(str);
                    document.getElementById('ctba').style.display = 'none';
                    document.getElementById('geral').style.display = 'none';    
            }
        }   
        } else {
            alert("Houve um problema ao obter os dados:\n" + req.statusText);
            return false;
        }
    }
}


function magicRequest( pagina )
{

    for ( i=1; i<=8; i++ ) {

        try {
            aux = eval (document.getElementById('ftipo'+i) );
            aux.innerHTML = '<img src="img/loading.gif" />';
        } catch ( nada ) {
            // nada
        }

    }

    pagina = pagina + '?' + document.f1.estad_uf.value ;
    pagina = pagina + '|' + document.f1.cidad_tipo.value ;
    pagina = pagina + '|' + document.f1.peso.value ;
    pagina = pagina + '|' ; //+ document.f1.ftipo_id.value ; //pagina = pagina + '|' + document.f1.ftipo_id.value ;
    pagina = pagina + '|' + document.f1.embalagem.value ;
    pagina = pagina + '|' + document.f1.peso_cubado.value ;
    pagina = pagina + '|' + document.f1.valor_seguro.value ;
    pagina = pagina + '|' + document.f1.cep.value ;
    pagina = pagina + '|' + document.f1.valor.value ;

    loadXMLDoc( pagina + '|' + Math.random() );
}

function changeUf ( obj )
{

    if ( obj.value == 'PR' )
    {
        
        document.getElementById('div_cidad_tipo').innerHTML = "<img src='img/cal_02.gif' align='middle' alt='Localização' title='Localização' /><select style='margin-left:7px;' name='cidad_tipo' id='cidad_tipo' style='width: 120px;' onChange=\"calcular();\"><option value='' selected='selected'></option><option value='1' >Curitiba e São José dos Pinhais</option><option value='3'>Região Metropolitana</option><option value='2'>Interior</option></select>";
        document.getElementById('div_cep').style.display = 'none';
        document.getElementById('div_cidad_tipo').style.display = '';
        
        //calcular()
    }
    else if ( obj.value )
    {
        document.getElementById('div_cidad_tipo').innerHTML = "<select name='cidad_tipo' id='cidad_tipo' style='width: 120px;' onChange=\"calcular();\"><option value='' selected='selected'></option><option value='1' >Capital</option><option value='2'>Interior</option></select><input type='button' value='Calcular' onClick=\"calcular();\" />";
        document.getElementById('div_cep').style.display = 'inline';
        document.getElementById('div_cidad_tipo').style.display = 'none';
        //calcular()
    }
}

function printf(valor,casas,pont) {
var n=valor;
var toStr=n.toString();
if(toStr.indexOf(".") == -1) {
 return valor;
}
else {
 var div=toStr.split(".");
 var fcent=div[1].substring(0,casas);
 return div[0]+pont+fcent;
}
}

function calcular ()
{
    var aux;
    var pos;
    
    if ( !document.f1.estad_uf.value )
    {
        alert ( 'Selecione seu estado!' );
        document.f1.estad_uf.focus();
    } 
    else
    {
        if ( document.f1.estad_uf.value == 'PR' && document.f1.cidad_tipo.value == '1' )
        {
            document.getElementById('geral').style.display = 'none';
            document.getElementById('ctba').style.display = 'block';
            //document.getElementById('img_calculador').src = 'img/titul_calcu_ctba.gif';
            //alert ( 10.00 + '-' + parseFloat(document.f1.soma.value) +'-'+ parseFloat(document.f1.valor_s_curitiba.value) ) ;
            aux = 10.00 + parseFloat(document.f1.soma.value) + parseFloat(document.f1.valor_s_curitiba.value) ;
            //alert(aux);
            aux = new String(aux);
            pos = aux.indexOf(".");
            tam = aux.length;
            if ( pos == -1 ) aux = aux + ",00";
            else
            {
                if ( (tam - pos) == 1 ) aux = aux + ",00";
                if ( (tam - pos) == 2 ) aux = aux + "0";
            }
            // corrigindo bug de soma no javascript;
            if (aux.length > 5 ) 
            {
                aux = aux.substring(0,5);
            }
            document.getElementById('ftipo_ctba').innerHTML = 'R$ ' + aux.replace(".", ",") ;
            document.getElementById('div_cep').style.display = 'none';
        }
        else if ( document.f1.estad_uf.value == 'PR' && document.f1.cidad_tipo.value == '3'  )
        {
            document.getElementById('geral').style.display = 'none';
            document.getElementById('ctba').style.display = 'block';
            //document.getElementById('img_calculador').src = 'img/titul_calcu_ctba.gif';
            aux = 12.50 + parseFloat(document.f1.soma.value) + parseFloat(document.f1.valor_s_curitiba.value) ;
            aux = new String(aux);
            pos = aux.indexOf(".");
            tam = aux.length;
            if ( pos == -1 ) aux = aux + ",00";
            else
            {
                if ( (tam - pos) == 1 ) aux = aux + ",00";
                if ( (tam - pos) == 2 ) aux = aux + "0";
            }
            // corrigindo bug de soma no javascript;
            if (aux.length > 5 ) 
            {
                aux = aux.substring(0,5);
            }
            document.getElementById('ftipo_ctba').innerHTML = 'R$ ' + aux.replace(".", ",") ;
            document.getElementById('div_cep').style.display = 'none';
        }else if ( document.f1.estad_uf.value == 'PR' && document.f1.cidad_tipo.value == '2' && document.f1.cep.value == ''  ) {
            document.getElementById('geral').style.display = 'none';
            document.getElementById('div_cep').style.display = 'inline';
            document.getElementById('ctba').style.display = 'none';
        } else if ( document.f1.estad_uf.value == 'PR' && document.f1.cidad_tipo.value == ''  )
        { 
            document.getElementById('cep').value='';
            document.getElementById('ctba').style.display = 'none';
            document.getElementById('geral').style.display = 'none';            
        }else {
            document.getElementById('ctba').style.display = 'none';
            document.getElementById('geral').style.display = 'block';
            //document.getElementById('img_calculador').src = 'img/titul_calcu.gif';
            
        }
        magicRequest('ajaxCalcula.php');
    }
   
}

function funcaoVoltar ( param )
{

    /*alert ( window.opener ) ;
    if ( window.opener ) {
        window.opener.focus();
    } else {
        location.href = param ;
    }*/

    try {
        window.opener.focus();
    } catch ( e ) {
        location.href = param ;
        //alert ( param );
    }
}


