req = new Array();
almacenProdsValid = new Array();
var almacenProds = 1;

function getAjax(url, valores, elemento, cargando) {

	 //alert(valores);
     //alert(document.getElementById(elemento).innerHTML);

	 try {
     req[elemento] = new XMLHttpRequest(); /* e.g. Firefox */
     } catch(e) {
       try {
       req[elemento] = new ActiveXObject("Msxml2.XMLHTTP");  /* some versions IE */
       } catch (e) {
         try {
         req[elemento] = new ActiveXObject("Microsoft.XMLHTTP");  /* some versions IE */
         } catch (E) {
          req[elemento] = false;
         }
       }
     }

	 document.getElementById(cargando).style.visibility="visible";
     errorTxt = "Ocurrio un error";

     req[elemento].open("POST",url,true);
     req[elemento].onreadystatechange = function() {respuestaContenido(elemento, errorTxt, cargando);};
     req[elemento].setRequestHeader('Content-Type','application/x-www-form-urlencoded');
     req[elemento].send(valores);
}


function respuestaContenido(elemento, errorTxt, cargando) {
   var output = '';
   var codigo_pre = new Array();
   var codigo = new Array();

   if(req[elemento].readyState == 4) {
   	  if(req[elemento].status == 200) {
         output = req[elemento].responseText;
         document.getElementById(cargando).style.visibility="hidden";
		 document.getElementById(elemento).innerHTML=output;
		 try {
			 codigo_pre = req[elemento].responseText.split('<!-- JSX');
		 	 if(typeof(codigo_pre[1])!='undefined') codigo = codigo_pre[1].split('-->');
			 if(typeof(codigo[0])!='undefined') eval(codigo[0]);
		 } catch (e) { }
      }
   }
}

function getJSON(id, url) {

	try {
     req[id] = new XMLHttpRequest(); /* e.g. Firefox */
     } catch(e) {
       try {
       req[id] = new ActiveXObject("Msxml2.XMLHTTP");  /* some versions IE */
       } catch (e) {
         try {
         req[id] = new ActiveXObject("Microsoft.XMLHTTP");  /* some versions IE */
         } catch (E) {
          req[id] = false;
         }
       }
     }

     req[id].onreadystatechange = function() {respuesta_productos_JSON(id);};
     req[id].open("GET",url,true);
     req[id].send(null);
}

function respuesta_productos_JSON(id) {

   if(req[id].readyState == 4) {
   	  if(req[id].status == 200) {
        var respuesta_json = req[id].responseText;
    	var datosJSON = eval("("+respuesta_json+")");
		respuestasJSON(datosJSON, id);
	  }
   }
}

function validar_form_login() {
	login = document.getElementById('login').value;
	pass = document.getElementById('passwd').value;

	if (login.length != 0 && pass.length != 0)
		document.getElementById('flogin').submit();
	else {
			alert("Por favor no te dejes ningun campo por rellenar!");
			return false;
	}
}

function respuestasJSON(data, caller) {
	switch (caller) {
		case '':
			var v0id=null;
		break;

		case '':
			var v0id=null;
		break;
	}
}

function cat_op(elemento, id, op) {

	var val = (elemento.checked) ? 1 : 0;
	//alert('id='+id+'&'+op+'='+val);
	getAjax('modules/catalogo/modificar_precio.php', op+'_q=1&id='+id+'&'+op+'='+val , id, 'load_'+id);
}

function setImagenPrimeraCatalogo(id, producto, imagen) {
	getAjax('modules/catalogo/modificar_precio.php', 'setprim=1&imagen='+imagen+'&producto='+producto, id, 'load_'+id);
}

function setImagenPrimeraInmuebles(id, producto, imagen) {
	getAjax('modules/catalogo/modificar_precio.php', 'setpriminm=1&imagen='+imagen+'&producto='+producto, id, 'load_'+id);
}

function capaSuggest(elemento, tabla, columna, ordenar, funcion_click, funcion_over, function_out) {

	if (elemento.value.length > 1) {
		var ancho = elemento.offsetWidth;
		var posicionTop = obtenerPosicion(elemento).top;
		var posicionLeft = obtenerPosicion(elemento).left;

		document.getElementById('capa_suggest').style.top = (posicionTop-5) +"px";
		document.getElementById('capa_suggest').style.left = ((posicionLeft+ancho)+7)+"px";
		document.getElementById('capa_suggest_main').innerHTML = '<img id="capa_suggest_loading" src="images/cargando-2.gif" />';

		getAjax('include/ajax.php','modo=suggest&ordenar='+ordenar+'&tabla='+tabla+'&columna='+columna+'&funcion_click='+funcion_click+'&funcion_over='+funcion_over+'&funcion_out='+function_out+'&key='+elemento.value, 'capa_suggest_main', 'capa_suggest_loading');
		document.getElementById('capa_suggest').style.visibility= "visible";
	}
}

function obtenerPosicion(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 resetCapaInfo() {
	document.getElementById('capa_suggest_main').innerHTML = '<img id="capa_suggest_loading" src="images/cargando-2.gif" />';
	document.getElementById('capa_suggest').style.visibility= "hidden";
}

function almacenInsertProducto(id) {

	var container = document.createElement('div');
	var padre = document.getElementById('productos_box');
	container.className='productos_box_content';
	container.id = almacenProds;

	almacenProdsValid[id] = almacenProds;
	almacenProds++;

	padre.appendChild(container);

	getAjax('include/ajax.php','modo=almacenProducto&id_prod='+id+'&box='+container.id, container.id, 'productosLoading');
}

function almacenBorrarProducto(id, box) {
	var padre = document.getElementById('productos_box');
	var hijo = document.getElementById(id);
	padre.removeChild(hijo);
	almacenProdsValid[id] = false;
}

function label(str, cap, focus) {

	if (str.value == cap && focus == 1)
		document.getElementById(str.id).value='';

	if (focus == 0 && str.value.length == 0)
		document.getElementById(str.id).value=cap;
}

function resumenEntradaAlmacen() {

	var factura = document.getElementById('factura').value;
	var p = document.getElementById('p_tmpl');
	var producto = document.getElementById('producto_tmpl');
	var lote = document.getElementById('lote_tmpl');
	var unidades = document.getElementById('unidades_tmpl');
	var precio_ud = document.getElementById('pr_ud');
	var precio_tot = document.getElementById('pr_tot');
	var padre = document.getElementById('productos');

	var total=0;
	var subtotal=0;
	var iva=0;

	var error=false;

	if (factura.length == 0) {
		error=true;
		document.getElementById('factura').className='almacenEntradaFactura_error';
	} else
		document.getElementById('factura').className='almacenEntradaFactura';

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

		if (almacenProdsValid[i] != false) {

			var n_p = p.cloneNode(true);
			var n_producto = producto.cloneNode(true);
			var n_lote = lote.cloneNode(true);
			var n_unidades = unidades.cloneNode(true);
			var n_precio_ud = precio_ud.cloneNode(true);
			var n_precio_tot = precio_tot.cloneNode(true);

			var nombre = document.getElementById('prod_name_'+i).innerHTML;
			var tasas = document.getElementById('prod_tax_'+i).value.split(';');

			n_producto.innerHTML = (nombre.length < 30) ? nombre : nombre.substring(0,30)+'...';
			n_lote.innerHTML = document.getElementById('prod_lot_'+i).value;
			n_unidades.innerHTML = parseInt(document.getElementById('prod_uni_'+i).value);
			n_precio_ud.innerHTML = parseFloat(document.getElementById('prod_prec_'+i).value.replace(',','.'));


			var subtot = n_precio_ud.innerHTML * n_unidades.innerHTML;
			n_precio_tot.innerHTML = subtot.toFixed(2);

			if (n_lote.innerHTML.length == 0 || n_lote.innerHTML == 'Lote') {
				error=true;
				document.getElementById('prod_lot_'+i).className='productos_box_input_error';
			} else
				document.getElementById('prod_lot_'+i).className='productos_box_input';

			if (n_unidades.innerHTML.length == 0 || n_unidades.innerHTML == 'NaN') {
				error=true;
				document.getElementById('prod_uni_'+i).className='productos_box_input_error';
			} else
				document.getElementById('prod_uni_'+i).className='productos_box_input';

			if (n_precio_ud.innerHTML.length == 0 || n_precio_ud.innerHTML == 'NaN') {
				error=true;
				document.getElementById('prod_prec_'+i).className='productos_box_input_precio_error';
			} else
				document.getElementById('prod_prec_'+i).className='productos_box_input_precio';

			n_p.id = 'p_'+i;
			n_producto.id = 'n_producto_'+i;
			n_lote.id = 'n_lote_'+i;
			n_unidades.id = 'n_unidades_'+i;
			n_precio_ud.id = 'n_precio_ud_'+i;
			n_precio_tot.id = 'n_precio_tot_'+i;

			n_lote.style.marginLeft='5px';
			n_unidades.style.marginLeft='5px';
			n_precio_ud.style.marginLeft='5px';
			n_precio_tot.style.marginLeft='5px';

			subtotal += subtot;

			for (var j=(tasas.length-1); j>=0; j--) {
				var tax_tmp = subtot * tasas[j] / 100;
				iva += tax_tmp;
			}

			n_p.style.display='block';
			n_p.innerHTML = '';
			padre.appendChild(n_p);
			n_p.appendChild(n_producto);
			n_p.appendChild(n_lote);
			n_p.appendChild(n_unidades);
			n_p.appendChild(n_precio_ud);
			n_p.appendChild(n_precio_tot);
		}
	}

	//iva = subtotal * 16 / 100;
	total = subtotal + iva;

	document.getElementById('subtotal_val').innerHTML = subtotal.toFixed(2);
	document.getElementById('iva_val').innerHTML = iva.toFixed(2);
	document.getElementById('total_val').innerHTML = total.toFixed(2);
	document.getElementById('num_fac_val').innerHTML = factura;

	if (error) {
		document.getElementById('error_form').innerHTML = '<br />No se puede dejar ningún campo por rellenar, verifique los campos con el borde de color rojo';
		resetresumenEntradaAlmacen();
	} else {
		document.getElementById('resumenEntradaAlmacen').style.display = 'block';
		document.getElementById('error_form').innerHTML = '';
	}
}

function resetresumenEntradaAlmacen() {
	document.getElementById('productos').innerHTML='';
	document.getElementById('subtotal_val').innerHTML = 0;
	document.getElementById('iva_val').innerHTML = 0;
	document.getElementById('total_val').innerHTML = 0;
	document.getElementById('resumenEntradaAlmacen').style.display = 'none';
}

function enviarEntradaAlmacen() {
	if (confirm('¿Estas seguro que deseas efectuar la entrada en el almacen?')) {
		document.getElementById('items').value = (almacenProds-1);
		//document.getElementById('prod_prec_1').value='';
		document.getElementById('form_entrada_almacen').submit();
	}
}

function formListados() {
	var qry_por = document.getElementById('qry_por').value;
	var action = (qry_por == 'producto') ? 'panel.php?opcion=146' : 'panel.php?opcion=224';
	var form = document.getElementById('form_listados');
	form.action = action;
	form.submit();
}

function selectListados() {
	if (document.getElementById('qry_por').value != 'producto') {
		document.getElementById('qry_min').style.display='none';
	} else {
		document.getElementById('qry_min').style.display='inline';
	}
}

function addItemStock(pedidos, almacen, producto, accion) {

	var cant = document.getElementById('ped_prod_'+producto);
	var total = document.getElementById('sel_prod_'+producto);
	var disp = document.getElementById('disp_lot_'+almacen);
	var sel = document.getElementById('sel_lot_'+almacen);
	var valid = document.getElementById('valid');
	var input = document.getElementById('productos_b['+producto+']['+almacen+']');

	switch (accion) {
		case 'add':
			if ((parseInt(disp.innerHTML)-1)<0) {
				alert('No quedan productos');
			} else if (parseInt(total.innerHTML) >= parseInt(cant.innerHTML)) {
				alert('No quedan unidades por seleccionar');
			} else {
				total.innerHTML=parseInt(total.innerHTML)+1;
				disp.innerHTML=parseInt(disp.innerHTML)-1;
				sel.innerHTML=parseInt(sel.innerHTML)+1;
				input.value = sel.innerHTML;
				if (parseInt(total.innerHTML) == parseInt(cant.innerHTML)) {
					total.style.color='green';
					valid.value=1;
				}
			}
		break;

		case 'del':
			//alert('del almacen: '+almacen+' producto: '+producto+' cantidad: '+pedidos);
			if (parseInt(sel.innerHTML) <= 0) {
				alert('No hay seleccionado ningun producto');
			} else {
				total.innerHTML=parseInt(total.innerHTML)-1;
				disp.innerHTML=parseInt(disp.innerHTML)+1;
				sel.innerHTML=parseInt(sel.innerHTML)-1;
				input.value = sel.innerHTML;
				total.style.color='red';
				valid.value=0;
			}
		break;

		case 'tot':
			//alert('tot almacen: '+almacen+' producto: '+producto);
			var swap = parseInt(cant.innerHTML)-parseInt(total.innerHTML);
			if (parseInt(disp.innerHTML) < swap) {
				alert('No hay suficientes unidades en este lote');
			} else if (parseInt(total.innerHTML) >= parseInt(cant.innerHTML)) {
				alert('No quedan unidades por seleccionar');
			} else {
				disp.innerHTML=parseInt(disp.innerHTML)-swap;
				total.innerHTML=parseInt(total.innerHTML)+swap;
				sel.innerHTML=parseInt(sel.innerHTML)+swap;
				input.value = sel.innerHTML;
				total.style.color='green';
				valid.value=1;
			}
		break;
	}
}

function validarFormLotes() {

	var form = document.getElementById('formLotes');
	var valid = document.getElementById('valid');
	if (valid.value == 1) {
		form.submit();
	} else {
		alert('Debe seleccionar todas las unidades del pedido para poder continuar.');
	}
}

function setDefOps(valor, id) {
	switch (valor) {
		case 'n0':
			document.getElementById('opcion1_'+id).value='';
		break;

		case 'd0':
			document.getElementById('opcion1_'+id).value='Menos de 12 unidades';
		break;

		case 'd1':
			document.getElementById('opcion1_'+id).value='Mas de 12 unidades';
		break;
    
        case 'p':
			document.getElementById('opcion1_'+id).value='Pensionistas';
		break;
	}
}


function comprobar_form(form_t) {
	var correcto = true;
	var form = '';
    var mensajes = 'Comprueba los siguientes datos: \n\n';
	var regexp = /[\w]+/;
    var regexp2 = /[\s]+/;
    switch (form_t) {
		case 'registro':
			if (document.getElementById('user_ok').innerHTML == 1) {
				correcto=false;
				mensajes += '  - Nombre de usuario en uso, por favor escoja otro.\n';
			}
            
            if (document.getElementById('user_ok').innerHTML == 2) {
				correcto=false;
				mensajes += '  - Comprobacion de usuario en curso, por favor vuelva a hacer click en enviar.\n';
			}
            
            if (document.getElementById('cp').value.length <= 4) {
				correcto=false;
				mensajes += '  - Debe indicar un código postal correcto\n';
			}

			if (document.getElementById('telefono').value.length <= 5) {
				correcto=false;
				mensajes += '  - Debe indicar un telefono para que el repartidor pueda contactarle\n';
			}

			if (document.getElementById('nombre').value.length <= 1) {
				correcto=false;
				mensajes += '  - Debe indicar un nombre para poder realizar la factura\n';
			}

			if (document.getElementById('nif').value.length <= 8) {
				correcto=false;
				mensajes += '  - Debe indicar un NIF/CIF/NIE valido para poder realizar la factura.\n';
			}

			if (document.getElementById('direccion').value.length <= 5) {
				correcto=false;
				mensajes += '  - Debe indicar una direccion valida para que le pueda llegar el pedido.\n';
			}

			if (document.getElementById('ciudad').value.length <= 3) {
				correcto=false;
				mensajes += '  - Debe indicar una poblacion valida para que le pueda llegar el pedido.\n';
			}

			if (document.getElementById('mail').value.length <= 8) {
				correcto=false;
				mensajes += '  - Debe indicar una direccion de correo valida para que le pueda llegar el pedido.\n';
			}

			if (document.getElementById('login').value.length <= 3) {
				correcto=false;
				mensajes += '  - Debe indicar un nombre de usuario correcto.\n';
			}
            
            if (!regexp.test(document.getElementById('login').value) || regexp2.test(document.getElementById('login').value)) {
				correcto=false;
				mensajes += '  - El nombre de usuario solo puede contener caracteres alfanumericos.\n';
			}

			if (document.getElementById('passwd').value.length <= 3) {
				correcto=false;
				mensajes += '  - Debe indicar una contraseña de almenos 4 caracteres.\n';
			}
             
            if (!regexp.test(document.getElementById('passwd').value) || regexp2.test(document.getElementById('passwd').value)) {
				correcto=false;
				mensajes += '  - La contraseña solo puede contener caracteres alfanumericos.\n';
			}
            
			form='form_reg_norm';
		break;

		case 'distro':
            if (document.getElementById('user_ok_d').innerHTML == 1) {
				correcto=false;
				mensajes += '  - Nombre de usuario en uso, por favor escoja otro.\n';
			}
            
            if (document.getElementById('user_ok_d').innerHTML == 2) {
				correcto=false;
				mensajes += '  - Comprobacion de usuario en curso, por favor vuelva a hacer click en enviar.\n';
			}
            
			if (document.getElementById('cp_d').value.length <= 4) {
				correcto=false;
				mensajes += '  - Debe indicar un código postal correcto\n';
			}

			if (document.getElementById('telefono_d').value.length <= 5) {
				correcto=false;
				mensajes += '  - Debe indicar un telefono para que el repartidor pueda contactarle\n';
			}

			if (document.getElementById('nombre_d').value.length <= 1) {
				correcto=false;
				mensajes += '  - Debe indicar un nombre para poder realizar la factura\n';
			}

			if (document.getElementById('nif_d').value.length <= 8) {
				correcto=false;
				mensajes += '  - Debe indicar un NIF/CIF/NIE valido para poder realizar la factura.\n';
			}

			if (document.getElementById('direccion_d').value.length <= 5) {
				correcto=false;
				mensajes += '  - Debe indicar una direccion valida para que le pueda llegar el pedido.\n';
			}

			if (document.getElementById('ciudad_d').value.length <= 3) {
				correcto=false;
				mensajes += '  - Debe indicar una poblacion valida para que le pueda llegar el pedido.\n';
			}

			if (document.getElementById('mail_d').value.length <= 8) {
				correcto=false;
				mensajes += '  - Debe indicar una direccion de correo valida para que le pueda llegar el pedido.\n';
			}

			if (document.getElementById('login_d').value.length <= 3) {
				correcto=false;
				mensajes += '  - Debe indicar un nombre de usuario correcto.\n';
			}
            
            if (!regexp.test(document.getElementById('login_d').value) || regexp2.test(document.getElementById('login_d').value)) {
				correcto=false;
				mensajes += '  - El nombre de usuario solo puede contener caracteres alfanumericos.\n';
			}
            
			if (document.getElementById('passwd_d').value.length <= 3) {
				correcto=false;
				mensajes += '  - Debe indicar una contraseña de almenos 4 caracteres.\n';
			}
            
            if (!regexp.test(document.getElementById('passwd_d').value) || regexp2.test(document.getElementById('passwd_d').value)) {
				correcto=false;
				mensajes += '  - La contraseña solo puede contener caracteres alfanumericos.\n';
			}
            
			form='form_reg_dist';
		break;
	}

	if (correcto)
		document.getElementById(form).submit();
    else
        alert(mensajes);

}

function checkUser(str, id) {
    document.getElementById(id).innerHTML = 2;
    getAjax('gestion/include/ajax.php','modo=checkUser&str='+str, id, 'cargando_checkuser');
}


function togglePromocion() {
    var desplegado = document.getElementById('promocion_despelgado').value;
    if (desplegado == 1) {
        document.getElementById('promocion_despelgado').value = 0;
        document.getElementById('span_promocion_desplegable').style.background='right center no-repeat url(images/desplegar.gif)';
        document.getElementById('span_promocion_desplegable').innerHTML='Desplegar';
    } else {
        document.getElementById('promocion_despelgado').value = 1;
        document.getElementById('span_promocion_desplegable').style.background='right center no-repeat url(images/replegar.gif)';
        document.getElementById('span_promocion_desplegable').innerHTML='Replegar';
    }
}



