// JavaScript Document
﻿// JavaScript Document

function urlPop(url,w,h){

    window.top.$.fn.colorbox({href:url,width:''+w+'px', height:''+h+'px', iframe:true});

}



function maximo(obj,e,maximo) {

    ma=maximo; //nº máximo de caracteres

    tecla=(document.all)?e.keyCode:e.which;

    if(obj.value.length==ma && tecla!=8)

        return false;

}



function agregaPuntosFijo(val){

    

    //return val;

    var valor = new String(val);

    var largo = valor.length;   

    var retorno = '';

    var cont = 0;

    if(largo > 3){  

        for(i=largo-1; i >= 0; i--){

            if(cont == 3){

                retorno = ','+retorno

                cont = 0

            }

            retorno = valor.charAt(i)+retorno

            cont++;

        }

        return retorno;

    }

    else{

        return val; 

    }

}



function format(input)

{

    var num = input.replace(/\./g,'');

    if(!isNaN(num))

    {

       num = num.toString().split('').reverse().join('').replace(/(?=\d*\.?)(\d{3})/g,'$1.');

       num = num.split('').reverse().join('').replace(/^[\.]/,'');

       return num;

    }

    else

    { 

       //alert("Solo se permiten numeros");

       input = input.replace(/[^\d\.]*/g,'');

       return input;

    }

}







function puntitos(donde,caracter){



    pat = /[\*,\+,\(,\),\?,\,$,\[,\],\^]/

    valor = donde.value

    largo = valor.length

    crtr = true

    if(isNaN(caracter) || pat.test(caracter) == true){

        if (pat.test(caracter)== true ){ 

            caracter = "\ " + caracter

        }

        carcter = new RegExp(caracter,"g")

        valor = valor.replace(carcter,"")

        donde.value = valor

        crtr = false

    }

    else{

        var nums = new Array()

        cont = 0

        for(m=0;m<largo;m++){

            if(valor.charAt(m) == "," || valor.charAt(m) == " ")

                {continue;}

            else{

                nums[cont] = valor.charAt(m)

                cont++

            }

        }

    }

    var cad1="",cad2="",tres=0

    if(largo > 3 && crtr == true){

        for (k=nums.length-1;k>=0;k--){

            cad1 = nums[k]

            cad2 = cad1 + cad2

            tres++

            if((tres%3) == 0){

                if(k!=0){

                    cad2 = "," + cad2

                }

            }

        }

        donde.value = cad2

    }

}

    

function IsNumber(e) {

    tecla = (document.all) ? e.keyCode : e.which;

    if (tecla==8 || tecla==0) return true;

    patron = /\d/; // Solo acepta numeros

    te = String.fromCharCode(tecla);

    return patron.test(te);

}

function IsNumberDec(e) {

    tecla = (document.all) ? e.keyCode : e.which;

    if (tecla==8 || tecla==0) return true;

    patron = /[.,0123456789]/; // Solo acepta numeros

    te = String.fromCharCode(tecla);

    return patron.test(te);

}

function IsRut(e){

    tecla = (document.all) ? e.keyCode : e.which;

    if (tecla==8 || tecla ==0) return true;

    patron = /[-kK0123456789\s-]/;

    te = String.fromCharCode(tecla);

    return patron.test(te)

} 



function getRadioButtonSelectedValue(ctrl) {

    for(i=0;i<ctrl.length;i++)

        if(ctrl[i].checked) return ctrl[i].value;

}

function IsNombre(e){

    tecla = (document.all) ? e.keyCode : e.which;

    if (tecla==8 || tecla==0) return true;

    patron = /[a-zA-ZáéíóúñÁÉÍÓÚÑ\s-]/;

    te = String.fromCharCode(tecla);

    return patron.test(te); 

}



function IsTexto(e){

    tecla = (document.all) ? e.keyCode : e.which;

    if (tecla==8 || tecla==0) return true;

    patron = /[a-zA-Z0-9_.,:;@áéíóúñÁÉÍÓÚÑ\s-]/;

    te = String.fromCharCode(tecla);

    return patron.test(te); 

}



function validarEntero(valor){ 

if (valor == ''){

    valor = true

}else{

    valor = isNaN(valor)

}

return valor

}



function isEmailAddress(stremail){

var s = stremail

var filter=/^[A-Za-z][A-Za-z0-9_.]*@[A-Za-z0-9_]+\.[A-Za-z0-9_.]+[A-za-z]$/;

if (s.length == 0 ) return true;

if (filter.test(s))

return true;

else

return false;

}



function ltrim(s) {

    return s.replace(/^\s+/, "");

}



function rtrim(s) {

    return s.replace(/\s+$/, "");

}



function trim(s) {

    return rtrim(ltrim(s)); 

}



function radioValor(ctrl) {

    for(i=0;i<ctrl.length;i++)

        if(ctrl[i].checked) return ctrl[i].value;

}



function paginador(pag,totalPag){

    for(var i=1; i <= totalPag; i++){

        jQuery('#pag-'+i).hide();   

    }

    jQuery('#pag-'+pag).fadeIn('slow');

}



function filtraPorEstados(valor){

    

    if(valor == 'todos'){

        jQuery('.activo-0').show();

        jQuery('.activo-1').show();

    }

    else if(valor == 'si'){

        jQuery('.activo-0').hide();

        jQuery('.activo-1').show();

    }

    else if(valor == 'no'){

        jQuery('.activo-1').hide();

        jQuery('.activo-0').show();

    }

    

}



function busqueda(){

    var txt_buscado = jQuery('#txtBuscador').val();

    var total_filas = (jQuery('#tt-filas').val() * 1);

    for(var i = 1; i <= total_filas; i++){



        jQuery.ajax({

            type: "POST",

            url: "financiamiento.php",

            data: "tipo=busqueda&texto_buscado="+txt_buscado+"&html_evaluar="+jQuery('#idf-'+i).html(),

            success: function(msg){

                if(msg == 'ok'){

                    jQuery('#idf-'+i).show();

                }

                else{

                    jQuery('#idf-'+i).hide();

                }

            }       

        });

    }

}



function guarda_valor(itemSeleccionado,tipoSeleccion){



    $('#'+tipoSeleccion).val(itemSeleccionado);



    if(tipoSeleccion == 'sel_region'){

        $('#sel-comuna').hide();

        $('.combo-comuna').hide();

        $('#comunas-reg-'+itemSeleccionado).show();

    }   

}



function carga_comunas(reg_id,ident,pag){

    jQuery.ajax({

        type: "POST",

        url: "/operaciones_ajax.php",

        data: "tipo=carga_comuna&reg_id="+reg_id+"&ident="+ident+"&pag="+pag,

        success: function(msg){

            $('#carga-comunas').html(msg);

        }       

    }); 

}

function carga_comunas_perfil(reg_id,tipo_retorno){

    jQuery.ajax({

        type: "POST",

        url: "/operaciones_ajax.php",

        data: "tipo=carga_comunas_perfil&reg_id="+reg_id+"&tipo_retorno="+tipo_retorno,

        success: function(msg){

            $('#carga-comunas-'+tipo_retorno).html(msg);    

            $(document).ready(function(){

                $("#comuna-"+tipo_retorno).cocombobox();

            });

        }       

    }); 

}



function valida_envio_busqueda(frm){

    var msg = '';

    if(getRadioButtonSelectedValue(frm.tipo_vivienda)){

        frm.submit();   

    }

    else{

        $('#mensaje_error').html('Debes seleccionar un tipo de vivienda.');

        //$('#tipo_vivienda').focus();

        return false;   

    }

}



function crea_link(){

    $.ajax({

        type: "POST",

        url: "/operaciones_ajax.php",

        data: "tipo=crea_link",

        success: function(msg){

            if(msg == 'ok'){

                return true;

            }else{

                return false;

            }

        }       

    }); 

}



function cambia_pagina(num_pag){

    var total_pag = ( $('#total_paginas').val() * 1);

    if(num_pag == 'prev'){

        num_pag = ($('#pag_actual').val() * 1 ) - 1;

    }

    if(num_pag == 'sig'){

        num_pag = ($('#pag_actual').val() * 1 ) + 1;

    }

    

    if(num_pag < 1){

        num_pag = 1;    

    }

    if(num_pag > total_pag ){

        num_pag = total_pag;    

    }

    

    $('.paginas').fadeOut('fast',function(){    

        $('#pag-'+num_pag).fadeIn('fast');

        $('#pag_actual').val(num_pag);

        $('.btn-paginas').css('color','#008AED');

        $('#btn-pag-'+num_pag).css('color','#000000');

    });

    

    /*

    $('.paginas').hide('fast',function(){

        $('#pag-'+num_pag).show('slide',{ direction: "right"});

        $('#pag_actual').val(num_pag);

        $('.btn-paginas').css('color','#008AED');

        $('#btn-pag-'+num_pag).css('color','#000000');

    });

    */

    

    

}



function carga_busqueda(id_orden,tipo){

    $.ajax({

        type: "POST",

        url: "/operaciones_ajax.php",

        data: "tipo=carga_busqueda&id_orden="+id_orden+"&tipo_vivienda="+tipo,

        success: function(msg){

            $('.resu-panes').html(msg);

            $('.resu-panes').fadeIn('slow');

        }       

    }); 

}

var busquedaViva = 0;

function busqueda_viva(){

    if (busquedaViva == 0){

        $.ajax({

            type: "POST",

            url: "/operaciones_ajax.php",

            data: $('#buscahogar').serialize()+"&tipo=busqueda_viva",

            success: function(msg){

                    $('.resu-panes').fadeOut('hide',function(){

                    $('.resu-panes').html(msg);

                    $('.resu-panes').fadeIn('slow');

                });

            }       

        }); 

    }

}





function ValidaRut( Objeto )

{

    var tmpstr = "";

    var intlargo = Objeto;

    if (intlargo.length> 0)

    {

        crut = Objeto;

        largo = crut.length;

        if ( largo <2 )

        {   alert('Rut inválido');

            return false;

        }

        for ( i=0; i <crut.length ; i++ )

        if ( crut.charAt(i) != ' ' && crut.charAt(i) != '.' && crut.charAt(i) != '-' )

        {

            tmpstr = tmpstr + crut.charAt(i);

        }

        rut = tmpstr;

        crut=tmpstr;

        largo = crut.length;

    

        if ( largo> 2 )

            rut = crut.substring(0, largo - 1);

        else

            rut = crut.charAt(0);

    

        dv = crut.charAt(largo-1);

    

        if ( rut == null || dv == null )

        return 0;

    

        var dvr = '0';

        suma = 0;

        mul  = 2;

    

        for (i= rut.length-1 ; i>= 0; i--)

        {

            suma = suma + rut.charAt(i) * mul;

            if (mul == 7)

                mul = 2;

            else

                mul++;

        }

    

        res = suma % 11;

        if (res==1)

            dvr = 'k';

        else if (res==0)

            dvr = '0';

        else

        {

            dvi = 11-res;

            dvr = dvi + "";

        }

    

        if ( dvr != dv.toLowerCase() )

        {

            //alert('El Rut Ingreso es Invalido');

            return false;

        }

        return true;

    }

}





/********************************* FUNCIONES DE REGISTRO ************************************************************/

function validarDatos(form)

{

    var rut;

    var largo;

    var enviar;

    enviar = true;

    

    form.txtNombre.value = trim(form.txtNombre.value)

    if ((form.txtNombre.value == "") && enviar == true) 

    { 

      LimpiarBordeCajas();

      document.getElementById("msg_error").innerHTML = '*Por favor complete correctamente el campo nombre.';

      form.txtNombre.style.border = '1px solid #008652';

      form.txtNombre.focus(); 

      enviar = false; 

    }

    

    form.txtPaterno.value = trim(form.txtPaterno.value)

    if ((form.txtPaterno.value == "" || form.txtPaterno.value == "Paterno" ) && enviar == true) 

    { 

      LimpiarBordeCajas();

      document.getElementById("msg_error").innerHTML = '*Por favor complete correctamente el campo apellido paterno.';

      form.txtPaterno.style.border = '1px solid #008652';

      form.txtPaterno.focus();

      enviar = false; 

    }

    

    form.txtMaterno.value = trim(form.txtMaterno.value)

    if ((form.txtMaterno.value == "" || form.txtMaterno.value == "Materno") && enviar == true) 

    { 

      LimpiarBordeCajas();

      document.getElementById("msg_error").innerHTML = '*Por favor complete correctamente el campo apellido materno.';

      form.txtMaterno.style.border = '1px solid #008652';

      form.txtMaterno.focus(); 

      enviar = false; 

    }   

    

    if (form.txtRut.value == "" && enviar == true) 

    { 

       LimpiarBordeCajas();

       document.getElementById("msg_error").innerHTML = '*Por favor complete correctamente el campo rut.';

       form.txtRut.style.border = '1px solid #008652';

       form.txtRut.focus(); 

       enviar = false;

    }    

    else if(enviar == true)

    {    

       rut = form.txtRut.value;

       if (ValidaRut(rut) == false)

       {

          LimpiarBordeCajas();

          document.getElementById("msg_error").innerHTML = '*Por favor ingrese un rut v&aacute;lido.';

          form.txtRut.style.border = '1px solid #008652';

          form.txtRut.focus(); 

          enviar = false; 

       }

    }

        

    form.txtMail.value = trim(form.txtMail.value)

    if (form.txtMail.value != "" && form.txtMail.value != "juan@aconcagua.cl" && enviar == true) 

    { 

       if (form.txtMail.value.indexOf('@', 0) == -1 || form.txtMail.value.indexOf('.', 0) == -1) 

       { 

          LimpiarBordeCajas();

          document.getElementById("msg_error").innerHTML = '*Por favor complete correctamente el e-mail.';

          form.txtMail.style.border = '1px solid #008652';

          form.txtMail.focus(); 

          enviar = false;

       } 

    }

    

    else

    {

       if (enviar == true)

       { 

          LimpiarBordeCajas();

          document.getElementById("msg_error").innerHTML = '*Por favor complete correctamente el e-mail.';

          form.txtMail.style.border = '1px solid #008652';

          form.txtMail.focus(); 

          enviar = false;

       }         

    }

    

    

    if( trim($("#txtCelular").val()) == "" && trim($("#txtFono").val()) == "" && enviar == true ){

          LimpiarBordeCajas();

          document.getElementById("msg_error").innerHTML = '*Por favor ingrese al menos un número telefónico.';

          form.txtCelular.style.border = '1px solid #008652';

          form.txtCelular.focus(); 

          form.txtFono.style.border = '1px solid #008652';

          form.txtFono.focus();

          enviar = false;   

    }

    

   form.txtPassword1.value = trim(form.txtPassword1.value)

   form.txtPassword2.value = trim(form.txtPassword2.value)

   if (form.txtPassword1.value == "" && enviar == true) 

   { 

      LimpiarBordeCajas();

      document.getElementById("msg_error").innerHTML = '*Por favor complete correctamente el campo password.';

      form.txtPassword1.style.border = '1px solid #008652';

      form.txtPassword1.focus(); 

      enviar = false;

   }

   else

   {  

      largo = form.txtPassword1.value;

      if (largo.length < 6  && enviar == true) 

      { 

         

         LimpiarBordeCajas();

         document.getElementById("msg_error").innerHTML = '*La password debe tener al menos 6 caracteres.';

         form.txtPassword1.style.border = '1px solid #008652';

         form.txtPassword1.focus(); 

         form.txtPassword1.select();

         enviar = false;

      }  

   }

   

   if (form.txtPassword2.value == "" && enviar == true) 

   { 

      LimpiarBordeCajas();

      document.getElementById("msg_error").innerHTML = '*Por favor confirme su password.';

      form.txtPassword2.style.border = '1px solid #008652';

      form.txtPassword2.focus(); 

      enviar = false;

   }

   

   if ((form.txtPassword1.value != "" && form.txtPassword2.value != "") && ( enviar == true))

   { 

      if (form.txtPassword1.value != form.txtPassword2.value)

      {

         LimpiarBordeCajas();

         document.getElementById("msg_error").innerHTML = '*Las passwords no deben ser distintas.';

         form.txtPassword2.style.border = '1px solid #008652';

         form.txtPassword2.focus(); 

         form.txtPassword2.select();

         enviar = false;

      }

   }

    

   if(form.chkAcepto.checked == false && enviar == true)

   {

      LimpiarBordeCajas();

      document.getElementById("msg_error").innerHTML = '*Debe leer y aceptar los términos.';

      form.chkAcepto.style.border = '1px solid #008652';

      form.chkAcepto.focus(); 

      enviar = false;

   }

    

    if (enviar==true)

    { 

       form.submit();

    }

} 



function LimpiarBordeCajas()

{

   document.f1.txtNombre.style.border    = '0'  

   document.f1.txtPaterno.style.border   = '0'  

   document.f1.txtMaterno.style.border   = '0'  

   document.f1.txtRut.style.border       = '0'  

   document.f1.txtMail.style.border      = '0'  

   document.f1.txtPassword1.style.border = '0'  

   document.f1.txtPassword2.style.border = '0'

   document.f1.chkAcepto.style.border    = '0'

   document.f1.txtFono.style.border      = '0'

   document.f1.txtCelular.style.border   = '0'

}









/********************************* FUNCIONES FORMULARIO CREDITO ************************************************************/

function validarDatosCredito(form)

{

    var enviar;

    enviar = true;

    

    form.txtMonto.value = trim(form.txtMonto.value)

    if ((form.txtMonto.value == "" || form.txtMonto.value < 1) && enviar == true) 

    { 

      LimpiarBordeCajasCredito();

      document.getElementById("msg_error_credito").innerHTML = '*Por favor ingrese el monto en Dolares $';

      //form.txtMonto.style.border = '1px solid #008652';

      form.txtMonto.focus(); 

      enviar = false; 

    }

    

    form.txtPie.value = trim(form.txtPie.value)

    if ((form.txtPie.value == "") && enviar == true) 

    { 

      LimpiarBordeCajasCredito();

      document.getElementById("msg_error_credito").innerHTML = '*Por favor ingrese el montodel pìe en Dolares $';

      //form.txtPie.style.border = '1px solid #008652';

      form.txtPie.focus(); 

      enviar = false; 

    }

    

    form.txtPlazo.value = trim(form.txtPlazo.value)

    if ((form.txtPlazo.value == "" || form.txtPlazo.value < 1) && enviar == true) 

    { 

      LimpiarBordeCajasCredito();

      document.getElementById("msg_error_credito").innerHTML = '*Por favor ingrese el plazo del crédito.';

      //form.txtPlazo.style.border = '1px solid #008652';

      form.txtPlazo.focus(); 

      enviar = false; 

    }

    

    form.txtTaza.value = trim(form.txtTaza.value)

    if ((form.txtTaza.value == "") && enviar == true) 

    { 

      LimpiarBordeCajasCredito();

      document.getElementById("msg_error_credito").innerHTML = '*Por favor ingrese la tasa de interés.';

      //form.txtTaza.style.border = '1px solid #008652';

      form.txtTaza.focus(); 

      enviar = false; 

    }

    

    if (enviar==true)

    { 

       LimpiarBordeCajasCredito();

       document.getElementById("msg_error_credito").innerHTML = '';

       calcularCredito(form.txtMonto.value, form.txtPie.value, form.txtPlazo.value, form.txtTaza.value, radioValor(form.optSubsidio),radioValor(form.optTipo));

    }

} 



function LimpiarBordeCajasCredito()

{

   document.frmCredito.txtMonto.style.border = '0'

   document.frmCredito.txtPie.style.border   = '0'  

   document.frmCredito.txtPlazo.style.border = '0'  

   document.frmCredito.txtTaza.style.border  = '0'  

}





/********************************* FUNCIONES FORMULARIO DIVIDENDO************************************************************/

function validarDatosDividendo(form)

{

    var enviar;

    enviar = true;

    

    form.txtMonto2.value = trim(form.txtMonto2.value)

    if ((form.txtMonto2.value == "" || form.txtMonto2.value < 1) && enviar == true) 

    { 

      LimpiarBordeCajasDividendo();

      document.getElementById("msg_error_dividendo").innerHTML = '*Por favor ingrese el monto en Dolares $';

      form.txtMonto2.focus(); 

      enviar = false; 

    }

    

    form.txtPie1.value = trim(form.txtPie1.value)

    if ((form.txtPie1.value == "") && enviar == true) 

    { 

      LimpiarBordeCajasDividendo();

      document.getElementById("msg_error_dividendo").innerHTML = '*Por favor ingrese el monto del pìe en Dolares $';

      form.txtPie1.focus(); 

      enviar = false; 

    }

    

    form.txtPlazo1.value = trim(form.txtPlazo1.value)

    if ((form.txtPlazo1.value == "" || form.txtPlazo1.value < 1) && enviar == true) 

    { 

      LimpiarBordeCajasDividendo();

      document.getElementById("msg_error_dividendo").innerHTML = '*Por favor ingrese el plazo del crédito.';

      form.txtPlazo1.focus(); 

      enviar = false; 

    }

    

    form.txtTaza1.value = trim(form.txtTaza1.value)

    if ((form.txtTaza1.value == "") && enviar == true) 

    { 

      LimpiarBordeCajasDividendo();

      document.getElementById("msg_error_dividendo").innerHTML = '*Por favor ingrese la tasa de interés.';

      form.txtTaza1.focus(); 

      enviar = false; 

    }

    

    if (enviar==true)

    { 

       LimpiarBordeCajasDividendo();

       document.getElementById("msg_error_dividendo").innerHTML = '';

       calcularDividendo(form.txtMonto2.value, form.txtPie1.value, form.txtPlazo1.value, form.txtTaza1.value, radioValor(form.optSubsidio1),radioValor(form.optTipo1));

    }

} 



function LimpiarBordeCajasDividendo()

{

   document.frmDividendo.txtMonto2.style.border = '0'

   document.frmDividendo.txtPie1.style.border   = '0'   

   document.frmDividendo.txtPlazo1.style.border = '0'   

   document.frmDividendo.txtTaza1.style.border  = '0'

}







/********************************* FUNCIONES FORMULARIO CREDITO ************************************************************/

function validarEnvianosTuPregunta(numInput)

{

    var pregunta = '';      

    pregunta = trim($('#txtPregunta'+numInput).val());

    

    if(pregunta == '' || pregunta == 'Escribe aquí...' || pregunta == 'Escribe aqu&iacute;...'){

        $.fn.colorbox({href:'/mensaje-error-pregunta-financiamiento/',width:'300px', height:'100px', iframe:true}); 

        return false;

    }

    

    $.ajax({

        type: "POST",

        url: "/operaciones_ajax.php",

        data: "tipo=validarEnvianosTuPregunta&pregunta="+pregunta,

        success: function(msg){

            $.fn.colorbox({href:msg,width:'380px', height:'345px', iframe:true});       

            return false;

        }       

    });

} 



function LimpiarBordeCajasPreguntas(caja)

{

   if (caja == 1) 

   {

      document.fp1.txtPregunta1.style.border = '0';

   }

   

   if (caja == 2) 

   {

      document.fp2.txtPregunta2.style.border = '0';

   }

   

   if (caja == 3) 

   {

      document.fp3.txtPregunta3.style.border = '0';

   }

  

}







/***************** FUNCIONES DE DESCUBRE NUESTROS PROYECTOS ***********************************/

function carga_proyectos(id_com){



    $.ajax({

        type: "POST",

        url: "/operaciones_ajax.php",

        data: "tipo=carga_proyectos&id_comuna="+id_com,

        success: function(msg){

            $('#proyectos').fadeOut('slow',function(){

                $('#proyectos').html(msg);

                $('#proyectos').fadeIn('slow');

                // Transversal, Llamados de tipografia (Cufon)

                Cufon.replace('.type');

                }

            );

        }       

    });

}

/***********************************************************************************************/

var numBusqueda = 0;

var urlBusqueda = '';



function busca_proyectos(txt,e){

    

    var RETURN = 13;

    var TAB = 9;

    var ESC = 27;

    var ARRUP = 38;

    var ARRDN = 40;

    var ARRLEFT = 37;

    var ARRRIGHT = 39;



    var key = window.event ? e.keyCode : e.which;

    var posicion = 1;

    switch(key){

        

        case TAB:       break;

        case ARRLEFT:   break;

        case ARRRIGHT:  break;

        

        case ESC:

            $("#suggest").hide();

        break;

        

        case ARRUP:

            /***** valida el limite de movimiento ******/

            numBusqueda--;

            if(numBusqueda == 0)numBusqueda = 1;

            /***** valida el limite de movimiento ******/

            

            $(".cont_hover").removeClass("hoverMenu");

            $("#link_"+numBusqueda+"").parent().addClass("hoverMenu");

            var p = $("#link_"+numBusqueda);

            var position = p.position();            

            $("#suggest").scrollTop( $("#suggest").scrollTop() + position.top - 135 )

                        

            urlBusqueda = $("#link_"+numBusqueda+"").attr("href");

        break;

        

        case ARRDN:

            /***** valida el limite de movimiento ******/ 

            numBusqueda++;          

            if(!$("#link_"+numBusqueda).length) numBusqueda--;

            /***** valida el limite de movimiento ******/

                        

            $(".cont_hover").removeClass("hoverMenu");

            $("#link_"+numBusqueda).parent().addClass("hoverMenu");

            var p = $("#link_"+numBusqueda);

            var position = p.position();            

            $("#suggest").scrollTop( $("#suggest").scrollTop() + position.top - 135 )



            urlBusqueda = $("#link_"+numBusqueda+"").attr("href");

        break;

        

        case RETURN:

            var nombre_proyecto = $("#link_"+numBusqueda+"").html();

            $("#input-buscador").val(nombre_proyecto);

            $("#suggest").hide("fast",function(){

                window.location.href = urlBusqueda;     

            });

            

        break;

        

        default:

            numBusqueda = 0;

            $.ajax({

                type: "POST",

                url: "/operaciones_ajax.php",

                data: "tipo=busca_proyectos&txt="+txt.value,

                success: function(msg){

                    $('#suggest').html(msg);

                    $("#suggest").slideDown();                  

                    

                    /*********** Marca primera posición del menu desplegable ************/                  

                        /***** valida el limite de movimiento ******/ 

                        numBusqueda++;          

                        if(!$("#link_"+numBusqueda).length) numBusqueda--;

                        /***** valida el limite de movimiento ******/

                                    

                        $(".cont_hover").removeClass("hoverMenu");

                        $("#link_1").parent().addClass("hoverMenu");

                        var p = $("#link_1");

                        var position = p.position();            

                        $("#suggest").scrollTop( $("#suggest").scrollTop() + position.top - 135 )

            

                        urlBusqueda = $("#link_1").attr("href");

                    /*********** Marca primera posición del menu desplegable ************/              

                    

                    if($('#buscador .combtn').attr("class") == "combtn" ){

                        $('#buscador .combtn').addClass("opened");

                    }                   

                    $('#buscador').mouseleave(function(){

                        $("#suggest").slideUp();

                        $('#buscador .combtn').removeClass("opened");

                    });

                }       

            });     

        break;  

    }

}



function elimina_favoritos(idFav){

    

    $.ajax({

        type: "POST",

        url: "/operaciones_ajax.php",

        data: "tipo=elimina_favoritos&idFav="+idFav,

        success: function(msg){

            if(msg == 'ok'){

                $('#fav-'+idFav).remove();

                $('#lifav-'+idFav).remove();

            }

        }       

    });

}



function olvido_clave(paso){

    var rut = $('#txtRut').val();

    var codigo = $('#txtCod').val();

    var extension = '';

    if(paso==3){

        extension = "&p1="+$('#txtPass1').val()+"&p2="+$('#txtPass2').val();

    }

    $.ajax({

        type: "POST",

        url: "/operaciones_ajax.php",

        data: "tipo=olvido_clave&paso="+paso+"&rut="+rut+"&codigo="+codigo+extension,

        success: function(msg){

            $('#contenido-form').fadeOut('slow',function(){

                $('#contenido-form').html(msg);                                          

                $('#contenido-form').fadeIn('slow');

            });

        }       

    });

}





var map;

var arrHtml;

var arrCordenadas;

function mapa_resultado_busqueda() {

    

    var blueIcon = new GIcon(G_DEFAULT_ICON);

    blueIcon.image = '/axi_gmap_mark.png';

    var markerOptions = { icon:blueIcon };

    

    var posicion = $('#mapPosicion').val(); 

    var zoom = $('#mapZoom').val();

    arrCordenadas = $('#mapCordenadas').val();

    arrHtml = $('#mapHtml').val();

    if(posicion != '' && arrCordenadas != ''){



        arrCordenadas = arrCordenadas.split("|");

        arrHtml = arrHtml.split("|");

        posicion = posicion.split(",");

        var latitud = posicion[0];

        var longitud = posicion[1];

        

        if (GBrowserIsCompatible()) {   

            map = new GMap2(document.getElementById("map"));

            //map.addControl(new GLargeMapControl());

            //map.addControl(new GMapTypeControl());

            map.setUIToDefault();

            map.disableGoogleBar();

            //map.setCenter(new GLatLng(latitud,longitud), 5);

            map.setCenter(new GLatLng(-32.657876,-71.147461), 5); // posicion central desde antofagasta a osorno

            

            function crearMarcaPestanas(punto,contenidoHtml) {

                var marca = new GMarker(punto, markerOptions);

                GEvent.addListener(marca, "click", function() {

                marca.openInfoWindowHtml(contenidoHtml);

                });

                return marca;

            }

            

            for(i=0; i < arrCordenadas.length; i++){

                var arrLatLong = arrCordenadas[i].split(",");           

                map.addOverlay(crearMarcaPestanas(new GLatLng(arrLatLong[0],arrLatLong[1]), arrHtml[i]));

            }

            

        }   

    }

}



function muestra_resultado(tipo){

    $.ajax({

        type: "POST",

        url: "/operaciones_ajax.php",

        data: "tipo=muestra_resultado&tipoResultado="+tipo,

        success: function(msg){

            $('#tipo-seleccionado').val(tipo);

            if(tipo == 'lista'){

                if($('.uno a').attr('class') == ''){

                    $('.dos a').removeClass('current');          

                    $('.uno a').addClass('current');

                    $('#resu-mapa').fadeOut('slow',function(){$('#resu-lista').fadeIn('slow');$('.orden_busqueda').show();});

                }               

            }

            else if(tipo == 'mapa'){

                if($('.dos a').attr('class') == ''){

                    $('.uno a').removeClass('current');         

                    $('.dos a').addClass('current');

                                    

                    $('#resu-lista').fadeOut('slow',function(){

                        $('.orden_busqueda').hide();

                        $('#resu-mapa').show();

                        mapa_resultado_busqueda();                  

                    });

                }

            }       

        }

    }); 

}



function cargaSelTipoOpotunidad(tipoX,idP,idT,idV){



    $.ajax({

        type: "POST",

        url: "/operaciones_ajax.php",

        data: "tipo=cargaSelTipoOpotunidad&tipoX="+tipoX+"&idP="+idP+"&idT="+idT+"&idV="+idV,

        success: function(msg){

            $('#area-sel2').slideUp('fast', function(){

                $('#area-sel2').html(msg);                                           

                $('#area-sel2').slideDown('fast');                                   

            });         

        }       

    });

}





/***************** FUNCION QUE CALCULA Y GUARDA CREDITOS ***********************************/

function calcularCredito(monto, pie, plazo, taza, subsidio, tipo){



    $.ajax({

        type: "POST",

        url: "/operaciones_ajax.php",

        data: "tipo=calcularCredito&monto="+monto+"&pie="+pie+"&plazo="+plazo+"&taza="+taza+"&subsidio="+subsidio+"&tipoX="+tipo,

        success: function(msg){

            $('#pagina_credito').fadeOut('slow',function(){

                $('#pagina_credito').html(msg);

                $('#pagina_credito').fadeIn('slow');

            });

        }       

    });

}





/***************** FUNCION DIVIDENDO ***********************************/

function calcularDividendo(monto, pie, plazo, taza, subsidio, tipo){



    $.ajax({

        type: "POST",

        url: "/operaciones_ajax.php",

        data: "tipo=calcularDividendo&monto="+monto+"&pie="+pie+"&plazo="+plazo+"&taza="+taza+"&subsidio="+subsidio+"&tipoX="+tipo,

        success: function(msg){

            $('#pagina_dividendo').fadeOut('slow',function(){

                $('#pagina_dividendo').html(msg);

                $('#pagina_dividendo').fadeIn('slow');

            });

        }       

    });

}



function guarda_valor_select(valor,input){

    $('#'+input).val(valor);

}



/***************** FUNCION GLOSARIO ***********************************/

function glosario(txt){

    

    $.ajax({

        type: "POST",

        url: "/asistencia-script.php",

        data: "termino="+txt+"&amp;tipo=Glosario",

        success: function(msg){

            $('#termino').html(msg);

            $("#termino").slideDown();

            

            $('#glosariofrm').mouseleave(function(){

                $("#termino").slideUp();

            });

        }       

    });

}



/***************** CLICKS EN FAQS ***********************************/

function clicks(id,type){

    $.ajax({

        type: "POST",

        url: "/asistencia-script.php",

        data: "id="+id+"&tipo="+type      

    });

}



/*************** MOVIMIENTO POR LOS TAB FINANCIAMIENTO **************/

function tabsFinanciamiento(tabSeleccionado,btnSeleccionado){

    $('.finan-pane').hide();

    $('.finan-tabs li a').removeClass('current');

    $('#'+tabSeleccionado).show();

    $('#'+btnSeleccionado).addClass('current'); 

}



function validaFormCuantoPuedesPedir(){

    var msj = '';

    var foco = '';

    $('#msj-error').html(''); 

    

    if(trim($('#renta1').val()) == '' || trim($('#renta1').val()) == 'Escribe el monto'){

        msj = '- Debes ingresar una renta.';

        foco = 'renta1';

    }

    else if(trim($('#tasa').val()) == '' || trim($('#tasa').val()) < 1 || (trim($('#tasa').val())*1) > 8 ){

        msj = '- Debes ingresar una tasa de interes real.';

        foco = 'tasa';

    }

    else if(($('#txtPlazo').val() * 1) < 1 ){

        msj = '- Debes ingresar una cantidad de a&ntilde;os plazo.';

        foco = 'txtPlazo';

    }

    

    if(msj == ''){

        $.ajax({

            type: "POST",

            url: "/operaciones_ajax.php",

            data: $('#frmCpp').serialize()+"&tipo=validaFormCuantoPuedesPedir",

            success: function(msg){

                $('#resultado-cpp').fadeOut('slow',function(){

                    $('#resultado-cpp').html(msg);

                    $('#resultado-cpp').fadeIn('slow'); 

                });             

            } 

        });

    }

    else{

        $('#msj-error').html(msj);

        $('#'+foco).val('');

        $('#'+foco).focus();

    }

}



/*=================  COMPARADOR  ====================*/

var capa = '';

function comparador(id){

    var goes = 'si';

    $('.franja-compara').slideDown("fast");

    if(document.getElementById('abrirCerrar').className != 'abrir-cerrar act'){     

        $('.abrir-cerrar').addClass("act");

        $('.franja-compara').animate({"bottom": "0px"}, "slow");

    }else{

        goes = 'no';

    }

    $.ajax({

        type: "POST",

        url: "comparador-script.php",

        data: "id="+id,

        success: function(msg){         

            if(msg =='errorid'){                

            }else if(msg =='errorexiste'){

                capa = "#id-"+id+"";

                $(capa).fadeOut('fast');

                $(capa).fadeIn('slow');             

            }else if(msg =='errormax'){

                if(goes=='si'){

                    setTimeout("$('.lista-compara').effect('shake', { times:3 }, 80);",500);    

                }else{

                    $('.lista-compara').effect("shake", { times:3 }, 80);           

                }                               

            }else{

                $('.lista-compara').html(msg);

                setTimeout("$('#id-"+id+"').fadeIn('slow');",500);                      

            }

        }       

    });

}

var tipo ='';

function del(id){   

    tipo = "#id-"+id+"";

    $(tipo).fadeTo( 400, 0,function(){

        $(tipo).animate({width: 'hide'},function(){

            $(tipo).remove();mensajeComp(); 

        });

    }); 

    $.ajax({

        type: "POST",

        url: "comparador-script.php",

        data: "rem="+id

    });

}

function mensajeComp(){

    var contenido = document.getElementById('box-comparador').innerHTML;

    if(contenido==0){

        $('.abrir-cerrar').removeClass("act");

        $('.franja-compara').animate({"bottom": "-120px"}, "slow"); 

    }

}

function abrirComp(){

    if(document.getElementById('abrirCerrar').className == 'abrir-cerrar act'){     

        $('.abrir-cerrar').removeClass("act");

        $('.franja-compara').animate({"bottom": "-120px"}, "slow");         

    }else{

        $('.abrir-cerrar').addClass("act");

        $('.franja-compara').animate({"bottom": "0px"}, "slow");    

    }   

}

function irComparador(){

    fname = document.form1;

    $.ajax({type: "POST",url: "comparador-script.php",data: "cant=si",

                success: function(msg){                 

                    if(msg==1 || msg==0){

                        $('#texto-muestra').fadeOut('slow',function(){

                        $('#texto-muestra2').fadeIn('slow').delay(200).fadeOut();

                        $('#texto-muestra2').fadeIn('slow').delay(200).fadeOut(function(){

                                $('#texto-muestra').fadeIn('slow').delay(300);

                            });

                        });                     

                    }else{

                        fname.submit();

                    }                   

                }                   

        });     

}

/*=================  COMPARADOR  ====================*/









/************ FUNCIONES COTIZACION **************************************/

function cargaU$Cotizacion(valor){

    $('#valorPropiedadX').val(valor);

    $('#valPropiedad').fadeOut('slow',function(){

        $('#valPropiedad').html(valor+' S/');

        Cufon.replace('.type'); 

        $('#valPropiedad').fadeIn('slow');      

    });

}

function validaFormCoti(){

    $.ajax({

        type: "POST",

        url: "/operaciones_ajax.php",

        data: "tipo=validaFormCoti&proyecto="+$('#proyectoX').val()+"&modelo="+$('#modeloX').val()+"&modo="+$('#modoX').val()+"&annos="+$('#annosX').val()+"&sub="+$('#subX').val()+"&piso="+$('#pisoX').val()+"&valorPropiedad="+$('#valorPropiedadX').val()+"&pie="+$('#txtPie').val()+"&enviarUnAmigo="+$('#EnviarUnAmigo').val(),

        success: function(msg){

            $('#res-cotizacion').fadeOut('slow',function(){

                $(this).html(msg);

                $(this).fadeIn();

            });         

        }

    });

}

/************************************************************************/





function printSWF(file,w,h){

    var strHome = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0" id="homeflash" width="'+w+'" height="'+h+'" align="">\n';

    strHome += '<param name="movie" value="'+file+'">\n'; 

    strHome += '<param name="swliveconnect" value="true">\n';

    strHome += '<param name="quality" value="high">\n';

    strHome += '<param name="bgcolor" value="#FFFFFF">\n'; 

    strHome += '<param name="wmode" value="transparent">\n';

    strHome += '<param name="menu" value="false">\n';

    strHome += '<embed src="'+file+'" quality="high" bgcolor="#FFFFFF" menu="false" wmode="transparent" width="'+w+'" height="'+h+'" name="homeflash" swliveconnect="true" align=""  TYPE="application/x-shockwave-flash" pluginspace="http://www.macromedia.com/go/getflashplayer">\n';

    strHome += '</embed>\n';

    strHome += '</object>\n';

    document.write(strHome);

}



/********************** CONTACTANOS ***********************************/

function enviar_email_contactanos(){

    

    var nombre = $('#nombre').val();

    var paterno = $('#paterno').val();

    var materno = $('#materno').val();

    //var txtRut = $('#txtRut').val();

    var email = $('#email').val();

    var telefono = $('#telefono').val();

    if($("#tipoConsulta1").attr("checked"))var cbconsulta =$("#tipoConsulta1").attr("value");

    if($("#tipoConsulta2").attr("checked"))var cbconsulta =$("#tipoConsulta2").attr("value");

    if($("#tipoConsulta3").attr("checked"))var cbconsulta =$("#tipoConsulta3").attr("value");

    if($("#tipoConsulta4").attr("checked"))var cbconsulta =$("#tipoConsulta4").attr("value");

    

    var cbproyecto = $('#cbproyecto').val();  

    var comentario = $('#comentario').val();

    

    $.ajax({

        type: "POST",

        url: "test.php",

        data: "tipo=enviar_email_contactanos&nombre="+nombre+"&paterno="+paterno+"&materno="+materno+"&email="+email+"&telefono="+telefono+"&cbconsulta="+cbconsulta+"&cbproyecto="+cbproyecto+"&comentario="+comentario,

        success: function(msg){

            //$('#msg').html(msg);

            if(msg == 'ok'){

                $.fn.colorbox({href:'contacto2.php',width:'300px', height:'100px', iframe:true});

                $('#nombre').val('');

                $('#paterno').val('');

                $('#materno').val('');

                //$('#txtRut').val('');

                $('#email').val('');

                $('#telefono').val('');

                $('#comentario').val('');

                $('#cbproyecto').val('');
                $('#contenerdorProy').html('<ol id="uno" class="combo w-294"><li><a href="#" rel="">Seleccione</a></li></ol>');

                $('.proy-tipobx #option').html('Seleccione');

                return false;

            }

            else if(msg == 'error'){

                $.fn.colorbox({href:'error.php',width:'300px', height:'100px', iframe:true}); 

                return false;

            }

            else{

                $.fn.colorbox({href:'error.php',width:'300px', height:'100px', iframe:true}); 

                return false;

            }

        }

    }); 

}


function llenaProyectos(val){

    var valor = val

    $.ajax({

        type: "POST",

        url: "/contactanos-script.php",

        data: "tipo=tipoProyContactanos&id="+valor,

        success: function(msg){

            $('#contenerdorProy').html('<ol id="uno" class="combo w-294"><li><a href="#" rel="">Seleccione</a></li>'+msg);  

            $(document).ready(function(){

                $("#uno").cocombobox();

                $(".unobx").css("z-index","124");

            });

        }       

    });

}



var muestra = 1;

function muestraCombos(txt){    

    if(txt=='Compra de una vivienda' || txt=="Subsidio"){

        if(muestra == 0){

            $('.contenedorCombos').slideDown('slow',function(){

                $('.combo.proy-tipobx').fadeIn(700);

                $('.combo.unobx').fadeIn(700);

                muestra = 1;    

            });         

        }

    }else if(txt=='Servicio al cliente' || txt=="Otro" ){

        if(muestra == 1){           

            $('.contenedorCombos').slideUp('slow',function(){   

                $('.combo.proy-tipobx').fadeOut(200);

                $('.combo.unobx').fadeOut(200); 

                muestra = 0;

            });

        }

    }

}







/***********************************************************/



function recetear_buscador(){



    

    // limpiamos checkbox de regiones           

    $('.chkRegion').removeAttr("checked");

    

    // limpiamos checkbox de opciones avanzadas         

    $('.chkOpAvanzadas').removeAttr("checked");

    

    //limpiamos los radio button de casas o departamentos           

    $('.radioIndex').removeAttr("checked");

    

    // limpiamos html cargado en comunas

    $('#carga-comunas').html('');

                

    

    busquedaViva = 1; // dejamos variable en 1 para no actualizar la busqueda

    

    // limpiamos select de baños

    $("#banosTodos").click();



    // limpiamos select de dormitorios

    $("#dormiTodos").click();                       

                

    // Dejamos rangos de precios por default

    $("#total_range").slider({

        range: true,

        min: 800,

        max: 25000,

        step: 100,

        values: [800, 25000],

        slide: function(event, ui) {

            $("#total_value").val('U$ ' + agregaPuntosFijo(ui.values[0]) + ' - U$ ' + agregaPuntosFijo(ui.values[1]) );

        }

    });         

    $("#total_value").val('U$ ' + agregaPuntosFijo($("#total_range").slider("values", 0)) + ' - U$ ' + agregaPuntosFijo($("#total_range").slider("values", 1)) );





    // Dejamos rangos de dividendo por default

    $("#dividendo_range").slider({

        range: true,

        min: 50000,

        max: 5000000,

        step: 50000,

        values: [50000, 5000000],

        slide: function(event, ui) {

            $("#dividendo_value").val('S/' + agregaPuntosFijo(ui.values[0]) + ' - S/' + agregaPuntosFijo(ui.values[1]) );

        }

    }); 

    $("#dividendo_value").val('S/' + agregaPuntosFijo($("#dividendo_range").slider("values", 0)) + ' - S/' + agregaPuntosFijo($("#dividendo_range").slider("values", 1)) );

    busquedaViva = 0; // dejamos la variable en 0 para poder actualizar la busqueda

    $.ajax({

        type: "POST",

        url: "/operaciones_ajax.php",

        data: "tipo=limpiaRegiones",

        success: function(msg){

            busqueda_viva(); // realiza nueva busqueda con los filtros limpios

        }       

    });

    

}       



function enviar_datos_miperfil(){



    var sexo = $("#sexo").val();

    var fechaNacimiento = $("#txtFechaNacimiento").val();

    var estadoCivil = $("#estado-civil").val();

    var nacionalidad = $("#txtNacionalidad").val();

    var actividad = $("#txtActividad").val();

    var rangoIngresos = $("#rango-ingresos").val();

    var direccionResidencia = $("#direccion-residencia").val();

    var regionResidencia = $("#region-residencia").val();

    var comunaResidencia = $("#comuna-residencia").val();

    var direccionLaboral = $("#direccion-laboral").val();

    var regionLaboral = $("#region-laborales").val();

    var comunaLaboral = $("#comuna-laboral").val();

    var fonoLaboral = $("#txtFonoLaboral").val();

    var email = $("#txtEmail").val();

    var fonoFijo = $("#txtTelefonoFijo").val();

    var fonoCelular = $("#txtCelular").val();

    var horarioPreferido = $("#horario-preferido").val();

    

    $.ajax({

        type: "POST",

        url: "/operaciones_ajax.php",

        data: "tipo=enviar_datos_miperfil&sexo="+sexo+"&fechaNacimiento="+fechaNacimiento+"&estadoCivil="+estadoCivil+"&nacionalidad="+nacionalidad+

              "&actividad="+actividad+"&rangoIngresos="+rangoIngresos+"&direccionResidencia="+direccionResidencia+"&regionResidencia="+regionResidencia+

              "&comunaResidencia="+comunaResidencia+"&direccionLaboral="+direccionLaboral+"&regionLaboral="+regionLaboral+"&comunaLaboral="+comunaLaboral+

              "&fonoLaboral="+fonoLaboral+"&email="+email+"&fonoFijo="+fonoFijo+"&fonoCelular="+fonoCelular+"&horarioPreferido="+horarioPreferido,            

        success: function(msg){



            if(msg == 'ok'){

                

                $.fn.colorbox({href:'/mensaje-miperfil-ok/',width:'300px', height:'100px', iframe:true});

                return false;               

            }

            else if(msg == 'error'){                

                

                $.fn.colorbox({href:'/mensaje-miperfil-error/',width:'300px', height:'100px', iframe:true});    

                return false;

            }

        }       

    });

    

}



function facebook(){

    $.fn.colorbox({href:'/redes-sociales-facebook.php',width:'510px', height:'550px', iframe:true});

}



function copyText(theSel) {

    if (!document.all) return; // IE only

    theForm = theSel.form;

    theForm.copyArea.value=theSel.options[theSel.selectedIndex].value;

    r=theForm.copyArea.createTextRange();

    r.select();

    r.execCommand('copy');

} 



function copy(inElement) {

  if (inElement.createTextRange) {

    var range = inElement.createTextRange();

    if (range && BodyLoaded==1)

     range.execCommand('Copy');

  } else {

    var flashcopier = 'flashcopier';

    if(!document.getElementById(flashcopier)) {

      var divholder = document.createElement('div');

      divholder.id = flashcopier;

      document.body.appendChild(divholder);

    }

    document.getElementById(flashcopier).innerHTML = '';

   var divinfo = '<embed src="_clipboard.swf" FlashVars="clipboard='+escape(inElement.value)+'" width="0" height="0" type="application/x-shockwave-flash"></embed>';

    document.getElementById(flashcopier).innerHTML = divinfo;

  }

}



function envia_pregunta() {

    if( trim($("#txtPregunta").val()) == "" ){

        $("#msj_error").css("background-color","#FF9");

        $("#msj_error").html("Debes ingresar una pregunta.");

        return false;

    }

    

    $.ajax({

        type: "POST",

        url: "/operaciones_ajax.php",

        data: "tipo=envia_pregunta&txtPregunta="+trim($("#txtPregunta").val()),           

        success: function(msg){

            if(msg == "ok"){

                window.top.$.fn.colorbox({href:'/mensaje-miperfil-enviar-pregunta/',width:'350px', height:'120px', iframe:true});

                return false;

            }

            else{

                $("#msj_error").css("background-color","#FF9");

                $("#msj_error").html("Tu pregunta no ha podido ser enviada, intenta más tarde.");

                return false;

            }

        }       

    });

    

}



function guardarAlerta(){

        

    var tipoAlerta = trim($("#tipoAlerta").val());

    var proyecto = trim($("#proyecto").val());

    var modelo = trim($("#modelo").val());

    var periodo = trim($("#opcion_depto").val());

    var op1 = $("#cbxCambioDePrecio").attr("checked");

    var op2 = $("#cbxVendida").attr("checked");

    var op3 = $("#cbxOportunidad").attr("checked");

    var op4 = $("#cbxSimilar").attr("checked");

    

    if( op1 == true || op2 == true || op3 == true || op4 == true ){

        

        $.ajax({

            type: "POST",

            url: "/operaciones_ajax.php",

            data: "tipo=guardarAlerta&cbxCambioDePrecio="+op1+"&cbxVendida="+op2+"&cbxOportunidad="+op3+"&cbxSimilar="+op4+"&tipoAlerta="+tipoAlerta+"&proyecto="+proyecto+"&modelo="+modelo+"&periodo="+periodo,

            success: function(msg){

                if(msg=="ok"){

                    window.top.$.fn.colorbox({href:'/mensaje-alertas-ok/',width:'350px', height:'120px', iframe:true});

                    return false;

                }

                else{

                    $("#msj_error").html(msg);

                    return false;

                }

            }       

        });         

    }

    else{

        $("#msj_error").html("Debes seleccionar almenos una alternativa");

        return false;   

    }

        

    

        

}



function actualizarAlertas(identificador){



    var op1 = $("#cbxCambioDePrecio_"+identificador).attr("checked");

    var op2 = $("#cbxVendida_"+identificador).attr("checked");

    var op3 = $("#cbxOportunidad_"+identificador).attr("checked");

    var op4 = $("#cbxSimilar_"+identificador).attr("checked");

    

    $.ajax({

        type: "POST",

        url: "/operaciones_ajax.php",

        data: "tipo=actualizarAlertas&cbxCambioDePrecio="+op1+"&cbxVendida="+op2+"&cbxOportunidad="+op3+"&cbxSimilar="+op4+"&idal="+identificador,

        success: function(msg){

            if(msg!="ok"){

                window.top.$.fn.colorbox({href:'/mensaje-alertas-error/',width:'350px', height:'120px', iframe:true});

                return false;

            }

        }       

    });

}



function eliminarAlerta(identificador){

    $.ajax({

        type: "POST",

        url: "/operaciones_ajax.php",

        data: "tipo=eliminarAlerta&idal="+identificador,

        success: function(msg){

            if(msg!="ok"){

                window.top.$.fn.colorbox({href:'/mensaje-alertas-error/',width:'350px', height:'120px', iframe:true});

                return false;

            }

            else{

                //eliminar

                $(".cclose_"+identificador).parents("tr").fadeOut();

                return false;               

            }

        }       

    });

}



function descargarArchivos(seguimiento,etapa){

    

    $.ajax({

        type: "POST",

        url: "/operaciones_ajax.php",

        data: "tipo=descargarArchivos&seguimiento="+seguimiento+"&etapa="+etapa,

        success: function(msg){

            if(msg=="error"){

                window.top.$.fn.colorbox({href:'/mensaje-alertas-error/',width:'350px', height:'120px', iframe:true});

                return false;

            }

            else{

                document.location.href=msg;

            }

        }

    });

        

}



(function($) {

  var cache = [];

  // Arguments are image paths relative to the current page.

  $.preLoadImages = function() {

    var args_len = arguments.length;

    for (var i = args_len; i--;) {

      var cacheImage = document.createElement('img');

      cacheImage.src = arguments[i];

      cache.push(cacheImage);

    }

  }

})(jQuery)


