/*
 * General Home
 */
function agregar_favoritos(title,url){
	//var title=String(document.title);
	//var url=String(window.location);
	
	if (window.sidebar) // firefox
		window.sidebar.addPanel(title, url, "");
	else if(window.opera && window.print){ // opera
		var elem = document.createElement('a');
		elem.setAttribute('href',href);
		elem.setAttribute('title',title);
		elem.setAttribute('rel','sidebar');
		elem.click();
	} 
	else if(document.all)// ie
		window.external.AddFavorite(url, title);
		else {// otros web Browsers
		alert ("Presione Crtl+D para agregar a este sitio en sus Bookmarks");  
	}
} 
function number_format (number, decimals, dec_point, thousands_sep) {
    number = (number + '').replace(/[^0-9+\-Ee.]/g, '');
    var n = !isFinite(+number) ? 0 : +number,
        prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),        sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,
        dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
        s = '',
        toFixedFix = function (n, prec) {
            var k = Math.pow(10, prec);            return '' + Math.round(n * k) / k;
        };
    // Fix for IE parseFloat(0.55).toFixed(0) = 0;
    s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.');
    if (s[0].length > 3) {        s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep);
    }
    if ((s[1] || '').length < prec) {
        s[1] = s[1] || '';
        s[1] += new Array(prec - s[1].length + 1).join('0');    }
    return s.join(dec);
}
function utf8_decode ( str_data ) {
 
    var tmp_arr = [], i = 0, ac = 0, c1 = 0, c2 = 0, c3 = 0;
 
    str_data += '';
 
    while ( i < str_data.length ) {
        c1 = str_data.charCodeAt(i);
        if (c1 < 128) {
            tmp_arr[ac++] = String.fromCharCode(c1);
            i++;
        } else if ((c1 > 191) && (c1 < 224)) {
            c2 = str_data.charCodeAt(i+1);
            tmp_arr[ac++] = String.fromCharCode(((c1 & 31) << 6) | (c2 & 63));
            i += 2;
        } else {
            c2 = str_data.charCodeAt(i+1);
            c3 = str_data.charCodeAt(i+2);
            tmp_arr[ac++] = String.fromCharCode(((c1 & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
            i += 3;
        }
    }
 
    return tmp_arr.join('');
}
function overTD(td,color,element)
{
	if (color != '') {
		td.bgColor=color;
	}
	if (element != ''){
		document.getElementById(element).style.display="block";	
	}
}
	
function outTD(td,color,element)
{
	td.style.cursor='default';
	if (color != '') {
		td.bgColor=color;
	}
	if (element != ''){
		document.getElementById(element).style.display="none";	
	}
} 

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_showHideLayers() { //v6.0
  var i,p,v,obj,args=MM_showHideLayers.arguments;
  for (i=0; i<(args.length-2); i+=3) if ((obj=MM_findObj(args[i]))!=null) { v=args[i+2];
    if (obj.style) { obj=obj.style; v=(v=='show')?'visible':(v=='hide')?'hidden':v; }
    obj.visibility=v; }
}
function getAbsoluteElementPosition(element) {
if (typeof element == "string")
    element = document.getElementById(element)
  if (!element) return { top:0,left:0 };
  var y = 0;
  var x = 0;
  while (element.offsetParent) {
    x += element.offsetLeft;
    y += element.offsetTop;
    element = element.offsetParent;
  }
  return {top:y,left:x};
}


function checkEmail(email) {
	var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	if (!filter.test(email)) {
		return false;
	} else {
		return true;
	}
}

function mycarousel_initCallback(carousel) {
    jQuery('.control a').bind('click', function() {
        carousel.scroll(jQuery.jcarousel.intval(jQuery(this).text()));
        return false;
    });

    jQuery('.jcarousel-scroll select').bind('change', function() {
        carousel.options.scroll = jQuery.jcarousel.intval(this.options[this.selectedIndex].value);
        return false;
    });
};
//;


function aj(){
    if(window.XMLHttpRequest){
        return new XMLHttpRequest();
    }
    else{
        try{
            return new ActiveXObject('Microsoft.XMLHTTP');
        }catch(e){
            try{
                return new ActiveXObject('Msxml2.XMLHTTP');
            }catch(e){
                alert('tu navegador no soporta ajax');
                return false;
            }
        }
    }
}

function mostrar_header(modificar) {
	
	actualizar = false;
    if (modificar == 'none'){
		obj = document.getElementById('menu-cliente-on');
		obj.style.display = 'none';
		objstyledisplay = obj.style.display;		
		actualizar = true;
	} else if (modificar == 'click'){
		obj = document.getElementById('menu-cliente-on');
		obj.style.display = (obj.style.display=='none') ? 'block' : 'none';
		objstyledisplay = obj.style.display;
		actualizar = true;
	}
	
	if (actualizar)
	{
		var rpc=aj();
		if(rpc){
			rpc.open('POST','includes/mostrar_header.php',true);
			rpc.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');   
			aEnviar = 'mostrar='+objstyledisplay;
			rpc.onreadystatechange=function(){
				if(rpc.readyState==4){
				  document.getElementById('menu-cliente-off').innerHTML = (objstyledisplay=='none') ? '<img src="images/ico-ocultar.png" title="Abrir Cabecera" alt="Abrir Cabecera"/>' : '<img src="images/ico-ocultar.png" title="Cerrar Cabecera" alt="Cerrar Cabecera"/>';
				}
			}
			rpc.send(aEnviar);
		}
	}
}

function subProvincias(valor){
	if(valor > 0){
		var rpc=aj();
   		if(rpc){
	        document.getElementById('provi_domi_campo').innerHTML='<div align="left"><img src="../images/loader.gif" width="25" height="25">';			
			rpc.open("GET",'includes/select_provincias.php?id=' + valor,true);
			rpc.onreadystatechange=function() {
				if (rpc.readyState==4) {
					if(rpc.responseText!='false'){
						document.getElementById('provi_domi_campo').innerHTML = rpc.responseText;
						// edu $('#Provincia_select').attr('display', '').uniform();
						document.getElementById('provi_domi_campo').style.display = "block";
					}else{
						document.getElementById('provi_domi_campo').innerHTML = '';
						document.getElementById('provi_domi_campo').style.display = "none";
					}
				}
			}
			rpc.send(null)
		}
	}else{
		document.getElementById('provi_domi_campo').style.display = "none";
	}
}
function subProvincias_copia(valor,seleccion){
	if(valor > 0){
		var rpc=aj();
   		if(rpc){
	        document.getElementById('provi_domi_campo').innerHTML='<div align="left"><img src="../images/loader.gif" width="25" height="25">';			
			rpc.open("GET",'includes/select_provincias.php?id=' + valor,true);
			rpc.onreadystatechange=function() {
				if (rpc.readyState==4) {
					if(rpc.responseText!='false'){
						document.getElementById('provi_domi_campo').innerHTML = rpc.responseText;
						// edu $('#Provincia_select').attr('display', '').uniform();
						document.getElementById('provi_domi_campo').style.display = "block";
						document.getElementById("Provincia_select").value = seleccion;
					}else{
						document.getElementById('provi_domi_campo').innerHTML = '';
						document.getElementById('provi_domi_campo').style.display = "none";
					}
				}
			}
			rpc.send(null)
		}
	}else{
		document.getElementById('provi_domi_campo').style.display = "none";
	}
}
function subProvincias_f(valor){
	if(valor > 0){
		var rpc=aj();
   		if(rpc){
	        document.getElementById('provi_domi_campo_f').innerHTML='<div align="left"><img src="../images/loader.gif" width="25" height="25">';			
			rpc.open("GET",'includes/select_provincias_f.php?id=' + valor,true);
			rpc.onreadystatechange=function() {
				if (rpc.readyState==4) {
					if(rpc.responseText!='false'){
						document.getElementById('provi_domi_campo_f').innerHTML = rpc.responseText;
						// edu $('#Provincia_select_f').attr('display', '').uniform();
						document.getElementById('provi_domi_campo_f').style.display = "block";
					}else{
						document.getElementById('provi_domi_campo_f').innerHTML = '';
						document.getElementById('provi_domi_campo_f').style.display = "none";
					}
				}
			}
			rpc.send(null)
		}
	}else{
		document.getElementById('provi_domi_campo').style.display = "none";
	}
}

function subMunicipios_f(valor){
	if(valor > 0){
		var rpc=aj();
   		if(rpc){
	        document.getElementById('pobla_domi_campo_f').innerHTML='<div align="left"><img src="../images/loader.gif" width="25" height="25">';			
			rpc.open("GET",'includes/select_municipios_f.php?id=' + valor,true);
			rpc.onreadystatechange=function() {
				if (rpc.readyState==4) {
					if(rpc.responseText!='false'){
						document.getElementById('pobla_domi_campo_f').innerHTML = rpc.responseText;
						// edu $('#Poblacion_select_f').attr('display', '').uniform();
						document.getElementById('pobla_domi_campo_f').style.display = "block";
					}else{
						document.getElementById('pobla_domi_campo_f').innerHTML = '';
						document.getElementById('pobla_domi_campo_f').style.display = "none";
					}
				}	
			}
			rpc.send(null)
		}
	}else{
		document.getElementById('pobla_domi_campo').style.display = "none";
	}
}

function subMunicipios(valor){
	if(valor > 0){
		var rpc=aj();
   		if(rpc){
	        document.getElementById('pobla_domi_campo').innerHTML='<div align="left"><img src="../images/loader.gif" width="25" height="25">';			
			rpc.open("GET",'includes/select_municipios.php?id=' + valor,true);
			rpc.onreadystatechange=function() {
				if (rpc.readyState==4) {
					if(rpc.responseText!='false'){
						document.getElementById('pobla_domi_campo').innerHTML = rpc.responseText;
						// edu $('#Poblacion_select').attr('display', '').uniform();
						document.getElementById('pobla_domi_campo').style.display = "block";
					}else{
						document.getElementById('pobla_domi_campo').innerHTML = '';
						document.getElementById('pobla_domi_campo').style.display = "none";
					}
				}		
			}
			rpc.send(null)
		}
	}else{
		document.getElementById('pobla_domi_campo').style.display = "none";
	}
}
function subMunicipios_copia(valor,seleccion){
	if(valor > 0){
		var rpc=aj();
   		if(rpc){
	        document.getElementById('pobla_domi_campo').innerHTML='<div align="left"><img src="../images/loader.gif" width="25" height="25">';			
			rpc.open("GET",'includes/select_municipios.php?id=' + valor,true);
			rpc.onreadystatechange=function() {
				if (rpc.readyState==4) {
					if(rpc.responseText!='false'){
						document.getElementById('pobla_domi_campo').innerHTML = rpc.responseText;
						// edu $('#Poblacion_select').attr('display', '').uniform();
						document.getElementById('pobla_domi_campo').style.display = "block";
						document.getElementById("Poblacion_select").value = seleccion;						
					}else{
						document.getElementById('pobla_domi_campo').innerHTML = '';
						document.getElementById('pobla_domi_campo').style.display = "none";
					}
				}		
			}
			rpc.send(null)
		}
	}else{
		document.getElementById('pobla_domi_campo').style.display = "none";
	}
}
function subMunicipios_Text(valor){
	if(valor != ''){
		var rpc=aj();
		if(rpc){
			rpc.open("GET",'includes/select_municipios_text.php?id=' + valor,true);
			rpc.onreadystatechange=function() {
			if (rpc.readyState==4) {
				if(rpc.responseText!='false'){
					document.getElementById('pobla_domi_campo').innerHTML = rpc.responseText;
					document.getElementById('pobla_domi_campo').style.display = "block";
				}else{
					document.getElementById('pobla_domi_campo').innerHTML = '';
					document.getElementById('pobla_domi_campo').style.display = "none";
				}
				}					
			}
			rpc.send(null)
		}else{
			document.getElementById('pobla_domi_campo').style.display = "none";
		}
	}
}
function sendAndLoad_boletin(correo){
	var rpc=aj();
    if(rpc){
	//si pudo crearse el objeto, avanzamos (respetar el orden)
		
        rpc.open('POST','registro_boletin.php',true);
        rpc.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        //preparamos las variables a enviar
        //preparamos las variables a enviar
        
		aEnviar = 'correo='+correo;
		
        //creamos una función anónima que sirva de handler
        rpc.onreadystatechange=function(){
            if(rpc.readyState==4){
                //nos conectamos, recibimos y hacemos algo con lo que recibimos si queremos
                //en este caso, mostramos lo que enviamos
				document.getElementById('formulario_boletin').style.visibility="hidden";
				document.getElementById('formulario_boletin').style.display="none";			
				document.getElementById('registro_boletin').style.display='block';
                document.getElementById('registro_boletin').style.color='black';
                document.getElementById('registro_boletin').innerHTML=rpc.responseText;			
            }else{
                //no nos conectamos todavía y mostramos la precarga
                document.getElementById('registro_boletin').style.display='block';
            }
        }
        rpc.send(aEnviar);
    }
}

function sendAndLoad_usuario_cuentas_lista(pedido,estado,pago,registros,orden,orden_dir,pagina){
	var rpc=aj();
    if(rpc){
	//si pudo crearse el objeto, avanzamos (respetar el orden)	
		document.getElementById('div_cuentas_detalle').innerHTML='';	
        document.getElementById('div_cuentas_lista').innerHTML='<div align="left"><img src="../images/loader.gif" width="25" height="25">';
		rpc.open('POST','includes/usuario_mis_cuentas_lista.php',true);
        rpc.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

        aEnviar = 'pedido='+pedido+'&estado='+estado+'&pago='+pago+'&registros='+registros+'&orden='+orden+'&orden_dir='+orden_dir+'&pagina='+pagina;
        //creamos una función anónima que sirva de handler
        rpc.onreadystatechange=function(){
            if(rpc.readyState==4){
			    document.getElementById('div_filtros').style.display = '';				
				document.getElementById('div_cuentas_lista').innerHTML=utf8_decode(rpc.responseText);
            }
        }
        rpc.send(aEnviar);
    }
}
function sendAndLoad_usuario_facturas_lista(pedido,estado,finicio,ffin,registros,orden,orden_dir,pagina){	
	var rpc=aj();
    if(rpc){
	//si pudo crearse el objeto, avanzamos (respetar el orden)	
		document.getElementById('div_facturas_detalle').innerHTML='';	
        document.getElementById('div_facturas_lista').innerHTML='<div align="left"><img src="../images/loader.gif" width="25" height="25">';
		rpc.open('POST','includes/usuario_mis_facturas_lista.php',true);
        rpc.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

        aEnviar = 'pedido='+pedido+'&estado='+estado+'&finicio='+finicio+'&ffin='+ffin+'&registros='+registros+'&orden='+orden+'&orden_dir='+orden_dir+'&pagina='+pagina;
        //creamos una función anónima que sirva de handler
        rpc.onreadystatechange=function(){
            if(rpc.readyState==4){
			    document.getElementById('div_facturas_filtros').style.display = '';				
				document.getElementById('div_facturas_lista').innerHTML=utf8_decode(rpc.responseText);
            }
        }
        rpc.send(aEnviar);
    }
}
function facturas_marcar_facturas(){
	if (document.getElementById('marcar_facturas').checked){	
		var inp=document.getElementsByTagName('input');
		for(var i=0, l=inp.length;i<l;i++){
			if(inp[i].type=='checkbox' && inp[i].name.split('[]')[0]=='imp_factura')
				inp[i].checked=1;
				 //Activamos campo imprimir facturas
				 document.getElementById('img_imp_facturas').style.display = '';					
		}		
	} else {
		var inp=document.getElementsByTagName('input');
		for(var i=0, l=inp.length;i<l;i++){
			if(inp[i].type=='checkbox' && inp[i].name.split('[]')[0]=='imp_factura')
				inp[i].checked=0;
				 //Desactivamos campo imprimir facturas
				 document.getElementById('img_imp_facturas').style.display = 'none';									
		}		
	}
}
function facturas_marcar_facturas_recuperaciones(){
	if (document.getElementById('marcar_facturas_recuperaciones').checked){	
		var inp=document.getElementsByTagName('input');
		for(var i=0, l=inp.length;i<l;i++){
			if(inp[i].type=='checkbox' && inp[i].name.split('[]')[0]=='imp_factura_recuperacion')
				inp[i].checked=1;
				 //Activamos campo imprimir facturas
				 document.getElementById('img_imp_facturas_recuperaciones').style.display = '';					
		}		
	} else {
		var inp=document.getElementsByTagName('input');
		for(var i=0, l=inp.length;i<l;i++){
			if(inp[i].type=='checkbox' && inp[i].name.split('[]')[0]=='imp_factura_recuperacion')
				inp[i].checked=0;				
				 //Desactivamos campo imprimir facturas
				 document.getElementById('img_imp_facturas_recuperaciones').style.display = 'none';									
		}		
	}
}
//Controla si existen varias facturas marcadas para tener el boton de imprimir facturas avtivo
function facturas_control_activacion_imprimir_facturas(facturas_actual_id){
	if (document.getElementById(facturas_actual_id).checked){
		document.getElementById('img_imp_facturas').style.display = '';		
	} else {
		var inp=document.getElementsByTagName('input');
		alguna_factura_activa = false;
		for(var i=0, l=inp.length;i<l;i++){
			if(inp[i].type=='checkbox' && inp[i].name.split('[]')[0]=='imp_factura')
				//alert(inp[i].checked);
				if (inp[i].checked){
					alguna_factura_activa = true;				
				}
		}		
		
		if (!alguna_factura_activa){
			document.getElementById('img_imp_facturas').style.display = 'none';				
		}
	}
}
//Controla si existen varias facturas marcadas para tener el boton de imprimir facturas avtivo
function facturas_control_activacion_imprimir_facturas_recuperaciones(facturas_actual_id){
	if (document.getElementById(facturas_actual_id).checked){
		document.getElementById('img_imp_facturas_recuperaciones').style.display = '';		
	} else {
		var inp=document.getElementsByTagName('input');
		alguna_factura_activa = false;
		for(var i=0, l=inp.length;i<l;i++){
			if(inp[i].type=='checkbox' && inp[i].name.split('[]')[0]=='imp_factura_recuperacion') 
				//alert(inp[i].checked);
				if (inp[i].checked){
					alguna_factura_activa = true;				
				}
			
		}		
		
		if (!alguna_factura_activa){
			document.getElementById('img_imp_facturas_recuperaciones').style.display = 'none';				
		}
	}
}
// Controla la llamada de multiples facturas y recibos
function facturas_llamar_listado_multiples_facturas(tipo_listado,nombre_factura){ 
		if (tipo_listado == 'facturas'){ 
			array_facturas = 'imp_factura';
		} else if (tipo_listado == 'recuperaciones_factura'){ 
			array_facturas = 'imp_factura_recuperacion';				
		} else if (tipo_listado == 'recuperaciones'){ 
			array_facturas = 'imp_recuperacion';
		} else if (tipo_listado == 'incrementos'){ 
			array_facturas = 'imp_incremento';
		}
	 
		var inp=document.getElementsByTagName('input');
		numeros_facturas = '';
		for(var i=0, l=inp.length;i<l;i++){
			if(inp[i].type=='checkbox' && inp[i].name.split('[]')[0]==array_facturas)
				if (inp[i].checked){					
					if (numeros_facturas == ""){
						numeros_facturas = inp[i].value					
					} else {						
						numeros_facturas = numeros_facturas+","+inp[i].value;					
					}
				}
		}	
		parametros = "?facturas="+numeros_facturas+"&tipo_listado="+tipo_listado+"&nombre_factura="+nombre_factura;
		//if (tipo_listado == 'facturas'){
			//$urlFactura =  url_portal+"dompdf/dompdf.php?base_path="+url_portal+"/facturas/&options[Attachment]=0&input_file=getFacturasSel.php#toolbar=0&view=FitH&statusbar=0&messages=0&navpanes=0";			
			//$urlFactura =  url_portal+"dompdf/dompdf.php?base_path=facturas/&filenamee=Facturas-Seleccionadas.pdf&input_file="+url_portal+"facturas/getFacturasSel.php"+parametros;
		$urlFactura =  "includes/usuario_mis_facturas_apdf.php"+parametros;
		window.open($urlFactura);	
		//}		
}
function facturas_llamar_listado_factura(factura,tipo_listado,nombre_factura){ 
	parametros = "?facturas="+factura+"&tipo_listado="+tipo_listado+"&nombre_factura="+nombre_factura;
	$urlFactura =  "includes/usuario_mis_facturas_apdf.php"+parametros;
	window.open($urlFactura);	
}


function facturas_marcar_recuperaciones(){
	if (document.getElementById('marcar_recuperaciones').checked){	
		var inp=document.getElementsByTagName('input');
		for(var i=0, l=inp.length;i<l;i++){
			if(inp[i].type=='checkbox' && inp[i].name.split('[]')[0]=='imp_recuperacion')
				inp[i].checked=1;
				 //Activamos campo imprimir recuperaciones
				 document.getElementById('img_imp_recuperaciones').style.display = '';				
		}		
	} else {
		var inp=document.getElementsByTagName('input');
		for(var i=0, l=inp.length;i<l;i++){
			if(inp[i].type=='checkbox' && inp[i].name.split('[]')[0]=='imp_recuperacion')
				inp[i].checked=0;
				 //Desactivamos campo imprimir recuperaciones
				 document.getElementById('img_imp_recuperaciones').style.display = 'none';								
		}		
	}
}
function facturas_control_activacion_imprimir_recuperaciones(recuperacion_actual_id){
	if (document.getElementById(recuperacion_actual_id).checked){
		document.getElementById('img_imp_recuperaciones').style.display = '';		
	} else {
		var inp=document.getElementsByTagName('input');
		alguna_factura_activa = false;
		for(var i=0, l=inp.length;i<l;i++){
			if(inp[i].type=='checkbox' && inp[i].name.split('[]')[0]=='imp_recuperacion')
				//alert(inp[i].checked);
				if (inp[i].checked){
					alguna_factura_activa = true;				
				}
		}		
		
		if (!alguna_factura_activa){
			document.getElementById('img_imp_recuperaciones').style.display = 'none';				
		}
	}
}

function facturas_marcar_incrementos(){
	if (document.getElementById('marcar_incrementos').checked){	
		var inp=document.getElementsByTagName('input');
		for(var i=0, l=inp.length;i<l;i++){
			if(inp[i].type=='checkbox' && inp[i].name.split('[]')[0]=='imp_incremento')
				inp[i].checked=1;				
				 //Activamos campo imprimir incrementos
				 document.getElementById('img_imp_incrementos').style.display = '';					
		}		
	} else {
		var inp=document.getElementsByTagName('input');
		for(var i=0, l=inp.length;i<l;i++){
			if(inp[i].type=='checkbox' && inp[i].name.split('[]')[0]=='imp_incremento')
				inp[i].checked=0;
				 //Desactivamos campo imprimir incrementos
				 document.getElementById('img_imp_incrementos').style.display = 'none';				
		}		
	}
}
function facturas_control_activacion_imprimir_incrementos(incremento_actual_id){
	if (document.getElementById(incremento_actual_id).checked){
		document.getElementById('img_imp_incrementos').style.display = '';		
	} else {
		var inp=document.getElementsByTagName('input');
		alguna_factura_activa = false;
		for(var i=0, l=inp.length;i<l;i++){
			if(inp[i].type=='checkbox' && inp[i].name.split('[]')[0]=='imp_incremento')
				//alert(inp[i].checked);
				if (inp[i].checked){
					alguna_factura_activa = true;				
				}
		}		
		
		if (!alguna_factura_activa){
			document.getElementById('img_imp_incrementos').style.display = 'none';				
		}
	}
}

function sendAndLoad_usuario_cuentas_detalle(pedido,idUsuario){	
	var rpc=aj();
    if(rpc){
	//si pudo crearse el objeto, avanzamos (respetar el orden)	
		document.getElementById('div_cuentas_lista').innerHTML='';
        document.getElementById('div_cuentas_detalle').innerHTML='<div align="left"><img src="../images/loader.gif" width="25" height="25">';
		rpc.open('POST','includes/usuario_mis_pedidos_detalle.php',true); //Hacemos servir el mismo que el pedido
        rpc.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

        aEnviar = 'pedido='+pedido+'&pantalla=cuentas';
        //creamos una función anónima que sirva de handler
        rpc.onreadystatechange=function(){
            if(rpc.readyState==4){			   
				document.getElementById('div_filtros').style.display = 'none';				
				document.getElementById('div_cuentas_detalle').innerHTML=rpc.responseText;				
            }
        }
        rpc.send(aEnviar);
		
    }
}


function sendAndLoad_modificar_contrasena(antigua, nueva , nueva2){
    sin_error = true;
	
	document.getElementById("ok_datos").style.display = 'none'; 	
	document.getElementById("error_datos").style.display = 'none'; 	
	document.getElementById("antigua_obligatorio").style.display = 'none'; 
    document.getElementById("antigua").style.borderColor="";	
    document.getElementById("nueva_obligatorio").style.display = 'none';  
    document.getElementById("nueva").style.borderColor="";	
    document.getElementById("nueva2_obligatorio").style.display = 'none';  
    document.getElementById("nueva2").style.borderColor="";		

	if (antigua == '') {
		document.getElementById("antigua").style.borderColor="red";
		document.getElementById("antigua_obligatorio").style.display = '';  					
		sin_error = false;
	} 
	if (nueva == '') {
		document.getElementById("nueva").style.borderColor="red";
		document.getElementById("nueva_obligatorio").style.display = '';  					
		sin_error = false;
	}
	if (nueva2 == '') {
		document.getElementById("nueva2").style.borderColor="red";
		document.getElementById("nueva2_obligatorio").style.display = '';  					
		sin_error = false;
	}	
	if (nueva != nueva2){
		document.getElementById("error_datos").style.display = ''; 	
		document.getElementById("error_datos").innerHTML="La contrase&#241;a y la repetici&#243;n de la contrase&#241;a s&#243;n diferentes";
		sin_error = false;
	}

	if (sin_error){
		antigua_md5 = hex_md5(antigua);
		nueva_md5 = hex_md5(nueva);	

		var rpc=aj();
		if(rpc){		
			document.getElementById('loader').innerHTML='<img src="../images/loader.gif" width="16" height="16">';
			rpc.open('POST','includes/usuario_mis_datos_contrasena_modificar.php',true);
			rpc.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
			aEnviar = 'antigua_md5='+antigua_md5+'&nueva_md5='+nueva_md5;						
			rpc.onreadystatechange=function(){
				if(rpc.readyState==4){
					if (rpc.responseText == 1){							
						document.getElementById("ok_datos").style.display = '';  					
					} else {
						document.getElementById("error_datos").style.display = '';
						document.getElementById("error_datos").innerHTML = 'La contrase&#241;a actual &#233;s incorrecta'; 					
					}
					document.getElementById('loader').innerHTML='';
				}
			}	
			rpc.send(aEnviar);
		}
	}
}


function sendAndLoad_usuario_pedidos_lista(pedido,estado,envio,pago,registros,orden,orden_dir,pagina){	
	var rpc=aj();
    if(rpc){
	//si pudo crearse el objeto, avanzamos (respetar el orden)	
		document.getElementById('div_pedidos_detalle').innerHTML='';
        document.getElementById('div_pedidos_lista').innerHTML='<div align="left"><img src="../images/loader.gif" width="25" height="25">';
		rpc.open('POST','includes/usuario_mis_pedidos_lista.php',true);
        rpc.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

        aEnviar = 'pedido='+pedido+'&estado='+estado+'&envio='+envio+'&pago='+pago+'&registros='+registros+'&orden='+orden+'&orden_dir='+orden_dir+'&pagina='+pagina;
        //creamos una función anónima que sirva de handler
        rpc.onreadystatechange=function(){
            if(rpc.readyState==4){
				document.getElementById('div_filtros').style.display = ''; 			
				document.getElementById('div_pedidos_lista').innerHTML=utf8_decode(rpc.responseText);				
            }
        }
        rpc.send(aEnviar);
    }
}

function sendAndLoad_usuario_pedidos_detalle(pedido,div_filtros,div_lista,div_detalle){	
	var rpc=aj();
    if(rpc){
	//si pudo crearse el objeto, avanzamos (respetar el orden)	
		document.getElementById(div_lista).innerHTML='';
        document.getElementById(div_detalle).innerHTML='<div align="left"><img src="../images/loader.gif" width="25" height="25">';
		rpc.open('POST','includes/usuario_mis_pedidos_detalle.php',true);
        rpc.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        aEnviar = 'pedido='+pedido+'&pantalla='+div_detalle;
        //creamos una función anónima que sirva de handler
        rpc.onreadystatechange=function(){
            if(rpc.readyState==4){
			    document.getElementById(div_filtros).style.display = 'none';
				document.getElementById(div_detalle).innerHTML=rpc.responseText;					
            }
        }
        rpc.send(aEnviar);	
    }
}

function sendAndLoad_usuario_Cancelar_Pedido(idPedido,pedido,estado,pago,registros,pagina){
	if(confirm("¿Estás seguro que desea cancelar el pedido?")){
		var rpc=aj();
		if(rpc){
		//si pudo crearse el objeto, avanzamos (respetar el orden)	
			//document.getElementById('div_pedidos_lista').innerHTML='<div align="left"><img src="../images/loader.gif" width="25" height="25">';
			rpc.open('POST','includes/usuario_mis_pedidos_cancelar_pedido.php',true);
			rpc.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
			aEnviar = 'pedido='+idPedido;
			//creamos una función anónima que sirva de handler
			rpc.onreadystatechange=function(){
				if(rpc.readyState==4){
					 document.getElementById('pedido_cancelado_'+idPedido).style.display = '';
					 document.getElementById('pedido_cancelar_'+idPedido).style.display = 'none';
					 //sendAndLoad_usuario_pedidos_lista(pedido,estado,pago,registros,pagina);
				}
			}
			rpc.send(aEnviar);
		}		
	} else {
		return false;	
	}
}

function sendAndLoad_modificar_datos_configuraciones(p_campo, p_valor){
	var rpc=aj();
	rpc.open("POST",'includes/usuario_mis_configuraciones_modificar_datos.php',true);
	
	document.getElementById('campo_'+p_campo).innerHTML='<div align="left"><img src="../images/loader.gif" width="15" height="15">';		
	
	rpc.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	aEnviar = 'p_campo='+p_campo+'&p_valor='+p_valor;
	rpc.onreadystatechange=function(){
		if(rpc.readyState==4){
			//alert (rpc.responseText);
			if (p_campo == 'color_fondo'){
				document.getElementById('campo_'+p_campo).innerHTML='#'+p_valor;
				document.getElementById('datos_tienda_'+p_campo).value='#'+p_valor;
				document.getElementById('table_'+p_campo).bgColor='#'+p_valor;
			} else {
				document.getElementById('campo_'+p_campo).innerHTML=rpc.responseText;	
				MM_showHideLayers('div_editar_campo','','hide');
			}			
			//location.reload(true);
		}
	}
	rpc.send(aEnviar); 
}

function sendAndLoad_modificar_datos_configuraciones_checks(p_valor,p_opcion){	
	var rpc=aj();
	if (p_opcion == 'rating'){
		document.getElementById('check_rating_pensando').style.display = ''; 
		document.getElementById('check_rating').style.display = 'none'; 		
	} else if (p_opcion == 'comenfacebook'){
		document.getElementById('check_comentarios_facebook_pensando').style.display = ''; 
		document.getElementById('check_comentarios_facebook').style.display = 'none'; 		
	}
	if (p_valor){p_valor = 1} else {p_valor = 0}

	rpc.open('POST','includes/usuario_mis_configuraciones_modificar_check.php',true);	
	rpc.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	aEnviar = 'p_valor='+p_valor+'&p_opcion='+p_opcion;
	rpc.onreadystatechange=function(){
		if(rpc.readyState==4){
				if (p_opcion == 'rating'){
					document.getElementById('check_rating_pensando').style.display = 'none'; 
					document.getElementById('check_rating').style.display = ''; 		
				} else if (p_opcion == 'comenfacebook'){
					document.getElementById('check_comentarios_facebook_pensando').style.display = 'none'; 
					document.getElementById('check_comentarios_facebook').style.display = ''; 		
				}
		}
	}
	rpc.send(aEnviar); 
}



function sendAndLoad_intercambios_lista(){ 
	var rpc=aj();
	if(rpc){
	//si pudo crearse el objeto, avanzamos (respetar el orden)	
		document.getElementById('usuario_intercambios_lista').innerHTML='<div align="left"><img src="../images/loader.gif" width="25" height="25">';
		rpc.open('POST','includes/usuario_mis_intercambios_lista.php',true);
		rpc.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

		//aEnviar = 'pedido='+idPedido;
		aEnviar = '';
		//creamos una función anónima que sirva de handler
		rpc.onreadystatechange=function(){
			if(rpc.readyState==4){
				 document.getElementById('usuario_intercambios_lista').innerHTML=rpc.responseText;
			}
		}
		rpc.send(aEnviar);
	}		
}


function intercambios_eliminar(intercambio_id){
	var rpc=aj();
	if(rpc)
	{
		rpc.open("POST",'includes/usuario_mis_intercambios_eliminar.php',true);
		rpc.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		aEnviar = 'intercambio_id='+intercambio_id;
	
		rpc.onreadystatechange=function(){
			if(rpc.readyState==4){
				//alert (xmlHttp.responseText);
				sendAndLoad_intercambios_lista();
			}
		}
		rpc.send(aEnviar); 
	}
}


function intercambios_up(intercambio_id, intercambio_orden){
	var rpc=aj();
	if(rpc){
		rpc.open("POST",'includes/usuario_mis_intercambios_up.php',true);
		rpc.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		aEnviar = 'intercambio_id='+intercambio_id+'&intercambio_orden='+intercambio_orden;
	
		rpc.onreadystatechange=function(){
			if(rpc.readyState==4){
				//alert (rpc.responseText);
				sendAndLoad_intercambios_lista();
			}
		}
		rpc.send(aEnviar); 
	}
}

function intercambios_down(intercambio_id, intercambio_orden){
	var rpc=aj();
	if(rpc){	
		rpc.open("POST",'includes/usuario_mis_intercambios_down.php',true);
		rpc.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		aEnviar = 'intercambio_id='+intercambio_id+'&intercambio_orden='+intercambio_orden;
	
		rpc.onreadystatechange=function(){
			if(rpc.readyState==4){
				//alert (rpc.responseText);
				sendAndLoad_intercambios_lista();
			}
		}
		rpc.send(aEnviar); 
	}
}

function sendAndLoad_modificar_intercambio(id, pagina, url){
	var rpc=aj();
    if(rpc){			
		document.getElementById('campo_intercambio_'+id).innerHTML='<div align="left"><img src="../images/loader.gif" width="15" height="15">';
		rpc.open('POST','includes/usuario_mis_intercambios_modificar.php',true);
        rpc.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		var aEnviar='';
		aEnviar = 'id='+id+'&pagina='+pagina+'&url='+url;		
		//creamos una función anónima que sirva de handler
		rpc.onreadystatechange=function(){
			if(rpc.readyState==4){
				//alert(rpc.responseText);
				//document.getElementById('campo_intercambio_'+id).innerHTML=rpc.responseText;					
				sendAndLoad_intercambios_lista();
			}
			MM_showHideLayers('div_editar_intercambio','','hide');
		}	
		rpc.send(aEnviar);
	}
}

function sendAndLoad_alta_intercambio(pagina, url){
	var rpc=aj();
    if(rpc){			
		rpc.open('POST','includes/usuario_mis_intercambios_alta.php',true);
        rpc.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		//var aEnviar='';
		aEnviar = 'pagina='+pagina+'&url='+url;		
		//creamos una función anónima que sirva de handler
		rpc.onreadystatechange=function(){
			if(rpc.readyState==4){
				//alert(rpc.responseText);
				//document.getElementById('campo_intercambio_'+id).innerHTML=rpc.responseText;					
				sendAndLoad_intercambios_lista();
			}
			MM_showHideLayers('div_alta_intercambio','','hide');
		}	
		rpc.send(aEnviar);
	}
}

function carga_editar_campo_configuraciones(campo) {
	var elemento = document.getElementById('campo_'+campo);
	var pos = getAbsoluteElementPosition(elemento)
	document.getElementById('div_editar_campo').style.top=pos.top+"px";
	document.getElementById('div_editar_campo').style.left=pos.left+"px";
	document.getElementById('p_edit_campo').value=document.getElementById('campo_'+campo).innerHTML;
	document.getElementById('p_id').value=campo;
}

function carga_editar_intercambio(campo, pagina, url) {
	var elemento = document.getElementById('campo_intercambio_'+campo);
	var pos = getAbsoluteElementPosition(elemento)
	document.getElementById('div_editar_intercambio').style.top=pos.top+"px";
	document.getElementById('div_editar_intercambio').style.left=pos.left+"px";
	document.getElementById('p_intercambio_pagina').value=pagina;
	document.getElementById('p_intercambio_url').value=url;	
	document.getElementById('p_id').value=campo;
}
function carga_alta_intercambio() {
	var elemento = document.getElementById('src_campo_alta_intercambio');
	var pos = getAbsoluteElementPosition(elemento)
	document.getElementById('div_alta_intercambio').style.top=pos.top+"px";
	document.getElementById('div_alta_intercambio').style.left=pos.left+"px";
	document.getElementById('p_intercambio_pagina_alta').value='';
	document.getElementById('p_intercambio_url_alta').value='';	
}

function carga_ver_mensaje(id, origen, destino, asunto,leido) {
	document.getElementById('p_mensaje_ver_origen').value=origen;
	document.getElementById('p_mensaje_ver_destino').value=destino;
	document.getElementById('p_mensaje_ver_asunto').value=asunto;
	document.getElementById('p_mensaje_ver_contenido').value=document.getElementById('p_crm_men_contenido_'+id).value;			
	document.getElementById('p_mensaje_ver_leido').value=leido;
	document.getElementById('p_ver_id').value=id;	
}
function carga_responder_mensaje(id, origen, destino, asunto) {
	document.getElementById('p_mensaje_responder_origen').value=origen;
	document.getElementById('p_mensaje_responder_destino').value=destino;
	document.getElementById('p_mensaje_responder_asunto').value="Re: "+asunto;
	document.getElementById('p_mensaje_responder_contenido').value="";	
	document.getElementById('p_responder_id').value=id;
	//Limpiamos de errores
    document.getElementById("p_mensaje_responder_contenido_obligatorio").style.display = 'none'; 
    document.getElementById("p_mensaje_responder_contenido").style.borderColor="";		
}
function carga_enviar_mensaje(origen) {
	document.getElementById('p_mensaje_enviar_origen').value=origen;	
	document.getElementById('p_mensaje_enviar_asunto').value="";
	document.getElementById('p_mensaje_enviar_contenido').value="";	
    //Limpiamos de errores
    document.getElementById("p_mensaje_enviar_destino_obligatorio").style.display = 'none'; 
    document.getElementById("p_mensaje_enviar_destino").style.borderColor="";	
    document.getElementById("p_mensaje_enviar_asunto_obligatorio").style.display = 'none'; 
    document.getElementById("p_mensaje_enviar_asunto").style.borderColor="";	
    document.getElementById("p_mensaje_enviar_contenido_obligatorio").style.display = 'none'; 
    document.getElementById("p_mensaje_enviar_contenido").style.borderColor="";	
}

function carga_enviar_mensaje_pedidos(id_pedido, origen, destino) {
	document.getElementById('p_mensaje_enviar_origen').value=origen;
	document.getElementById('p_mensaje_enviar_destino').value=destino;
	document.getElementById('p_mensaje_enviar_asunto').value="Pedido "+id_pedido;
	document.getElementById('p_mensaje_enviar_contenido').value="";	
	//Limpiamos de errores
    document.getElementById("p_mensaje_enviar_contenido_obligatorio").style.display = 'none'; 
    document.getElementById("p_mensaje_enviar_contenido").style.borderColor="";		
}

function carga_enviar_mensaje_producto(referencia, origen, destino) {
	document.getElementById('p_mensaje_enviar_origen').value=origen;
	document.getElementById('p_mensaje_enviar_destino').value=destino;
	document.getElementById('p_mensaje_enviar_asunto').value="Referencia "+referencia;
	document.getElementById('p_mensaje_enviar_contenido').value="";	
	//Limpiamos de errores
    document.getElementById("p_mensaje_enviar_contenido_obligatorio").style.display = 'none'; 
    document.getElementById("p_mensaje_enviar_contenido").style.borderColor="";		
}


function carga_enviar_mensaje_rma(id_rma, origen, destino) {
	document.getElementById('p_mensaje_enviar_origen').value=origen;
	document.getElementById('p_mensaje_enviar_destino').value=destino;
	document.getElementById('p_mensaje_enviar_asunto').value="Reclamacion "+id_rma;
	document.getElementById('p_mensaje_enviar_contenido').value="";	
	//Limpiamos de errores
    document.getElementById("p_mensaje_enviar_contenido_obligatorio").style.display = 'none'; 
    document.getElementById("p_mensaje_enviar_contenido").style.borderColor="";		
}

function carga_enviar_rma_pedidos(id_pedido) {
	document.getElementById('p_pedido_rma_id_texto').value="Pedido "+id_pedido;
	document.getElementById('p_pedido_rma_id').value=id_pedido;
	document.getElementById('p_pedido_rma_contenido').value="";	
	//Limpiamos de errores
    document.getElementById("p_pedido_rma_tipo_obligatorio").style.display = 'none'; 
    document.getElementById("p_pedido_rma_tipo").style.borderColor="";		
    document.getElementById("p_pedido_rma_contenido_obligatorio").style.display = 'none'; 
    document.getElementById("p_pedido_rma_contenido").style.borderColor="";		
}


function sendAndLoad_mensajes_lista(mensaje, usuario_destino,estado,registros,orden,orden_dir,pagina){	
	var rpc=aj();
    if(rpc){
		//si pudo crearse el objeto, avanzamos (respetar el orden)	
		//document.getElementById('div_pedidos_detalle').innerHTML='';
        document.getElementById('div_mensajes_lista').innerHTML='<div align="left"><img src="../images/loader.gif" width="25" height="25">';
		rpc.open('POST','includes/usuario_mis_mensajes_lista.php',true);
        rpc.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

        aEnviar = 'mensaje='+mensaje+'&usuario_destino='+usuario_destino+'&estado='+estado+'&registros='+registros+'&orden='+orden+'&orden_dir='+orden_dir+'&pagina='+pagina;
        //creamos una función anónima que sirva de handler
        rpc.onreadystatechange=function(){
            if(rpc.readyState==4){
				document.getElementById('div_filtros').style.display = ''; 			
				document.getElementById('div_mensajes_lista').innerHTML=rpc.responseText;				
            }
        }
        rpc.send(aEnviar);
    }
}

function sendAndLoad_ver_mensaje(men_id){
	var rpc=aj();
    if(rpc){			
		//document.getElementById('mensaje_estado_'+men_id).innerHTML='<div align="left"><img src="../images/loader.gif" width="15" height="15">';				
		
		rpc.open('POST','includes/usuario_mis_mensajes_modificar_visto.php',true);
        rpc.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		aEnviar = 'men_id='+men_id;			
		rpc.onreadystatechange=function(){
			if(rpc.readyState==4){
				//document.getElementById('campo_intercambio_'+id).innerHTML=rpc.responseText;					
				if  (rpc.responseText != ''){
					document.getElementById('mensaje_estado_'+men_id).innerHTML = '<img src="img/ico_mail_open.png" title="Mensaje Leido" alt="Mensaje Leido" />';
					if (rpc.responseText == 0){
					    document.getElementById('li_mensajes_no_leidos').innerHTML = '<a href="/mis-mensajes.html"><img src="images/ico-mensajes-off.png" width="16" height="16" class="imgico" />Mis Mensajes <strong>('+rpc.responseText+')</strong></a>';
					    document.getElementById('div_menu_num_mensajes_no_leidos').innerHTML = '';
					} else {
					    document.getElementById('li_mensajes_no_leidos').innerHTML = '<a href="/mis-mensajes.html"><img src="images/ico-mensajes-on.png" width="16" height="16" class="imgico" />Mis Mensajes <strong>('+rpc.responseText+')</strong></a>';						
					    document.getElementById('menu_num_mensajes_no_leidos').value = rpc.responseText;
					}
				}
			}
			MM_showHideLayers('div_ver_mensaje','','hide');
		}	
		rpc.send(aEnviar);
	}
}
function sendAndLoad_responder_mensaje(men_id, men_asunto, men_contenido){
	sin_error = true;
	if (men_contenido == '') {
		document.getElementById("p_mensaje_responder_contenido").style.borderColor="red";
		document.getElementById("p_mensaje_responder_contenido_obligatorio").style.display = '';  										
		sin_error = false;
	} 
	
	if (sin_error)
	{ 
		var rpc=aj();
		if(rpc){				
			rpc.open('POST','includes/usuario_mis_mensajes_responder.php',true);
			rpc.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
			aEnviar = 'men_id='+men_id+'&men_asunto='+men_asunto+'&men_contenido='+men_contenido;						
			rpc.onreadystatechange=function(){
				if(rpc.readyState==4){
					//alert(rpc.responseText);
					//document.getElementById('campo_intercambio_'+id).innerHTML=rpc.responseText;					
					//document.getElementById('mensaje_estado_'+men_id).innerHTML = rpc.responseText;
					$().colorbox({width:"auto", height:"auto", inline:true, href:"#div_responder_mensaje_result"});
					sendAndLoad_mensajes_lista('0','0','0',20,'Fecha','Desc','0');
				}
				//MM_showHideLayers('div_responder_mensaje','','hide');
			}	
			rpc.send(aEnviar);
		}
	}		
}


function subTipo_enviar_mensaje(valor){
	if(valor > 0){
		var rpc=aj();
   		if(rpc){
	        document.getElementById('div_sub_tipo_mensaje').innerHTML='<div align="left"><img src="../images/loader.gif" width="25" height="25">';			
			rpc.open("GET",'includes/select_tipo_enviar_mensaje.php?id=' + valor,true);
			rpc.onreadystatechange=function() {
				if (rpc.readyState==4) {
					if(rpc.responseText!='false'){
						document.getElementById('div_sub_tipo_mensaje').innerHTML = rpc.responseText;
						document.getElementById('div_sub_tipo_mensaje').style.display = "block";
					}else{
						document.getElementById('div_sub_tipo_mensaje').innerHTML = '';
						document.getElementById('div_sub_tipo_mensaje').style.display = "none";
					}
				}
			}
			rpc.send(null)
		}
	}else{
		document.getElementById('provi_domi_campo').style.display = "none";
	}
}
function sendAndLoad_cliente_enviar_mensaje(men_nombre, men_correo, men_asunto, men_mensaje, men_tipo, men_sub_tipo){
	sin_error = true;
	if ((men_nombre == '') || (men_correo == '') || (men_asunto == '') || (men_mensaje == '') || (men_tipo == '0')){
		document.getElementById("error_envio_mensaje").style.display='';
		sin_error = false;
	} 
	
	if (sin_error)
	{ 
		var rpc=aj();
		if(rpc){					
			rpc.open('POST','/includes/usuario_mail_cliente_contacto.php',true);
			rpc.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
			aEnviar = 'men_nombre='+men_nombre+'&men_correo='+men_correo+'&men_asunto='+men_asunto+'&men_mensaje='+men_mensaje+'&men_tipo='+men_tipo+'&men_sub_tipo='+men_sub_tipo;						
			rpc.onreadystatechange=function(){
				if(rpc.readyState==4){
					$().colorbox({width:"auto", height:"auto", inline:true, href:"#div_contacto_result"});
				}
			}	
			rpc.send(aEnviar);
		}
	}	
}


function sendAndLoad_eliminar_mensaje(men_id){
	if (confirm('¿Esta seguro de que desea borrar este Mensaje?')){
		var rpc=aj();
		if(rpc){				
			rpc.open('POST','includes/usuario_mis_mensajes_eliminar.php',true);
			rpc.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
			aEnviar = 'men_id='+men_id;						
			rpc.onreadystatechange=function(){
				if(rpc.readyState==4){
					//alert(rpc.responseText);
					sendAndLoad_mensajes_lista('0','0','0',20,'Fecha','Desc','0');			
				}				 
			}	
			rpc.send(aEnviar);
		}
	}
}

function sendAndLoad_anadir_a_favoritos(producto_id,anadir){
	var rpc=aj();
	if(rpc){		
        document.getElementById('li_anadir_a_favoritos').innerHTML='<div align="left"><img src="../images/loader.gif" width="16" height="16">';
		rpc.open('POST','anadir_a_favoritos.php',true);
		rpc.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		aEnviar = 'producto_id='+producto_id+'&anadir='+anadir;						
		rpc.onreadystatechange=function(){
			if(rpc.readyState==4){
				if (anadir == 1){
					document.getElementById('li_anadir_a_favoritos').innerHTML = '<a href="" onclick="sendAndLoad_anadir_a_favoritos('+producto_id+',0); return false;" class="favorificha-on">En Favoritos</a>';
				} else {
					document.getElementById('li_anadir_a_favoritos').innerHTML = '<a href="" onclick="sendAndLoad_anadir_a_favoritos('+producto_id+',1); return false;" class="favorificha-off">A&ntilde;adir a Favoritos</a>';					
				}
			}
		}	
		rpc.send(aEnviar);
	}
}

function sendAndLoad_anadir_a_avisar(producto_id,anadir){
	var rpc=aj();
	if(rpc){		
        document.getElementById('li_anadir_a_avisar').innerHTML='<div align="left"><img src="../images/loader.gif" width="16" height="16">';
		rpc.open('POST','anadir_a_avisar.php',true);
		rpc.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		aEnviar = 'producto_id='+producto_id+'&anadir='+anadir;						
		rpc.onreadystatechange=function(){
			if(rpc.readyState==4){
				if (anadir == 1){
					//alert(rpc.responseText);
					document.getElementById('li_anadir_a_avisar').innerHTML = '<a href="" onclick="sendAndLoad_anadir_a_avisar('+producto_id+',0); return false;" class="botonx botonx-220 producto-botonx-reponer-ok"><div><div>Aviso a&ntilde;adido</div></div></a>';
				} else {
					document.getElementById('li_anadir_a_avisar').innerHTML = '<a href="" onclick="sendAndLoad_anadir_a_avisar('+producto_id+',1); return false;"class="botonx botonx-220 producto-botonx-reponer"><div><div>Avisar al reponer</div></div></a>';					
				}
			}
		}	
		rpc.send(aEnviar);
	}
}

function sendAndLoad_usuario_pedidos_rma_lista(rma,estado,tipo,registros,orden,orden_dir,pagina){
	var rpc=aj();
    if(rpc){
	//si pudo crearse el objeto, avanzamos (respetar el orden)	
		document.getElementById('div_pedidos_rma_detalle').innerHTML='';
        document.getElementById('div_pedidos_rma_lista').innerHTML='<div align="left"><img src="../images/loader.gif" width="25" height="25">';
		rpc.open('POST','includes/usuario_mis_rma_lista.php',true);
        rpc.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

        aEnviar = 'rma='+rma+'&estado='+estado+'&tipo='+tipo+'&registros='+registros+'&orden='+orden+'&orden_dir='+orden_dir+'&pagina='+pagina;
        //creamos una función anónima que sirva de handler
        rpc.onreadystatechange=function(){
            if(rpc.readyState==4){
				document.getElementById('div_filtros_rma').style.display = ''; 			
				document.getElementById('div_pedidos_rma_lista').innerHTML=utf8_decode(rpc.responseText);				
            }
        }
        rpc.send(aEnviar);
    }
}
//UPDATE crm_usuarios_datos_tienda SET usudt_color_fondo = 'Club2e23 2' WHERE usudt_id =1 
function usuario_darmeBaja(idUsuario){
	if(confirm("¿Está seguro de desea darse de baja del sistema?\n\nNo tendrá marcha atrás y todos tus pedidos serán eliminados.")){
		document.location.href = 'baja.php?idUsuario='+idUsuario;
	}
}

function sendAndLoad_cantidad_carrito(key,precio,accion,iva,descuento,tarjeta,pedido_minimo,stock,dias_entrega){
		ejecutar_funciones = true;
		cantidad_productos = parseInt(document.getElementById('id_cantidad_'+key).value);
		
        try{ var envolver_cantidad = document.getElementById('id_envolver_'+key).value; }
		catch(err)
		{ var envolver_cantidad=0; }			
		
		if (((cantidad_productos == 1) && (accion == 'restar')) || (accion == 'borrar')){
			if(!confirm(" Esta seguro de borrar el producto del carrito")){
				return false;
			} else {
				accion = 'borrar';	
			}
		} 
		if ((cantidad_productos >= stock && dias_entrega == 0 ) && (accion == 'sumar')){
			 alert("No hay suficiente stock para este producto");		
			 return false;	
		/*} else if ((cantidad_productos >= stock && dias_entrega > 0 ) && (accion == 'sumar')){			 
			 alert("No hay suficiente stock para este producto, su pedido sera entregado en "+dias_entrega+" dias");		
		} else if ((cantidad_productos >= stock && dias_entrega > 0 ) && (accion == 'cantidad')){			 
			 alert("No hay suficiente stock para este producto, su pedido sera entregado en "+dias_entrega+" dias");		
		*/
		}
	
		if (isNaN(cantidad_productos)){
			alert('Ha de ser un valor correcto');
			return false;
		}

		if ((cantidad_productos <= 0) && (accion == 'cantidad')){
			if(!confirm(" Esta seguro de borrar el producto del carrito")){
				return false;
			} else {
				accion = 'borrar';	
			}
		}		
		if (ejecutar_funciones){	
				var rpc=aj();
				if(rpc){
					//si pudo crearse el objeto, avanzamos (respetar el orden)	
					//document.getElementById('div_pedidos_rma_detalle').innerHTML='';
					//document.getElementById('div_pedidos_rma_lista').innerHTML='<div align="left"><img src="../images/loader.gif" width="25" height="25">';
					rpc.open('POST','includes/carrito_ajax.php',true);
					rpc.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');			
					aEnviar = 'key='+key+'&accion='+accion+'&cantidad_productos='+cantidad_productos+'&stock='+stock+'&envolver_cantidad='+envolver_cantidad+'&dias_entrega='+dias_entrega;
					//creamos una función anónima que sirva de handler
					rpc.onreadystatechange=function(){
						if(rpc.readyState==4){
							var resultados = rpc.responseText.split("@");
							cantidad=parseInt(resultados[0]);							
							cantidad_antigua=parseInt(resultados[1]);
							//QUITAMOS TARJETA SI ES NECESARIO
							quitar_tarjeta=resultados[2];
							if (quitar_tarjeta == 's'){
								location.href = location.href
							}
							//	
							if ((stock == 0 && dias_entrega == 0 ) && (accion == 'sumar')){
								 alert("No hay suficiente stock para este producto");
								 document.getElementById('id_cantidad_'+key).value = cantidad_antigua;		
								 return false;	
							}							
							
							if ((envolver_cantidad > 0) && (cantidad_productos > 1) && (cantidad_productos < envolver_cantidad))
							{
								alert ('La cantidad de productos no puede ser inferior a los productos a envolver');							
								document.getElementById('id_cantidad_'+key).value = cantidad_antigua;
								return false;	
							}
							if ((envolver_cantidad == cantidad_productos) && (accion == 'restar'))
							{
								alert ('La cantidad de productos no puede ser inferior a los productos a envolver');							
								document.getElementById('id_cantidad_'+key).value = cantidad_antigua;
								return false;	
							}		
													
							if ((cantidad_productos > stock && dias_entrega == 0) && (accion == 'cantidad')){
								 alert ('No hay suficiente stock para este producto');
								 document.getElementById('id_cantidad_'+key).value = cantidad_antigua;
								 return false;	
							}							

							//cantidad_antigua=parseInt(cantidad_antigua);	
							iva = parseFloat(iva)/100;		
							descuento = parseFloat(descuento)/100;									
							
							// Descuento
							if (document.getElementById('id_descuento')) 
							{ 						
								valor_actual_descuento=document.getElementById('id_descuento').value;
								valor_actual_descuento=valor_actual_descuento.replace('.','');
								valor_actual_descuento=valor_actual_descuento.replace(',','.');
								valor_actual_descuento=parseFloat(valor_actual_descuento);		
								descuento_precio = precio*descuento;
								descuento_precio=parseFloat(descuento_precio);	
							
								if (accion == 'sumar')
								{									
									valor_actual_descuento_mostrar = valor_actual_descuento + descuento_precio;
									document.getElementById('id_descuento').value = number_format(valor_actual_descuento_mostrar,2,',','.');
								} else if (accion == 'restar'){ 
									valor_actual_descuento_mostrar = valor_actual_descuento - descuento_precio;
									document.getElementById('id_descuento').value = number_format(valor_actual_descuento_mostrar,2,',','.');
								} else if (accion == 'cantidad'){ 
									//restamos cantidad antigua
									descuento_precio=(precio*descuento)*cantidad_antigua;
									valor_actual_descuento = valor_actual_descuento - descuento_precio;	
									//sumamos cantidad nueva	
									descuento_precio_nuevo = (precio*descuento)*cantidad;
									valor_actual_descuento_mostrar=valor_actual_descuento+descuento_precio_nuevo;											
									document.getElementById('id_descuento').value = number_format(valor_actual_descuento_mostrar,2,',','.');
								}
							}
								 
							//Total Iva
							//precio=parseFloat(precio);
							valor_actual_iva=document.getElementById('id_total_iva').value;
							valor_actual_iva=valor_actual_iva.replace('.','');
							valor_actual_iva=valor_actual_iva.replace(',','.');
							valor_actual_iva=parseFloat(valor_actual_iva);						
							iva_precio=precio*iva;
							iva_precio=parseFloat(iva_precio);																	
							if (accion == 'sumar')
							{	valor_actual_iva = valor_actual_iva + iva_precio;
								if (document.getElementById('id_descuento')) 
								{
									valor_actual_iva = valor_actual_iva-((valor_actual_descuento_mostrar-valor_actual_descuento)*iva); 
								}
								document.getElementById('id_total_iva').value = number_format(valor_actual_iva,2,',','.');
							} else if (accion == 'restar'){ 
								valor_actual_iva = valor_actual_iva - iva_precio;
								if (document.getElementById('id_descuento')) 
								{
									valor_actual_iva = valor_actual_iva+((valor_actual_descuento-valor_actual_descuento_mostrar)*iva); 
								}								
								document.getElementById('id_total_iva').value = number_format(valor_actual_iva,2,',','.');
							} else if (accion == 'cantidad'){ 
								//restamos cantidad antigua
								iva_precio=(precio*iva)*cantidad_antigua;
								valor_actual_iva = valor_actual_iva - iva_precio;	
								//sumamos cantidad nueva	
								valor_iva_nuevo = (precio*iva)*cantidad;
								valor_actual_iva=valor_actual_iva+valor_iva_nuevo;		
								
								if (document.getElementById('id_descuento')) 
								{
									//restamos cantidad antigua
									descuento_iva=((precio*descuento)*cantidad_antigua)*iva;
									valor_actual_iva = valor_actual_iva+descuento_iva;	
									//sumamos cantidad nueva	
									valor_descuento_iva_nuevo = ((precio*descuento)*cantidad)*iva;
									valor_actual_iva=valor_actual_iva-valor_descuento_iva_nuevo;
								}
								
								document.getElementById('id_total_iva').value = number_format(valor_actual_iva,2,',','.');
							}
							
							// Total
							valor_actual_total=document.getElementById('id_total').value;
							valor_actual_total=valor_actual_total.replace('.','');
							valor_actual_total=valor_actual_total.replace(',','.');
							valor_actual_total=parseFloat(valor_actual_total);			
							precio_con_iva=(precio*iva)+precio;
							precio_con_iva=parseFloat(precio_con_iva);		
							if (accion == 'sumar')
							{	
								valor_actual_total = valor_actual_total + precio_con_iva;
								if (document.getElementById('id_descuento')) 
								{
									valor_actual_descuento_total=(valor_actual_descuento_mostrar-valor_actual_descuento)+((valor_actual_descuento_mostrar-valor_actual_descuento)*iva);		
									valor_actual_total = valor_actual_total-valor_actual_descuento_total; 
								}								
								document.getElementById('id_total').value = number_format(valor_actual_total,2,',','.');
							} else if (accion == 'restar'){ 
								valor_actual_total = valor_actual_total - precio_con_iva;
								if (document.getElementById('id_descuento')) 
								{
									valor_actual_descuento_total=(valor_actual_descuento-valor_actual_descuento_mostrar)+((valor_actual_descuento-valor_actual_descuento_mostrar)*iva);		
									valor_actual_total = valor_actual_total+valor_actual_descuento_total; 
								}	
								document.getElementById('id_total').value = number_format(valor_actual_total,2,',','.');
							} else if (accion == 'cantidad'){ 
								//restamos cantidad antigua
								precio_con_iva=((precio*iva)+precio)*cantidad_antigua;
								valor_actual_total = valor_actual_total - precio_con_iva;
								//sumamos cantidad nueva
								valor_total_nuevo = ((precio*iva)+precio)*cantidad;
								valor_actual_total=valor_actual_total+valor_total_nuevo;
								
								if (document.getElementById('id_descuento')) 
								{
									//restamos cantidad antigua
									descuento_total= ((precio*descuento)*iva)*cantidad_antigua+((precio*descuento)*cantidad_antigua);
									valor_actual_total = valor_actual_total+descuento_total;	
									//sumamos cantidad nueva	
									valor_descuento_nuevo = ((precio*descuento)*iva)*cantidad+((precio*descuento)*cantidad);
									valor_actual_total=valor_actual_total-valor_descuento_nuevo;
								}								
								//mostramos
								document.getElementById('id_total').value = number_format(valor_actual_total,2,',','.');
							}
							
			
							if (accion == 'borrar')
							{								
								// Obtenemos el iva del registro actual
								valor_subtotal   = document.getElementById('id_subtotal_'+key).value;
								valor_subtotal   = valor_subtotal.replace('.','');
								valor_subtotal   = valor_subtotal.replace(',','.');
								valor_subtotal   = parseFloat(valor_subtotal);						
								iva_precio=valor_subtotal*iva;										
								
								//Modificamos descuento
								if (document.getElementById('id_descuento')) 
								{
									descuento_precio=valor_subtotal*descuento;
									valor_descuento = valor_actual_descuento-descuento_precio;
									document.getElementById('id_descuento').value = number_format(valor_descuento,2,',','.');	
								}																
								
								//Modificamos iva total
								valor_actual_iva = document.getElementById('id_total_iva').value;
								valor_actual_iva = valor_actual_iva.replace('.','');
								valor_actual_iva = valor_actual_iva.replace(',','.');					
								valor_actual_iva = parseFloat(valor_actual_iva);																
								valor_actual_iva = valor_actual_iva-iva_precio;								
								if (document.getElementById('id_descuento')) 
								{
									iva_descuento=descuento_precio*iva;
									valor_actual_iva = valor_actual_iva+iva_descuento;
								}								
								document.getElementById('id_total_iva').value = number_format(valor_actual_iva,2,',','.');						
											
								//Modificamos valor total			
								valor_actual_total = document.getElementById('id_total').value
								valor_actual_total = valor_actual_total.replace('.','');
								valor_actual_total = valor_actual_total.replace(',','.');					
								valor_actual_total = parseFloat(valor_actual_total);	
								valor_total_restar = valor_subtotal + iva_precio; 
								valor_actual_total = valor_actual_total - valor_total_restar;
								if (document.getElementById('id_descuento')) 
								{
									valor_actual_total_descuento=descuento_precio+(descuento_precio*iva);
									valor_actual_total = valor_actual_total+valor_actual_total_descuento;
								}	
								document.getElementById('id_total').value = number_format(valor_actual_total,2,',','.');				
								
								//Se elimina el regitro
								document.getElementById('tr_producto_'+key).innerHTML = "";
							}
							
						
							// Total de Productos en la cesta: 
							// Obtenemos el iva del registro actual
							valor_num_productos_total = document.getElementById('id_num_productos_total').value;
							valor_num_productos_total = parseInt(valor_num_productos_total);
							if (accion == 'sumar')
							{												
								valor_num_productos_total += 1;
							} else if (accion == 'restar'){ 
								valor_num_productos_total -= 1;						
							} else if (accion == 'cantidad'){ 						
								valor_num_productos_total -= cantidad_antigua;						
								valor_num_productos_total += cantidad;													
							} else if (accion == 'borrar'){ 						
								valor_num_productos_total -= cantidad_antigua;												
							}
							
							
							// Elements externs a carrito
							document.getElementById('id_num_productos_total').value=valor_num_productos_total;				

							if (accion != 'borrar')
							{	
								//Cantidad
								document.getElementById('id_cantidad_'+key).value=cantidad;				
								//Importe subtotal
								document.getElementById('id_subtotal_'+key).value=number_format(precio*cantidad,2,',','.');							
							}
							
							if(valor_actual_total > pedido_minimo){ 
								document.getElementById('importe_inferior_minimo_pedido').style.display = 'none';
								document.getElementById('boton_comprar_carrito').style.display = '';
								document.getElementById('finalizar_inactivo').style.display = 'none';
								document.getElementById('finalizar_activo').style.display = '';									
							} else {
								document.getElementById('importe_inferior_minimo_pedido').style.display = '';
								document.getElementById('boton_comprar_carrito').style.display = 'none';
								document.getElementById('finalizar_inactivo').style.display = '';
								document.getElementById('finalizar_activo').style.display = 'none';									
							}
							
							if(valor_actual_total == 0)
							{
								document.getElementById('finalizar_inactivo').style.display = '';
								document.getElementById('finalizar_activo').style.display = 'none';	
							}
							
							if (valor_num_productos_total == 1){
								document.getElementById('cantidad_total_texto_productos').style.display = 'none';
								document.getElementById('cantidad_total_texto_producto').style.display = 'inline';								
							} else {
								document.getElementById('cantidad_total_texto_productos').style.display = 'inline';							
								document.getElementById('cantidad_total_texto_producto').style.display = 'none';								
							}

							if (valor_num_productos_total == 0){
								document.getElementById('finalizar_inactivo').style.display = 'none';
								document.getElementById('finalizar_activo').style.display = 'none';									
								document.getElementById('ver_carrito').style.display = 'none';
							} else {
								document.getElementById('ver_carrito').style.display = '';
							}
								
							document.getElementById('cantidad_total_productos_header').innerHTML=number_format(valor_num_productos_total);
							document.getElementById('cantidad_total_importe_header').innerHTML=number_format(valor_actual_total,2,',','.')+" &euro;";						
							
							if (valor_num_productos_total == 0){
								window.location = "index.php"
							}
						}												
					}
				  rpc.send(aEnviar);
				}
		}
}

function sendAndLoad_estado_envolver_para_regalo(estado, num_productos){	
	var rpc=aj();
	if(rpc){		
		rpc.open('POST','includes/carrito_envolver_para_regalo_estado.php',true);
		rpc.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		aEnviar = 'estado='+estado;						
		rpc.onreadystatechange=function(){
			if(rpc.readyState==4){			
				if (estado){
					for (i=1;i<=num_productos;i++) { 
						document.getElementById('control_cantidad_envolver_'+i).style.display = '';				
						document.getElementById('control_total_envolver_'+i).style.display = '';				
					}
				} else {
					for (i=1;i<=num_productos;i++) { 
						document.getElementById('control_cantidad_envolver_'+i).style.display = 'none';				
						document.getElementById('control_total_envolver_'+i).style.display = 'none';				
					}										
				}
			}
		}	
		rpc.send(aEnviar);
	}
}


function sendAndLoad_cantidad_envoler_carrito(key,precio,accion,iva,descuento,tarjeta,pedido_minimo){

	ejecutar_funciones = true;
	cantidad_envolver = parseInt(document.getElementById('id_envolver_'+key).value);
	cantidad_productos = parseInt(document.getElementById('id_cantidad_'+key).value);	
		
	if (isNaN(cantidad_envolver)){
		alert('Ha de ser un valor correcto');
		return false;
	}
	if ((cantidad_productos == cantidad_envolver) && (accion == 'sumar')){
		alert('La cantidad de productos a envolver no puede ser superior a los productos.');
		return false;
	}	
	if ((cantidad_envolver == 0) && (accion == 'restar')){
		alert('La cantidad de productos a envolver no puede ser superior a los productos.');
		return false;
	}	
	
	var rpc=aj();
	if(rpc){		
		rpc.open('POST','includes/carrito_ajax_envolver.php',true);
		rpc.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		aEnviar = 'key='+key+'&accion='+accion+'&cantidad_envolver='+cantidad_envolver+'&cantidad_productos='+cantidad_productos;				
		rpc.onreadystatechange=function(){
			if(rpc.readyState==4){
				
				var resultados = rpc.responseText.split("@");
				cantidad=parseInt(resultados[0]);							
				cantidad_antigua=parseInt(resultados[1]);			

				if (cantidad_productos < cantidad_envolver){	
					alert('La cantidad de productos a envolver no puede ser superior a los productos.');
					document.getElementById('id_envolver_'+key).value = cantidad_antigua;
					return false;
				}				
											
				iva = parseFloat(iva)/100;	
				descuento = parseFloat(descuento)/100;	
			
						// Descuento
						if (document.getElementById('id_descuento')) 
						{ 
							valor_actual_descuento=document.getElementById('id_descuento').value;
							valor_actual_descuento=valor_actual_descuento.replace('.','');
							valor_actual_descuento=valor_actual_descuento.replace(',','.');
							valor_actual_descuento=parseFloat(valor_actual_descuento);		
							descuento_precio = precio*descuento;
							descuento_precio=parseFloat(descuento_precio);	
							
							if (accion == 'sumar')
							{	valor_actual_descuento_mostrar = valor_actual_descuento + descuento_precio;
								document.getElementById('id_descuento').value = number_format(valor_actual_descuento_mostrar,2,',','.');
							} else if (accion == 'restar'){ 
								valor_actual_descuento_mostrar = valor_actual_descuento - descuento_precio;
								document.getElementById('id_descuento').value = number_format(valor_actual_descuento_mostrar,2,',','.');
							} else if (accion == 'cantidad'){ 
								//restamos cantidad antigua
								descuento_precio=(precio*descuento)*cantidad_antigua;
								valor_actual_descuento = valor_actual_descuento - descuento_precio;	
								//sumamos cantidad nueva	
								descuento_precio_nuevo = (precio*descuento)*cantidad;
								valor_actual_descuento_mostrar=valor_actual_descuento+descuento_precio_nuevo;											
								document.getElementById('id_descuento').value = number_format(valor_actual_descuento_mostrar,2,',','.');
							}
						}

						//Total Iva
						valor_actual_iva=document.getElementById('id_total_iva').value;
						valor_actual_iva=valor_actual_iva.replace('.','');
						valor_actual_iva=valor_actual_iva.replace(',','.');
						valor_actual_iva=parseFloat(valor_actual_iva);						
						iva_precio=precio*iva;
						iva_precio=parseFloat(iva_precio);																	
						if (accion == 'sumar')
						{	valor_actual_iva = valor_actual_iva + iva_precio;
							if (document.getElementById('id_descuento')) 
							{
								valor_actual_iva = valor_actual_iva-((valor_actual_descuento_mostrar-valor_actual_descuento)*iva); 
							}
							document.getElementById('id_total_iva').value = number_format(valor_actual_iva,2,',','.');
						} else if (accion == 'restar'){ 
							valor_actual_iva = valor_actual_iva - iva_precio;
							if (document.getElementById('id_descuento')) 
							{
								valor_actual_iva = valor_actual_iva+((valor_actual_descuento-valor_actual_descuento_mostrar)*iva); 
							}								
							document.getElementById('id_total_iva').value = number_format(valor_actual_iva,2,',','.');
						} else if (accion == 'cantidad'){ 
							//restamos cantidad antigua
							iva_precio=(precio*iva)*cantidad_antigua;
							valor_actual_iva = valor_actual_iva - iva_precio;	
							//sumamos cantidad nueva	
							valor_iva_nuevo = (precio*iva)*cantidad;
							valor_actual_iva=valor_actual_iva+valor_iva_nuevo;		
							
							if (document.getElementById('id_descuento')) 
							{
								//restamos cantidad antigua
								descuento_iva=((precio*descuento)*cantidad_antigua)*iva;
								valor_actual_iva = valor_actual_iva+descuento_iva;	
								//sumamos cantidad nueva	
								valor_descuento_iva_nuevo = ((precio*descuento)*cantidad)*iva;
								valor_actual_iva=valor_actual_iva-valor_descuento_iva_nuevo;
							}
							
							document.getElementById('id_total_iva').value = number_format(valor_actual_iva,2,',','.');
						}



						// Total
						valor_actual_total=document.getElementById('id_total').value;
						valor_actual_total=valor_actual_total.replace('.','');
						valor_actual_total=valor_actual_total.replace(',','.');
						valor_actual_total=parseFloat(valor_actual_total);			
						precio_con_iva=(precio*iva)+precio;
						precio_con_iva=parseFloat(precio_con_iva);		
						if (accion == 'sumar')
						{	
							valor_actual_total = valor_actual_total + precio_con_iva;
							if (document.getElementById('id_descuento')) 
							{
								valor_actual_descuento_total=(valor_actual_descuento_mostrar-valor_actual_descuento)+((valor_actual_descuento_mostrar-valor_actual_descuento)*iva);		
								valor_actual_total = valor_actual_total-valor_actual_descuento_total; 
							}								
							document.getElementById('id_total').value = number_format(valor_actual_total,2,',','.');
						} else if (accion == 'restar'){ 
							valor_actual_total = valor_actual_total - precio_con_iva;
							if (document.getElementById('id_descuento')) 
							{
								valor_actual_descuento_total=(valor_actual_descuento-valor_actual_descuento_mostrar)+((valor_actual_descuento-valor_actual_descuento_mostrar)*iva);		
								valor_actual_total = valor_actual_total+valor_actual_descuento_total; 
							}	
							document.getElementById('id_total').value = number_format(valor_actual_total,2,',','.');
						} else if (accion == 'cantidad'){ 
							//restamos cantidad antigua
							precio_con_iva=((precio*iva)+precio)*cantidad_antigua;
							valor_actual_total = valor_actual_total - precio_con_iva;
							//sumamos cantidad nueva
							valor_total_nuevo = ((precio*iva)+precio)*cantidad;
							valor_actual_total=valor_actual_total+valor_total_nuevo;
							
							if (document.getElementById('id_descuento')) 
							{
								//restamos cantidad antigua
								descuento_total= ((precio*descuento)*iva)*cantidad_antigua+((precio*descuento)*cantidad_antigua);
								valor_actual_total = valor_actual_total+descuento_total;	
								//sumamos cantidad nueva	
								valor_descuento_nuevo = ((precio*descuento)*iva)*cantidad+((precio*descuento)*cantidad);
								valor_actual_total=valor_actual_total-valor_descuento_nuevo;
							}								
							//mostramos
							document.getElementById('id_total').value = number_format(valor_actual_total,2,',','.');
						}

					 	
						// Elements externs a carrito
						if (accion != 'borrar')
						{	
							//Cantidad
							document.getElementById('id_envolver_'+key).value=cantidad;				
							//Importe subtotal
							document.getElementById('id_subtotal_envolver_'+key).value=number_format(precio*cantidad,2,',','.');							
						}
						
						if(valor_actual_total > pedido_minimo){ 
							document.getElementById('importe_inferior_minimo_pedido').style.display = 'none';
							document.getElementById('boton_comprar_carrito').style.display = '';
							document.getElementById('finalizar_inactivo').style.display = 'none';
							document.getElementById('finalizar_activo').style.display = '';									
						} else {
							document.getElementById('importe_inferior_minimo_pedido').style.display = '';
							document.getElementById('boton_comprar_carrito').style.display = 'none';
							document.getElementById('finalizar_inactivo').style.display = '';
							document.getElementById('finalizar_activo').style.display = 'none';									
						}
							
						if(valor_actual_total == 0)
						{
							document.getElementById('finalizar_inactivo').style.display = '';
							document.getElementById('finalizar_activo').style.display = 'none';	
						}
										
						document.getElementById('cantidad_total_importe_header').innerHTML=number_format(valor_actual_total,2,',','.');						
										
			}
		}	
		rpc.send(aEnviar);
	}				
}
/*
function validarFecha(fecha) {
	try{
	var fecha = fecha.split("-");
	var dia = fecha[0];
	var mes = fecha[1];
	var ano = fecha[2];
	var estado = true;
	if ((dia.length == 2) && (mes.length == 2) && (ano.length == 4)) {
	switch (parseInt(mes)) {
	case 1:dmax = 31;break;
	case 2: if (ano % 4 == 0) dmax = 29;
	 else dmax = 28;
	 break;
	case 3:dmax = 31;break;
	case 4:dmax = 30;break;
	case 5:dmax = 31;break;
	case 6:dmax = 30;break;
	case 7:dmax = 31;break;
	case 8:dmax = 31;break;
	case 9:dmax = 30;break;
	case 10:dmax = 31;break;
	case 11:dmax = 30;break;
	case 12:dmax = 31;break;
	}
	dmax!=""?dmax:dmax=-1;
	
	if ((dia >= 1) && (dia <= dmax) && (mes >= 1) && (mes <= 12)) {
	for (var i = 0; i < fecha[0].length; i++) {
	diaC = fecha[0].charAt(i).charCodeAt(0);
	(!((diaC > 47) && (diaC < 58)))?estado = false:'';
	mesC = fecha[1].charAt(i).charCodeAt(0);
	(!((mesC > 47) && (mesC < 58)))?estado = false:'';
	}
	}
	
	for (var i = 0; i < fecha[2].length; i++) {
	anoC = fecha[2].charAt(i).charCodeAt(0);
	(!((anoC > 47) && (anoC < 58)))?estado = false:'';
	}
	
	}else estado = false;
	return estado;
	}catch(err){
		alert("Error fechas");
	}
}
*/
function validar_fechas(fechaInicio, fechaFin){
  fechaInicio = fechaInicio.split('-');
  fechaFin = fechaFin.split('-');
                    
  fechaInicio = new Date(fechaInicio[2], fechaInicio[1] - 1, fechaInicio[0]).valueOf();
  if(isNaN(fechaInicio)){
	alert('Fecha inicio incorrecta');		  
	return false;
  }
  fechaFin = new Date(fechaFin[2], fechaFin[1] - 1, fechaFin[0]).valueOf();
  if(isNaN(fechaFin)){
	alert('Fecha fin incorrecta');		  
	return false;
  }

  if (fechaInicio > fechaFin) {
	alert('Fecha inicio Superior a fecha fin');	
	return false;
  } else {
   return true;
  }
}

function sendAndLoad_mostrar_estadisticas(finicio,ffin){
	// <![CDATA[
	if (validar_fechas(finicio,ffin)){
		document.getElementById("div_detalle_chart_am").innerHTML='<div align="center"><br><br><img src="../images/loader.gif" width="150" height="150"></div>';				
		var so = new SWFObject("amcharts/amline/amline.swf", "amline_estadisticas", "820", "420", "8", "#FFFFFF");
		so.addVariable("path", "amcharts/amline/");
		so.addVariable("settings_file", encodeURIComponent("includes/usuario_mis_estadisticas_settings.xml")); 	
		so.addVariable("data_file", encodeURIComponent("includes/usuario_mis_estadisticas_data.php?finicio="+finicio+"&ffin="+ffin));
		so.addVariable("loading_data", "Cargando Datos");  
		so.write("div_detalle_chart_am");	
		
		var so = new SWFObject("amcharts/ampie/ampie.swf", "ampie_productos_vendidos", "520", "430", "8", "#FFFFFF");
		so.addVariable("path", "amcharts/ampie/");
		so.addVariable("settings_file", encodeURIComponent("includes/usuario_mis_estadisticas_ampie_settings_productos_vendidos.xml"));		
		so.addVariable("data_file", encodeURIComponent("includes/usuario_mis_estadisticas_ampie_data_productos_vendidos.php?finicio="+finicio+"&ffin="+ffin));
		so.write("div_detalle_chart_am_pie_productos_vendidos");						

  	    sendAndLoad_mostrar_estadisticas_detalle(finicio,ffin);	
	}
}

function sendAndLoad_mostrar_estadisticas_detalle(finicio,ffin){	
	var rpc=aj();
    if(rpc){
	//si pudo crearse el objeto, avanzamos (respetar el orden)	
        document.getElementById('div_estadisticas_detalle').innerHTML='<div align="left"><img src="../images/loader.gif" width="25" height="25">';
		rpc.open('POST','includes/usuario_mis_estadisticas_detalle.php',true);
        rpc.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

        aEnviar = 'finicio='+finicio+'&ffin='+ffin;
        //creamos una función anónima que sirva de handler
        rpc.onreadystatechange=function(){
            if(rpc.readyState==4){
				document.getElementById('div_estadisticas_detalle').innerHTML=rpc.responseText;				
            }
        }
        rpc.send(aEnviar);
    }
}


function sendAndLoad_productosstock_lista(producto,titulo,registros,pagina){	
	var rpc=aj();
    if(rpc){
	//si pudo crearse el objeto, avanzamos (respetar el orden)	
		document.getElementById('div_productos_detalle').innerHTML='';
        document.getElementById('div_productos_lista').innerHTML='<div align="left"><img src="../images/loader.gif" width="25" height="25">';
		rpc.open('POST','includes/usuario_mis_productosstock_lista.php',true);
        rpc.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

        aEnviar = 'producto='+producto+'&titulo='+titulo+'&registros='+registros+'&pagina='+pagina;
        //creamos una función anónima que sirva de handler
        rpc.onreadystatechange=function(){
            if(rpc.readyState==4){
				document.getElementById('div_productos_filtros').style.display = ''; 			
				document.getElementById('div_productos_lista').innerHTML=rpc.responseText;				
            }
        }
        rpc.send(aEnviar);
    }
}

function sendAndLoad_producto_cambiarEstado_stock(id, estado_nuevo, estado_2, estado_1) {
	var rpc=aj();
    if(rpc){
		document.getElementById("conexion_"+id).src= "../images/loader.gif";
		document.getElementById("conexion_"+id).width= "15";
		//document.getElementById("conexion_"+id).height= "15";			
		rpc.open('POST','includes/usuario_mis_productosstock_cambiar_estado.php',true);
        rpc.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		var aEnviar='';

		aEnviar = 'id='+id+'&estado_nuevo='+estado_nuevo;		
		//creamos una función anónima que sirva de handler
		rpc.onreadystatechange=function(){
			if(rpc.readyState==4){
				//alert(rpc.responseText);
				estado_nuevo=rpc.responseText;	
				//Cambia el ícono, título y onclic
				if(estado_nuevo == 0) {	
					document.getElementById("list_conexion_"+id).disabled = true;
					document.getElementById("conexion_"+id).src = "includes/img/disconnect.png";
					document.getElementById("conexion_"+id).title = estado_2;
					document.getElementById("conexion_"+id).setAttribute("onclick", "sendAndLoad_producto_cambiarEstado_stock('"+id+"', '1', '"+estado_2+"', '"+estado_1+"');");
				}else if(estado_nuevo == 1) {
					document.getElementById("list_conexion_"+id).disabled = false;					
					document.getElementById("conexion_"+id).src = "includes/img/connect.png";
					document.getElementById("conexion_"+id).title = estado_1;
					document.getElementById("conexion_"+id).setAttribute("onclick", "sendAndLoad_producto_cambiarEstado_stock('"+id+"', '0', '"+estado_2+"', '"+estado_1+"');");
				}							
			}
		}	
		rpc.send(aEnviar);
	}
}


function sendAndLoad_producto_cambiarCantidad_stock(id, cantidad) {
	var rpc=aj();
    if(rpc){
		document.getElementById("list_conexion_"+id+"_pensando").style.display = '';
		document.getElementById("list_conexion_"+id).style.display = 'none';
		document.getElementById("list_conexion_"+id).width= "15";
		//document.getElementById("conexion_"+id).height= "15";			
		rpc.open('POST','includes/usuario_mis_productosstock_cambiar_cantidad.php',true);
        rpc.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		var aEnviar='';

		aEnviar = 'id='+id+'&cantidad='+cantidad;		
		//creamos una función anónima que sirva de handler
		rpc.onreadystatechange=function(){
			if(rpc.readyState==4){
				document.getElementById("list_conexion_"+id+"_pensando").style.display = 'none';
				document.getElementById("list_conexion_"+id).style.display = '';
			}
		}	
		rpc.send(aEnviar);
	}
}

function estado_pensando(id){	
	document.getElementById(id).innerHTML='<div align="left"><img src="../images/loader.gif" width="25" height="25"></div>';
}
function estado_nulo(id){	
	document.getElementById(id).innerHTML='';
}
function sendAndLoad_suscribirse(correo){
	var rpc=aj();
    if(rpc){		
        rpc.open('POST','/includes/suscribirse.php',true);
        rpc.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		aEnviar = 'correo='+correo;	
        rpc.onreadystatechange=function(){
            if(rpc.readyState==4){
				document.getElementById('formulario_suscripcion').style.visibility="hidden";
				document.getElementById('formulario_suscripcion').style.display="none";			
				document.getElementById('registro_suscripcion').style.display='block';
                document.getElementById('registro_suscripcion').style.color='black';
                //document.getElementById('registro_suscripcion').innerHTML=rpc.responseText;			
				document.getElementById('formulario_boletin').innerHTML=rpc.responseText;			
            }else{
                document.getElementById('registro_suscripcion').style.display='block';
            }
        }
        rpc.send(aEnviar);
    }
}
function sendAndLoad_suscribirse_home(correo){
	var rpc=aj();
    if(rpc){		
        rpc.open('POST','/includes/suscribirse.php',true);
        rpc.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		aEnviar = 'correo='+correo;	
        rpc.onreadystatechange=function(){
            if(rpc.readyState==4){
				document.getElementById('formulario_suscripcion_home').style.visibility="hidden";
				document.getElementById('formulario_suscripcion_home').style.display="none";			
				document.getElementById('registro_suscripcion_home').style.display='block';
                document.getElementById('registro_suscripcion_home').style.color='black';
                //document.getElementById('registro_suscripcion').innerHTML=rpc.responseText;			
				document.getElementById('formulario_boletin_home').innerHTML=rpc.responseText;			
            }else{
                document.getElementById('registro_suscripcion_home').style.display='block';
            }
        }
        rpc.send(aEnviar);
    }
}
function sendAndLoad_cupones(cupon){
	var rpc=aj();
    if(rpc){			
        rpc.open('POST','acc_actualiza_producto.php',true);
        rpc.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		aEnviar = 'cupon='+cupon;	
        rpc.onreadystatechange=function(){
            if(rpc.readyState==4){
				if (rpc.responseText == 'ok'){
					location.reload(true);
					document.getElementById('cupon').value='';		
					document.getElementById('error_cupon').style.display='none';						
				} else if (rpc.responseText == 'ko') {
					document.getElementById('cupon').value='';	
					document.getElementById('error_cupon').style.display='block';	
					document.getElementById('error_cupon').innerHTML = 'Cup&oacute;n o Tarjeta no Valido!';
				} else if (rpc.responseText == 'ko_Pedido_Minimo') {
					document.getElementById('cupon').value='';	
					document.getElementById('error_cupon').style.display='block';	
					document.getElementById('error_cupon').innerHTML = 'Importe m&iacute;nimo no alcanzado para el Cup&oacute;n!';
				}
            }
        }
        rpc.send(aEnviar);
    }
}
function agregarCarrito(id,stock,proc_id){	
	var rpc=aj();
    if(rpc){			
        rpc.open('POST','../../../agrega_carrito.php',true);
        rpc.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		aEnviar = 'id='+id+'&stock='+stock+'&proc_id='+proc_id;
        rpc.onreadystatechange=function(){
            if(rpc.readyState==4){							
				if (rpc.responseText == 'ok'){	
					document.location.href = '../../../carrito.html';
				}
            }
        }
        rpc.send(aEnviar);	  	
    }	
}
function comprar_preguardado_info(order){
	var rpc=aj();
    if(rpc){			
        rpc.open('POST','includes/comprar_preguardado_info.php',true);
		aEnviar = 'order='+order;			
        rpc.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        rpc.onreadystatechange=function(){
			if(rpc.readyState==4){				
  		 	    document.comprar_datos.submit();
			}
        }
        rpc.send(aEnviar);
    }
}

function usuario_registro_mail_repetido(mail,formulario){
	var rpc=aj();
    if(rpc){			
        rpc.open('POST','includes/usuario_registro_mail_repetido.php',true);
		aEnviar = 'mail='+mail;			
        rpc.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        rpc.onreadystatechange=function(){
			if(rpc.readyState==4){		
				if ((rpc.responseText == 'true') && (mail != '')){
  	 			    document.getElementById("Mail").style.borderColor="red";
					document.getElementById("Mail_repetido").style.display = ''; 
					document.getElementById("Mail").focus();					
				} else {
  	 			    document.getElementById("Mail").style.borderColor="";
					document.getElementById("Mail_repetido").style.display = 'none';  	

				}
			}
        }
        rpc.send(aEnviar);
    }
}
