
//###############################################################################################################
//#										    	RECETA
//###############################################################################################################

function search_receta() {
		
	if($("txt_receta").value=='') {
		alert("Ingrese un parametro para la busqueda");	
	}
	else {
		location = 'recetas_lista.php?search='+$("txt_receta").value;	
	}	
	
}

//###############################################################################################################
//#										    	HOME
//###############################################################################################################

function ext_pedido_detalle(id) {
		
	if($("pedidos_ext_"+id).style.display == 'none') {
		
		$("pedidos_ext_"+id).style.display = 'block';		
		$("pedidos_ext_"+id+'_s').style.display = 'block';		
		$("pedidos_ext_"+id+'_b').style.display = 'none';
				
	}
	else {
		
		$("pedidos_ext_"+id).style.display = 'none';	
		$("pedidos_ext_"+id+'_s').style.display = 'none';		
		$("pedidos_ext_"+id+'_b').style.display = 'block';
		
	}
	
}

//###############################################################################################################
//#										    	HOME
//###############################################################################################################

function login(flag) {
	
	var email_login='email_login';
	var clave_login='clave_login';
	var formulario=document.frm_login;
	if(flag)
	{
		email_login='email_login2';
		clave_login='clave_login2';
		formulario=document.frm_login2;
	}
	if($(email_login).value == '') {
		alert('El campo EMail no puede estar vacio.');
		$(email_login).focus();
	}
	else if(!isMail(email_login)) {
		alert('Email invalido.');
		$(email_login).focus();		
	}
	else if($(clave_login).value == '') {
		alert("El campo Clave no puede estar vacio.");
		$(clave_login).focus();		
	}
	else {
		formulario.submit();	
	}
}


function change_tab(e)  {
	var keycode;
	if (window.event) keycode = window.event.keyCode;
	else if (e) keycode = e.keyCode;
	else return true;
	alert(keycode);
	if (keycode == 9) {
		$("clave_login").focus();
		return false;	      
	 }
}
    
function mueveReloj(){

	if(document.getElementById('hora_reloj')) {
	
		segundo = parseInt(segundo) + 1;
		
		if(segundo >= 60) {
			segundo = 0;
			minuto = parseInt(minuto) +  1;	
		}	
		if(minuto >= 60) {
			minuto = 0;
			hora = parseInt(hora) + 1;
		}
		if(hora >= 24) {
			hora = 0; 
		}
		
		if((""+segundo).length == 1 ) {
			segundoM = '0' + segundo;
		}
		else {
			segundoM = segundo;
		}
		
		if((""+minuto).length == 1) {
			minutoM = '0' + minuto;
		}
		else {
			minutoM = minuto;
		}	
		
	    horaImprimible = hora + ":" + minutoM  ;
		
	    document.getElementById('hora_reloj').innerHTML = horaImprimible;
	
	    setTimeout("mueveReloj()",1000);
    
	}
    
} 

function search() {
	if($('search').value == '') {
		alert('Ingrese un paramentro para la busqueda');
		$('search').focus();
	}
	else {
		document.frm_search.submit();	
	}
}

function clean_search() {
	if($('search').value == ' - buscador rapido -') {
		$('search').value = '';
	}
}	


//###############################################################################################################
//#										    	PRODUCTOS DETALLE 
//###############################################################################################################

function comprar(act,unit) {

	if(unit == 0 && $('kilos').value == '0' && $('gramos').value == '0') {
		alert('Especificar cuando desea llevar');	
	}
	else if(unit == 0 && parseInt($('kilos').value) < 0 && parseInt($('gramos').value) < 0) {
		alert("NO pueden a ver valores negativos");
	}
	else if(unit == 1 && $('unidades').value == '0') {
		alert('Especificar cuando desea llevar');	
	}
	else if(unit == 1 && parseInt($('unidades').value) < 0) {
		alert("NO pueden a ver valores negativos");
	}
	else if($("limpieza") && $("limpieza").value == "") {
		alert("Seleccione una preparacion");
	}
	else {
		
		if($('cabeza_'+$('limpieza')) && $('cabeza_'+$('limpieza').value)) {
			$('cabeza').value = $('cabeza_'+$('limpieza').value).checked == true ? "1" : "0";
		}
		
		if($('espina_'+$('limpieza')) && $('espina_'+$('limpieza').value))	{	
			$('espina').value = $('espina_'+$('limpieza').value).checked == true ? "1" : "0";
		}
		
		$('act').value = act;	
		
		document.frm_comprar.submit();		
	}
	
}



function cambiar_receta(id) {	
	
	var recetas = $('recetas_ids').value.split(',');
	
	for(i = 0; i < recetas.length ; i++) {
		$('recetas_'+recetas[i]).style.display = 'none';
	}
	
	$("imprimir_receta").setAttribute("href","javascript:popup('popup/popup_receta.php?idr=" + id + "',500,400,'');");
	
	$('recetas_'+id).style.display = 'block';	
	
}

function cambiar_limpieza(id) {
	
	var limpiezas = $('limpiezas_ids').value.split(',');
	
	for(i = 0; i < limpiezas.length ; i++) {
		$('limp_'+limpiezas[i]).style.display = 'none';
	}
	
	$('limp_'+id).style.display = 'block';
}

function modKilos(act) {

	var kilos = $('kilos').value;

	if(act == 'subir') {
		$('kilos').value = eval(kilos) + 1 ;
	}
	else if(act == 'bajar') {
		if(kilos > 0) {
			$('kilos').value = eval(kilos) - 1;
		}
	}
	
	actualizar_total('gramos');

}

function modGramos(act) {

	var gramos = $('gramos').value;

	if(act == 'subir') {
		
		$('gramos').value = eval(gramos) + 50 ;
		
		if($('gramos').value == 1000) {
			
			$('gramos').value = 0;
			$('kilos').value = eval($('kilos').value) +1;	
					
		}
	}
	else if(act == 'bajar') {
		if(gramos > 0) {
			$('gramos').value = eval(gramos) - 50;
		}
	}
	
	actualizar_total('gramos');

}

function modUnidades(act) {

	var unidad = $('unidades').value;
	
	if(act == 'subir') {
		$('unidades').value = parseInt(unidad) + 1;
	}
	else if(act == 'bajar') {
		
		if(unidad != 0) {
			$('unidades').value = parseInt(unidad) - 1;
		}
		
	}
	
	actualizar_total('unidades');
	
}

function actualizar_total(act) {
	
	if(act == 'gramos') {
		var precio = parseFloat($('tot_precio').innerHTML.replace(',','.'));
		var gramos = (parseInt($('kilos').value)*1000) + parseInt($('gramos').value);
		var gramos_mini = $('gramos').value.substring(0,$('gramos').value.length-1);
		
		if(gramos_mini == '') {
			gramos_mini = '000';
		}
		else if(gramos_mini.length == 1) {
			gramos_mini = '0' + gramos_mini + '0';
		}
		else if(gramos_mini.length == 2) {
			gramos_mini =  gramos_mini + '0';	
		}
		
		$('tot_peso').innerHTML  = $('kilos').value + ',' + gramos_mini;
		$('tot_total').innerHTML = number_format(parseFloat((gramos * precio)/1000),2,',','.');
	}
	else if(act == 'unidades') {
		
		var peso = parseInt($('peso_prod').value);
		
		var precio = parseFloat($('tot_precio').innerHTML.replace(',','.'));
		
		var unidades = $('unidades').value;
		
		$('tot_peso').innerHTML  = $('unidades').value;
		$('tot_total').innerHTML = number_format((((unidades*peso) * precio)/1000),2,',','.');		
	}
	
}

function clear_limpieza_ext() {
	if($('limpieza_ext').value == 'Si desea especificar con mas detalle la preparacion anotelo aqui...') {
		$('limpieza_ext').value = '';	
	}	
}

function cambiar_solapa(solapa) {
	
	$('recetas').style.display 	       = 'none';
	$('caracteristicas').style.display = 'none';
	$('nutricion').style.display = 'none';
	
	
	$('solapa_caracteristicas').setAttribute("class","solapas");
	$('solapa_recetas').setAttribute("class","solapas");
	$('solapa_nutricion').setAttribute("class","solapas");
	
	$(solapa).style.display = 'block';
	$('solapa_'+solapa).setAttribute("class","solapas-red");
	

}

//###############################################################################################################
//#										    	REGISTRAR 
//###############################################################################################################

function get_localidades(idp,id,nombre) {
	
	var vars = "act=get_localidades_sel&idp=" + idp + "&nombre=" + nombre;

	var data = post("inc/ajax.php",vars);
	
	if(trim(data) != '') {
		
		$("localidades_"+id).innerHTML = data;
		
	}
	
}

function registrar() {

   var nombres_campos = new Array(); 
   //nombres_campos['usuario'] = 'Usuario';

   var ok = Validator.validar(document.frm,nombres_campos);
	
   if(ok) {
   		if($('condicion') && $('condicion').checked == false) {
   			alert('Debe aceptar las condiciones del documento legal');
   		}
   		else {
   	 		document.frm.submit();
   		}
   }
   else {
   	  Validator.imprimir_mensajes();
   }			   		
	
}

function chance_empresa(valor) {

	if(valor == 1) {
		$('div_empresa').style.display = 'block';
	}
	else {
		$('div_empresa').style.display = 'none';	
	}
	
}

function ver_segunda_direccion() {

	
	
}

//###############################################################################################################
//#										    	CARRITO 
//###############################################################################################################

function chk_pedido() {
	
	var no_tramos = 0;
	
	//HASTA AQUI EH QUEDADO
	for(i = 1 ; i <= 5; i++ ) {
		if($("tramo" + i)) {
			if($("tramo"+i+"_div").style.display == "block") {
				if($("tramo"+i).checked == false) {					
					no_tramos++;
				}
			}
			else {				
				no_tramos++;	
			}
		}
		else {
			
			no_tramos++;	
		}
	}
	
	
	
	if(document.frm.formas_envio && document.frm.formas_envio[0].checked == false && document.frm.formas_envio[1].checked == false) {
		alert('Seleccione una forma de envio');
	}
	else if(no_tramos == 5 && $("formas_envio")) {
		alert("Seleccione un tramo horario");
	}
	else if($('fecha_errores').innerHTML != "") {
		alert($('fecha_errores').innerHTML);	
	}
	else {
		document.frm.submit();
	}
	
}

function find_horarios(fecha) {

	var vars = "act=find_horarios&fecha="+fecha;
	var tmp = '';
	
	
	//var data = new Array();
	var data = post("inc/ajax.php",vars);
	
	var datos = new Array();
	
	data = data.split('||');
	
	for(i = 0 ; i < data.length;i++) {
		
		tmp = data[i].split('@@');
		
		datos[tmp[0]] = tmp[1];
		
	}
	
	$('fecha_errores').innerHTML = "";
	
	if(datos['error'] != '' && datos['error'] != undefined) {
		$('fecha_errores').innerHTML = datos['error'];
		
		$('tramo1_div').style.display = 'none';
		$('tramo2_div').style.display = 'none';
		$('tramo3_div').style.display = 'none';
		$('tramo4_div').style.display = 'none';
		$('tramo5_div').style.display = 'none';
		
		$('tramo1').checked = false;
		$('tramo2').checked = false;
		$('tramo3').checked = false;
		$('tramo4').checked = false;
		$('tramo5').checked = false;
		
		$("mensaje_tramos").style.display = 'none';
		
	}
	else {
		
		$("mensaje_tramos").style.display = 'block';
		
		$('tramo1_div').style.display = datos['tramo1'];
		$('tramo2_div').style.display = datos['tramo2'];
		$('tramo3_div').style.display = datos['tramo3'];
		$('tramo4_div').style.display = datos['tramo4'];
		$('tramo5_div').style.display = datos['tramo5'];
		
		if(datos['tramo1'] == 'block') {
			$('tramo1').checked = true;
		}
		else {
			$('tramo1').checked = false;
		}
				
		if(datos['tramo2'] == 'block') {
			$('tramo2').checked = true;
		}
		else {
			$('tramo2').checked = false;
		}
				
		if(datos['tramo3'] == 'block') {
			$('tramo3').checked = true;
		}
		else {
			$('tramo3').checked = false;
		}
				
		if(datos['tramo4'] == 'block') {
			$('tramo4').checked = true;
		}
		else {
			$('tramo4').checked = false;
		}
				
		if(datos['tramo5'] == 'block') {
			$('tramo5').checked = true;
		}
		else {
			$('tramo5').checked = false;
		}
		
		
		
	}
		
	$('id_items').focus();
	
	
	
}

function remover_item(id) {
	if(confirm('Seguro que desea remover este item del carrito ?')) {
		location = 'carrito.php?act=remover_item&id='+id;
	}
}

function actualizar_carrito_header() {

	var datos = post("inc/ajax.php","act=actualizar_carrito_header");
	
	var parse = datos.split("||");
	
	$("cantidad_header").innerHTML = number_format(parse[1],2,',','.');
	$("peso_header").innerHTML     = parse[0];
	
}

function actualizar_totales() {

	var items = $('id_items').value.split(',');
	var gastos_envio = 0; 
	
	var precio   = 0;
	var gramos   = 0;
	var subtotal = 0;
	var id       = 0;
	
	var peso_total = 0;
	
	for(i = 0 ; i < items.length ; i++) {
		
		id = items[i];
	
		precio = parseFloat($('tot_precio_'+id).innerHTML.replace(',','.'));
		
		if($('kilos_'+id)) {
			
			gramos = parseFloat((parseFloat($('kilos_'+id).value)*1000) + parseFloat($('gramos_'+id).value));
			
			peso_total += gramos;
			
			subtotal += parseFloat((gramos*precio)/1000);
			
		}
		else {
			
			unidades = $("unidades_"+id).value;
			
			peso = parseFloat($('peso_'+id).innerHTML);
			
			peso_total += peso*unidades;
			
			subtotal +=  (precio*(unidades*peso)/1000);	
				
		}
		
	}
	
	$("subtotal").innerHTML = number_format(subtotal,2,',','.');
	
	gastos_envio = parseFloat(post("inc/ajax.php","act=get_gastos_envio&total="+subtotal+"&peso="+peso_total));
	if(isNaN(gastos_envio))
	{
		gastos_envio=0;
	}
	
	$("gastos_de_envio").innerHTML = number_format(gastos_envio,2,',','.');
	
	$("total").innerHTML = number_format(subtotal+gastos_envio,2,',','.');
	

	
}

function actualizar_total_ext(id) {
	
	var precio = parseFloat($('tot_precio_'+id).innerHTML.replace(',','.'));

	if($('kilos_'+id)) {
	
		var cantidad = (parseInt($('kilos_'+id).value)*1000) + parseInt($('gramos_'+id).value);
		
		var subtotal =  number_format((precio*cantidad)/1000,2,',','.');
		
		$("subtotal_" + id).innerHTML = subtotal;		
		
	}
	else {
		
		var cantidad = $("unidades_"+id).value;	
		
		var peso = parseInt($('peso_'+id).innerHTML);
		
		var subtotal =  number_format((precio*(cantidad*peso)/1000),2,',','.');	
		
	}
	
	if(!$('kilos_'+id)) {
		$("subtotal_" + id).innerHTML = subtotal +" &euro;" ;
	}
	
	
	
	//Actualizamos la Session del Carrito
	var vars = "id="+id+"&cantidad="+cantidad+"&act=actualizar_item";
	
	var data = post("inc/ajax.php",vars)
	
	if(data != "") {
		alert(data);	
	}
	
	//Actualizamos el header del carrito (La famosa tarea "Refresco (Pero no jugo)")
	actualizar_carrito_header();
	
	actualizar_totales();
	
}

function modUnidades_ext(act,id) {

	var unidad = $('unidades_'+id).value;
	
	if(act == 'subir') {
		$('unidades_'+id).value = parseInt(unidad) + 1;
	}
	else if(act == 'bajar') {
		
		if(unidad != 1) {
			$('unidades_'+id).value = parseInt(unidad) - 1;
		}
		
	}
	
	actualizar_total_ext(id);
	
}

function modKilos_ext(act,id) {

	var kilos = $('kilos_'+id).value;

	if(act == 'subir') {
		$('kilos_'+id).value = eval(kilos) + 1 ;
	}
	else if(act == 'bajar') {
		if(kilos > 0) {
			$('kilos_'+id).value = eval(kilos) - 1;
		}
	}
	
	actualizar_total_ext(id);

}

function modGramos_ext(act,id) {

	var gramos = $('gramos_'+id).value;
	if(gramos=="")
	{
		gramos=0;
	}

	if(act == 'subir') {
		
		$('gramos_'+id).value = eval(parseFloat(gramos)) + 50 ;
		
		if($('gramos_'+id).value == 1000) {
			
			$('gramos_'+id).value = 0;
			$('kilos_'+id).value = eval($('kilos_'+id).value) +1;	
					
		}
	}
	else if(act == 'bajar') {
		if(gramos > 0) {
			$('gramos_'+id).value = eval(parseFloat(gramos)) - 50;
		}
	}
	
	actualizar_total_ext(id);

}

//###############################################################################################################
//#										    	EMPLEO
//###############################################################################################################

function enviar_empleo() {

   var nombres_campos = new Array(); 
   nombres_campos['nombre']        = 'Nombre';
   nombres_campos['apellido']      = 'Primer Apellido';
   nombres_campos['apellido2']     = 'Segundo Apellido';
   nombres_campos['edad'] 	       = 'Edad';
   nombres_campos['puesto']        = 'Puesto';
   nombres_campos['estado_civil']  = 'Estado Civil';
   nombres_campos['direccion']     = 'Direccion';
   nombres_campos['telefono']      = 'Primer Telefono';
   nombres_campos['telefono2']     = 'Segun Telefono';
   nombres_campos['email']         = 'Email';
   nombres_campos['cv']            = 'CV';

   var ok = Validator.validar(document.frm,nombres_campos);
	
   if(ok) {
   	 document.frm.submit();    		  		
   }
   else {
   	  Validator.imprimir_mensajes();
   }		
	
}

function enviar_contacto() {

   var nombres_campos = new Array(); 
   nombres_campos['nombre']        = 'Nombre';
   nombres_campos['apellido']      = 'Primer Apellido';
   nombres_campos['email']         = 'Email';
   nombres_campos['mensaje']       = 'Mensaje';
   nombres_campos['asunto']        = 'Asunto';

   var ok = Validator.validar(document.frm,nombres_campos);
	
   if(ok) {
   	 document.frm.submit();    		  		
   }
   else {
   	  Validator.imprimir_mensajes();
   }		
	
}

//###############################################################################################################
//#										    	SUGERENCIAS Y QUEJAS											#
//###############################################################################################################

function enviar_sq() {

   var nombres_campos = new Array(); 
   nombres_campos['comments'] = 'Comentarios';
   nombres_campos['email']    = 'Email';
   nombres_campos['nombre']   = 'Nombre';

   var ok = Validator.validar(document.frm,nombres_campos);
	
   if(ok) {
   	
   		if(document.frm.soq[0].checked == false && document.frm.soq[1].checked == false ) {
   			alert("Especifique si es una queja o una sugerencia por favor.");
   		}
   		else {
   		 document.frm.submit();  
   		}
   		  		
   }
   else {
   	  Validator.imprimir_mensajes();
   }			   		
	
}

//###############################################################################################################
//#										    	VARIAS
//###############################################################################################################


function $(id) {
	return document.getElementById(id);
}

function trim(s) {
    return s.replace(/^\s*(\S*(\s+\S+)*)\s*$/, "$1");
} 

function isMail(id){
 
	var s = document.getElementById(id);
	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.value)){
		return true;
	}else{
		return false;
	}
	
}

function post(url, vars){
	var xml = null;
	try {
		xml = new ActiveXObject('Microsoft.XMLHTTP');
	}catch(exception){
		xml = new XMLHttpRequest();
	}
	xml.open('POST',url,false);
	xml.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
	xml.send (vars);
	if(xml.status == 404) alert('Url no valida');
	return xml.responseText;
}

function popup(URL,w,h,vars) {
	
    var left = (screen.width - w) / 2;
    var top  = (screen.height - h) / 2
	
	window.open(URL,"","left="+left+",top=" + top + ",width="+w+",height="+h+vars);
	
}


//BY Joksnet 
function number_format( number, decimals, dec_point, thousands_sep )
{
    number = Math.round( number * Math.pow(10, decimals) ) / Math.pow(10, decimals);
 
    var str_number = number + '';
    var arr_int = str_number.split(".");
    var str_int = '';
    var str_decimals = '';
    var str_ext = '';
 
    if ( !arr_int[0] ) arr_int[0] = '0';
    if ( !arr_int[1] ) arr_int[1] = '';
 
    if ( arr_int[1].length < decimals )
    {
        str_decimals = arr_int[1];
 
        for ( var i = arr_int[1].length + 1; i <= decimals; i++ )
        {
            str_decimals += '0';
        }
 
        arr_int[1] = str_decimals;
    }
 
    if ( thousands_sep != '' && arr_int[0].length > 3 )
    {
        str_int = arr_int[0];
        arr_int[0] = '';
 
        for ( var j = 3; j < str_int.length; j += 3 )
        {
            str_ext = str_int.slice( str_int.length - j, str_int.length - j + 3 );
            arr_int[0] = thousands_sep + str_ext +  arr_int[0] + '';
        }
 
        str_first = str_int.substr( 0, ( str_int.length % 3 == 0 ) ? 3 : ( str_int.length % 3 ) );
        arr_int[0] = str_first + arr_int[0];
    }
 
    return arr_int[0] + dec_point + arr_int[1];
}

