﻿// 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 toGrayScale(im){
    im.style.cursor='pointer';
    if(document.createElement("canvas").getContext){
        if(im.gs){
            im.src=im.gs;
            return;
        }
        var ref = document.createElement("canvas");
        ref.width = im.width || im.offsetWidth;
        ref.height =im.height  || im.offsetHeight;
        var context = ref.getContext("2d");
        context.drawImage(im,0,0);
        var iData=context.getImageData(0,0,  ref.width, ref.height);
        var data   = iData.data;
        var length = data.length;
          for (var i = 0;i<length;i+=4) {
            var average = (data[i]+data[i+1]+data[i+2])/3;
              data[i]   = average;
              data[i+1] = average;
              data[i+2] = average;
            
          }
          context.putImageData(iData, 0, 0);
          im.src=im.gs=ref.toDataURL();
    }else{
        im.style.filter = 'progid:DXImageTransform.Microsoft.BasicImage(grayscale=1)';
    }
    
}

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 IsFijo(e){
	tecla = (document.all) ? e.keyCode : e.which;
	if (tecla==8 || tecla ==0) return true;
	patron = /[-0123456789\s\/-]/;
	te = String.fromCharCode(tecla);
	return patron.test(te)
} 

function IsCelular(e){
	tecla = (document.all) ? e.keyCode : e.which;
	if (tecla==8 || tecla ==0) return true;
	patron = /[-0123456789\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 IsCasilla(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');
}
/**LOGIN**/
function msgError(txt){
	if(txt=='clear'){
		$('.er').html('');
		$('#mensajeError').hide()
	}else{
		$('.er').html('');	
		$('.'+txt).css({'font-size':'12px','color':'#F93100','position':'absolute','padding':'3px 0 0 5px'}).html('*');	
		$('#mensajeError').fadeOut("",function(){
			if(trim(txt) == 'txtPass'){txt='txtContraseña';}			
			$(this).html('El campo '+txt.substring(3)+' es incorrecto');
			$(this).fadeIn(500,function(){
				setTimeout("$('#mensajeError').fadeOut(300)",2000);
			});
		});
	}
}
function validaFormLogin(){
	sw='';
	if($('#selZona').val()==''){msgError('selZona');sw='selZona';}
	else if($('#selValidacion').val()==''){msgError('selValidacion');sw='selValidacion';}
	else if($('#txtRut').val()=='' || ValidaRut($('#txtRut').val())==false){msgError('txtRut');sw='txtRut';}	
	else if($('#txtPass').val()=='' || $('#txtPass').val().length < 4){msgError('txtPass');sw='txtPass';}	
	if(trim(sw)==''){
		msgError('clear');		
		jQuery.ajax({
		type: "POST",
		url: "/sucursal-en-linea/login/validar/",
		data: $('#formLogin').serialize() , 
		success: function(msg){
				if( msg=='ok' ){
					$( '#formLogin' ).submit() ;
				}else{
					$(window.location).attr('href', '/sucursal-en-linea/login/');
				}
			}       
		});	
	}
}
/**LOGIN**/

/** recuperacion de contraseña **/
function validaFormRecuperacion() {
	
	sw='';
	if( $('#selZona').val()=='' ){ msgError('selZona');sw='selZona'; }
	else if($('#txtRut').val()=='' || ValidaRut($('#txtRut').val())==false){msgError('txtRut');sw='txtRut';}	

	if(trim(sw)==''){
		msgError('clear');		
		jQuery.ajax({
			type: "POST",
			url: "/sucursal-en-linea/login/recuperar-contrasena-enviar-email/",
			data: $('#formLogin').serialize() , 
			success: function(msg){
				$('#resp').html(msg);
			}       
		});	
	}	
}


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: "../../operaciones_ajax.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á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 U.F.';
	  //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 pesos';
	  //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 U.F.';
      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 montodel pìe en pesos';
      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í...'){
		$.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');
				}
			);
		}       
	});
}

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+"&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ñ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 cargaUfCotizacion(valor){
	$('#valorPropiedadX').val(valor);
	$('#valPropiedad').fadeOut('slow',function(){
		$('#valPropiedad').html(valor+' UF');
		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="../../sucursal-en-linea/js/'+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="../../sucursal-en-linea/js/'+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 txtNombres = $('#txtNombres').val();
	var txtPaterno = $('#txtPaterno').val();
	var txtMaterno = $('#txtMaterno').val();
	var txtRut = $('#txtRut').val();
	var txtEmail = $('#txtEmail').val();
	var txtFono = $('#txtFono').val();
	if($("#tipoConsulta1").attr("checked"))var tipoConsulta =$("#tipoConsulta1").attr("value");
	if($("#tipoConsulta2").attr("checked"))var tipoConsulta =$("#tipoConsulta2").attr("value");
	if($("#tipoConsulta3").attr("checked"))var tipoConsulta =$("#tipoConsulta3").attr("value");
	if($("#tipoConsulta4").attr("checked"))var tipoConsulta =$("#tipoConsulta4").attr("value");
	
	var uno = $('#uno').val();	
	var txtConsulta = $('#txtConsulta').val();
	
	$.ajax({
		type: "POST",
		url: "/operaciones_ajax.php",
		data: "tipo=enviar_email_contactanos&txtNombres="+txtNombres+"&txtPaterno="+txtPaterno+"&txtMaterno="+txtMaterno+"&txtRut="+txtRut+"&txtEmail="+txtEmail+"&txtFono="+txtFono+"&tipoConsulta="+tipoConsulta+"&uno="+uno+"&txtConsulta="+txtConsulta,
		success: function(msg){
			//$('#msg').html(msg);
			if(msg == 'ok'){
				$.fn.colorbox({href:'/mensaje-contactanos-ok/',width:'300px', height:'100px', iframe:true});
				$('#txtNombres').val('');
				$('#txtPaterno').val('');
				$('#txtMaterno').val('');
				$('#txtRut').val('');
				$('#txtEmail').val('');
				$('#txtFono').val('');
				$('#txtConsulta').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:'/mensaje-contactanos-error/',width:'300px', height:'100px', iframe:true});	
				return false;
			}
			else{
				$.fn.colorbox({href:'/mensaje-contactanos-error-interno/',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('UF ' + agregaPuntosFijo(ui.values[0]) + ' - UF ' + agregaPuntosFijo(ui.values[1]) );
		}
	});			
	$("#total_value").val('UF ' + agregaPuntosFijo($("#total_range").slider("values", 0)) + ' - UF ' + 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('$' + agregaPuntosFijo(ui.values[0]) + ' - $' + agregaPuntosFijo(ui.values[1]) );
		}
	});	
	$("#dividendo_value").val('$' + agregaPuntosFijo($("#dividendo_range").slider("values", 0)) + ' - $' + 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="../../sucursal-en-linea/js/_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)


function contarCaracteres(id,maximo) {

  n = $('#'+id).val().length;
  t = maximo;

  if (n > t) 
  {
    /*document.forms[form][name].value = document.forms[form][name].value.substring(0, t);*/
	$('#'+id).val( $('#'+id).val().substring(0,t) );
  }
  else 
  {
    /*document.forms[form]['result'].value = t-n;*/
	$('#'+id+'_resto').html(t-n);
  }
}

function validaEnvioComentario(){
	
	var nombre = trim($("#txtNombre").val());
	var email = trim($("#txtEmail").val());
	var comentario = trim($("#txtComentario").val());
	var entrada = trim($("#txtEntrada").val());
	var msj = '';
	var foco = '';
	$('#msj_error').html(''); 
	
	if(nombre == '' || nombre.length < 3 ){
		msj = 'Debes ingresar un nombre válido.';
		foco = 'txtNombre';
	}
	else if(!isEmailAddress(email) || email == ''){
		msj = 'Debes ingresar un email válido.';
		foco = 'txtEmail';
	}
	else if(comentario == ''){
		msj = 'Debes ingresar un comentario.';
		foco = 'txtComentario';
	}
		
	if(msj == ''){
		$.ajax({
			type: "POST",
			url: "/operaciones_ajax.php",
			data: "tipo=validaEnvioComentario&nombre="+nombre+"&email="+email+"&comentario="+comentario+"&entrada="+entrada,
			success: function(msg){				
				var arrMsj = msg.split("|");
				
				if(arrMsj[0]=="ok"){
					$("#contRespuesta").html(arrMsj[1]);
					$("#contRespuesta").fadeIn();
					$("#txtNombre").val("");
					$("#txtEmail").val("");
					$("#txtComentario").val("");					
				}
				else{
					$("#msj_error").html(arrMsj[1]);
					return false;
				}
			}       
		});
	}
	else{
		$('#msj_error').html(msj);
		$('#'+foco).val('');
		$('#'+foco).focus();
	}
		
}

function enviaPregunta(){
	
	var msj = '';
	$('#msj_error').html(''); 
	
	if( trim($("#selRespuesta").val()) == '' ){
		msj = 'Debes seleccionar una respuesta para continuar.';
	}
	
	if(msj == ''){
		$.ajax({
			type: "POST",
			url: "/operaciones_ajax.php",
			data: "tipo=enviaPregunta&respuesta="+trim($("#selRespuesta").val())+"&trivia="+trim($("#trivia").val())+"&pregunta="+trim($("#pregunta").val()),
			success: function(msg){				
				arr = msg.split("|");
				if(arr[0] == "ok"){
					$(".cont_trivia").html(arr[1]);
				}
				else{
					$('#msj_error').html(arr[1]);
				}
			}       
		});
	}
	else{
		$('#msj_error').html(msj);
	}
	
	return false;	
}

function ingresaRespTrivia(){
	
	var msj = '';
	var foco = '';
	$('#msj_error').html(''); 
	
	if( trim($("#txtNombre").val()) == '' ){
		msj = 'Debes ingresar un nombre para continuar.';
		foco = 'txtNombre';
	}
	else if( !isEmailAddress( trim($("#txtEmail").val()) ) || trim($("#txtEmail").val()) == '' ){
		msj = 'Debes ingresar un email.';
		foco = 'txtEmail';
	}
	else if( trim($("#txtFono").val()) == '' ){
		msj = 'Debes ingresar un fono para continuar.';
		foco = 'txtFono';
	}
	
	if(msj == ''){
		$.ajax({
			type: "POST",
			url: "/operaciones_ajax.php",
			data: "tipo=ingresaRespTrivia&nombre="+trim($("#txtNombre").val())+"&email="+trim($("#txtEmail").val())+"&fono="+trim($("#txtFono").val()),
			success: function(msg){				
				arr = msg.split("|");
				if(arr[0] == "ok"){
					$("#msj_error").html(arr[1]);
					$("#txtNombre").val("");
					$("#txtEmail").val("");
					$("#txtFono").val("");
				}
				else{
					$('#msj_error').html(arr[1]);
				}
			}       
		});
	}
	else{
		$('#msj_error').html(msj);
		$('#'+foco).val('');
		$('#'+foco).focus();
	}
	
	return false;		
}

function ingresaRespTriviaUnica(){
	
	var msj = '';
	var foco = '';
	$('#msj_error').html(''); 
	
	if( trim($("#txtNombre").val()) == '' ){
		msj = 'Debes ingresar un nombre para continuar.';
		foco = 'txtNombre';
	}
	else if( !isEmailAddress( trim($("#txtEmail").val()) ) || trim($("#txtEmail").val()) == '' ){
		msj = 'Debes ingresar un email.';
		foco = 'txtEmail';
	}
	else if( trim($("#txtFono").val()) == '' ){
		msj = 'Debes ingresar un fono para continuar.';
		foco = 'txtFono';
	}
	
	if(msj == ''){
		$.ajax({
			type: "POST",
			url: "/operaciones_ajax.php",
			data: "tipo=ingresaRespTriviaUnica&nombre="+trim($("#txtNombre").val())+"&email="+trim($("#txtEmail").val())+"&fono="+trim($("#txtFono").val()),
			success: function(msg){				
				arr = msg.split("|");
				if(arr[0] == "ok"){
					$("#msj_error").html(arr[1]);
					$("#txtNombre").val("");
					$("#txtEmail").val("");
					$("#txtFono").val("");
				}
				else{
					$('#msj_error').html(arr[1]);
				}
			}       
		});
	}
	else{
		$('#msj_error').html(msj);
		$('#'+foco).val('');
		$('#'+foco).focus();
	}
	
	return false;		
}

function cargaTrivia(trivia){
	$.ajax({
		type: "POST",
		url: "/operaciones_ajax.php",
		data: "tipo=cargaTrivia&trivia="+trivia,
		success: function(msg){				
			arr = msg.split("|");
			if(arr[0] == "ok"){
				$(".cont_trivia").html(arr[1]);
			}
			else{
				$('#msj_error').html(arr[1]);
			}
		}       
	});
	
	return false;
}

function listarCategorias(id,campo){
	$.ajax({
		type: "POST",
		url: "/bo/catalogo/script-sub-categorias.php",
		data: 'id='+id,
		dataType: 'html',
		beforeSend: function(x){
			//----------------------------
			var combo = campo;
			combo.options.length = 0;
			combo.options[0] = new Option('Cargando...','');
			//----------------------------
			},
		success: function(html){
			//----------------------------
			if (html=='error'){
				var combo = campo;
				combo.options.length = 0;
				combo.options[0] = new Option('Error','');
			}else{
				var combo = campo;
				combo.options.length = 0;
				html = decodeURIComponent(html);
				lineas = html.split("#");
				for (var i=0; i<lineas.length; i++) {
					datos = lineas[i].split("|");
					combo.options[i] = new Option(datos[1], datos[0]);
				}
			}
			//----------------------------
			}
		});
}

function listarCategoriasBuscador(id,campo){
	$.ajax({
		type: "POST",
		url: "/script-sub-categorias.php",
		data: 'id='+id,
		dataType: 'html',
		beforeSend: function(x){
			//----------------------------
			var combo = campo;
			combo.options.length = 0;
			combo.options[0] = new Option('Cargando...','');
			//----------------------------
			},
		success: function(html){
			//----------------------------
			if (html=='error'){
				var combo = campo;
				combo.options.length = 0;
				combo.options[0] = new Option('Error','');
			}else{
				var combo = campo;
				combo.options.length = 0;
				html = decodeURIComponent(html);
				lineas = html.split("#");
				for (var i=0; i<lineas.length; i++) {
					datos = lineas[i].split("|");
					combo.options[i] = new Option(datos[1], datos[0]);
				}
			}
			//----------------------------
			}
		});
}

function irLogin(mail, pass){
	$.ajax({
		type: "POST",
		url: "/script-login.php",
		data: 'mail='+mail+'&pass='+pass,
		dataType: 'html',
		success: function(html){
			//----------------------------
			if (html=='login-si')
			{
				window.location.reload();
			}
			else
			{
				$('#msg-login-error').fadeOut("",function(){
			    	$(this).html(html);
					$(this).fadeIn("slow",function(){$(this).fadeOut(4000);});
				});
			}
			//----------------------------
		}
   });
}

function irLogout(){
	$.ajax({
		url: "/script-logout.php",
		dataType: 'html',
		success: function(html){
			//----------------------------
			if (html=='logout-si')
			{
				window.location.reload();
			}
			//----------------------------
		}
   });
}


function listarComunas(id,campo){
	jQuery.ajax({
		type: "POST",
		url: "/script-comunas.php",
		data: 'id='+id,
		dataType: 'html',
		beforeSend: function(x){
			//----------------------------
			var combo = campo;
			combo.options.length = 0;
			combo.options[0] = new Option('Cargando...','');
			//----------------------------
			},
		success: function(html){
			//----------------------------
			if (html=='error'){
				var combo = campo;
				combo.options.length = 0;
				combo.options[0] = new Option('Error','');
			}else{
				var combo = campo;
				combo.options.length = 0;
				html = decodeURIComponent(html);
				lineas = html.split("#");
				for (var i=0; i<lineas.length; i++) {
					datos = lineas[i].split("|");
					combo.options[i] = new Option(datos[1], datos[0]);
				}
			}
			//----------------------------
			}
		});
}

function cargaJuego(swf,ancho,alto){
	
	$.ajax({
		type: "POST",
		url: "/operaciones_ajax.php",
		data: "tipo=cargaJuego&swf="+swf+"&ancho="+ancho+"&alto="+alto,
		success: function(msg){				
			$(".juego_interno").html(msg);			
		}       
	});	
}

function buscaCumpleaneros(){
	$.ajax({
		type: "POST",
		url: "/operaciones_ajax.php",
		data: "tipo=buscaCumpleaneros&txtBuscado="+trim($("#txtBusquedaCumple").val()),
		success: function(msg){				
			arr = msg.split("|");
			if(arr[0] == "ok"){
				$(".items_cumple").html(arr[1]);
			}				
		}
	});
	return false;		
}

function agregaProducto(producto){
	$.ajax({
		type: "POST",
		url: "/operaciones_ajax.php",
		data: "tipo=agregaProducto&producto="+producto,
		success: function(msg){				
			arr = msg.split("|");
			if(arr[0] == "ok"){
				$(".items_misproductos").html(arr[1]);
			}				
		}
	});	
}

function agregarInvitado(){
	$.ajax({
		type: "POST",
		url: "/operaciones_ajax.php",
		data: "tipo=agregarInvitado&nombre="+$("#txtNombreNew").val()+"&email="+$("#txtEmailNew").val(),
		success: function(msg){				
			$(".invitados").append(msg);
			$("#txtNombreNew").val("");
			$("#txtEmailNew").val("");
		}
	});	
}

function enviaDatosCumpleano(){
	
	var msj = '';
	var foco = '';
	$('#msj_error').html(''); 
	
	if( trim($("#txtNombre").val()) == '' ){
		msj = 'Debes ingresar un nombre para continuar.';
		foco = 'txtNombre';
	}
	else if( !isEmailAddress( trim($("#txtEmail").val()) ) || trim($("#txtEmail").val()) == '' ){
		msj = 'Debes ingresar un email.';
		foco = 'txtEmail';
	}
	
	if(msj == ''){
		
		$.ajax({
			type: "POST",
			url: "/operaciones_ajax.php",
			data: "tipo=enviaDatosCumpleano&nombre="+$("#txtNombre").val()+"&email="+$("#txtEmail").val()+"&dia="+$("#selFechaDia").val()+"&mes="+$("#selFechaMes").val()+"&ano="+$("#selFechaAno").val(),
			success: function(msg){
				arr = msg.split("|");
				if(arr[0] == "error"){
					$('#msj_error').html(arr[1]);
				}
				else {
					$(".paso3_a").fadeOut("slow",function(){
						$(".paso3_b").fadeIn("slow");
						$(".subtitulo-pasos").html('<img src="/images/txt-crea-tu-invitacion.jpg" width="395" height="20">');
					});	
				}
			}
		});	
		
	}
	else {
		$('#msj_error').html(msj);
		$('#'+foco).val('');
		$('#'+foco).focus();
	}
	
}

function enviarInvitaciones(){
	
	var msj = '';
	var foco = '';
	$('#msj_error2').html(''); 
	
	if( trim($("#txtTextoInvitacion").val()) == '' ){
		msj = 'Debes ingresar un comentario en la tarjeta.';
		foco = 'txtTextoInvitacion';
	}
	
	plantilla = $(".contenedor_plantilla img").attr("src");
			
	if(msj == ''){
		
		$.ajax({
			type: "POST",
			url: "/operaciones_ajax.php",
			data: "tipo=enviarInvitaciones&texto="+$("#txtTextoInvitacion").val()+"&plantilla="+plantilla,
			success: function(msg){
				arr = msg.split("|");
				if(arr[0] == "error"){
					$('#msj_error2').html(arr[1]);
				}
				else {
					document.location.href = "/tu-espacio/dijon-kids/tu-cumple/fin/";
				}
			}
		});	
		
	}
	else {
		$('#msj_error2').html(msj);
		$('#'+foco).val('');
		$('#'+foco).focus();
	}	
}

function personalizaTuEcards() {
	
	var urlImg = $(".ecards_interno img").attr("src");
	var idImg = $(".ecards_interno img").attr("id");

	$.ajax({
		type: "POST",
		url: "/operaciones_ajax.php",
		data: "tipo=personalizaTuEcards&imagen="+urlImg+"&idImg="+idImg,
		success: function(msg){
			arr = msg.split("|");
			if(arr[0] == "ok"){
				$(".ecards_interno").css("padding","20px 47px");
				$(".ecards_interno").css("width","496px");    
				$('.ecards_interno').html(arr[1]);
				$("#btnPaso1").hide(0,$("#btnPaso2").show());
			}
		}
	});	
}

function enviaTuEcards(){

	var msj = '';
	var foco = '';
	$('#msj_error').html(''); 
	
	if( trim($("#txtNombreEmisor").val()) == '' ){
		msj = 'Debes ingresar tu nombre.';
		foco = 'txtNombreEmisor';
	}
	else if( trim($("#txtEmailEmisor").val()) == '' || !isEmailAddress( trim($("#txtEmailEmisor").val()) ) ){
		msj = 'Debes ingresar tu email.'; 
		foco = 'txtEmailEmisor';
	}
	else if( trim($("#txtNombreDest1").val()) == '' && trim($("#txtNombreDest2").val()) == '' && trim($("#txtNombreDest3").val()) == '' && trim($("#txtNombreDest4").val()) == '' && trim($("#txtNombreDest5").val()) == ''){
		msj = 'Debes ingresar el nombre de tu amigo.'; 
		foco = 'txtNombreDest1';
	}
	else if( trim($("#txtEmailDest1").val()) == '' && trim($("#txtEmailDest2").val()) == '' && trim($("#txtEmailDest3").val()) == '' && trim($("#txtEmailDest4").val()) == '' && trim($("#txtEmailDest5").val()) == '' ){
		msj = 'Debes ingresar el email de tu amigo.';  
		foco = 'txtEmailDest1';
	}
	else if( !isEmailAddress(trim($("#txtEmailDest1").val())) ){
		msj = 'Debes ingresar el email de tu amigo.';  
		foco = 'txtEmailDest1';
	}
	else if( !isEmailAddress(trim($("#txtEmailDest2").val())) ){
		msj = 'Debes ingresar el email de tu amigo.';  
		foco = 'txtEmailDest2';
	}
	else if( !isEmailAddress(trim($("#txtEmailDest3").val())) ){
		msj = 'Debes ingresar el email de tu amigo.';  
		foco = 'txtEmailDest3';
	}
	else if( !isEmailAddress(trim($("#txtEmailDest4").val())) ){
		msj = 'Debes ingresar el email de tu amigo.';  
		foco = 'txtEmailDest4';
	} 
	else if( !isEmailAddress(trim($("#txtEmailDest5").val())) ){
		msj = 'Debes ingresar el email de tu amigo.';  
		foco = 'txtEmailDest5';
	}
	
	if(msj == ''){
		$.ajax({
			type: "POST",
			url: "/operaciones_ajax.php",
			data: "tipo=enviaTuEcards&"+$("#frmEcards").serialize(),
			success: function(msg){
				arr = msg.split("|");
				if(arr[0] == "error"){
					$('#msj_error').html(arr[1]);
				}
				else {
					$('.ecards_interno').html(arr[1]);
					$("#btnPaso2").hide();
				}
			}
		});	
	}
	else {
		$('#msj_error').html(msj);
		$('#'+foco).val('');
		$('#'+foco).focus();		
	}
	
}





















