function removeOption(span)
{
  var elSel = document.getElementById(span);
  var i;
  for (i = elSel.length - 1; i>=0; i--) {
      elSel.remove(i);
  }
  opt = document.createElement("option");
  opt.setAttribute('value','');				
  opt.appendChild(document.createTextNode('Localidad'));
  elSel.appendChild(opt);
}

function buscaSubcategorias( categoria, span ) {

	ajax = nuevoAjax();
	ajax.open('POST', 'http://www.regalosamedida.es/lib/localidadesXML.php', true );
	
	ajax.onreadystatechange = function() {
		if ( ajax.readyState == 4 ) {
		removeOption(span);
          	var localidades = ajax.responseXML.documentElement;
			
          		for (var i = 0; i < localidades.getElementsByTagName('localidad').length; i++) {
				var id = localidades.getElementsByTagName('localidad')[i].getAttribute('id');
				var nombre = localidades.getElementsByTagName('localidad')[i].getAttribute('nombre');
				
				opt = document.createElement("option");
				opt.setAttribute('id',id);
				opt.setAttribute('value',id);				
				opt.appendChild(document.createTextNode(nombre));
				document.getElementById(span).appendChild(opt);
			}
		}
	}
	ajax.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
	ajax.send( 'categoria=' + categoria );
	
}

function buscaSubcategoriasSelected( categoria, span, idselected ) {

	ajax_cat = nuevoAjax();
	ajax_cat.open('POST', 'http://www.regalosamedida.es/lib/localidadesXML.php', true );
	
	ajax_cat.onreadystatechange = function() {
		if ( ajax_cat.readyState == 4 ) {
		removeOption(span);
        var localidades = ajax_cat.responseXML.documentElement;
			
       	for (var i = 0; i < localidades.getElementsByTagName('localidad').length; i++) {
						
						var id = localidades.getElementsByTagName('localidad')[i].getAttribute('id');
						var nombre = localidades.getElementsByTagName('localidad')[i].getAttribute('nombre');
						
						opt = document.createElement("option");
						opt.setAttribute('id',id);
						opt.setAttribute('value',id);
						if(id == idselected){
								opt.setAttribute('selected','selected');
						}
						opt.appendChild(document.createTextNode(nombre));
						document.getElementById(span).appendChild(opt);
			}

		}
	}
	ajax_cat.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
	ajax_cat.send( 'categoria=' + categoria );
	
	
}

function nuevoAjax(){
	var xmlhttp=false;
	try {
		xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
	} catch (e) {
		try {
			xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
		} catch (E) {
			xmlhttp = false;
		}
	}
	if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
		xmlhttp = new XMLHttpRequest();
	}
	return xmlhttp;
}


/* --- */

function objetoAjax(){
        var xmlhttp=false;


        try {
                xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
                try {
                   xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
                } catch (E) {
                        xmlhttp = false;
                }
        }

        if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
                xmlhttp = new XMLHttpRequest();
        }
        return xmlhttp;
}



function resultado(datos,destino,idprod,lng,campana){

				if(lng=='en'){
					txt = 'Added to your order';
					
					if(campana == 1){
						txtClosedAlt = 'Do not have enough gifts for this product';
					}else{
						txtClosedAlt = 'Do not have enough credits for this product';					
					}	
					
					txtClosed = 'Choose gift';
				}else{
					txt = 'A&ntilde;adido al pedido';
					
					if(campana == 1){
						txtClosedAlt = 'No dispones de los regalos suficientes para este producto';
					}else{
						txtClosedAlt = 'No dispones de los puntos suficientes para este producto';						
					}
					txtClosed = 'Elegir regalo';
				}

        divResultado = document.getElementById(destino);
        divBoxPedido = document.getElementById("elementos-boxpedido");
        anterior = divResultado.innerHTML;
        
        ajax=objetoAjax();
        ajax.open("GET", datos);
        ajax.onreadystatechange=function() {
                if (ajax.readyState==4) {
                        divResultado.innerHTML = ajax.responseText;
												divBoxPedido.innerHTML = ajax.responseText;                        
                        
                        if (anterior != divResultado.innerHTML){
                        		document.getElementById('carrito'+idprod).innerHTML = '<span class="bt_carrito-off">'+txt+'</span>';
                        		
                        		//alert('loading...');
                        		 $("#boxPedido").gbxShow();
															getTop();
                        }else{
														document.getElementById('carrito'+idprod).innerHTML = '<span class="bt_carrito-closed">'+txtClosed+'</span><span class="nopuntos">'+txtClosedAlt+'</span>';
														//document.getElementById('carrito'+idprod).innerHTML = '<span class="bt_carrito-closed">'+txtClosed+'</span>';
														//alert('<span class="bt_carrito-closed">'+txtClosed+'</span> <div class="nopuntos">' + txtClosedAlt +'</div>');
														//alert(txtClosedAlt);
                      	}
                }
        }
        ajax.send(null);
}

function getTop() {
		if (document.documentElement && !document.documentElement.scrollTop)
			top2 = 200;
		// IE6 +4.01 but no scrolling going on
		else if (document.documentElement && document.documentElement.scrollTop)
			top2 = document.documentElement.scrollTop+200;
		// IE6 +4.01 and user has scrolled
		else if (document.body && document.body.scrollTop)
			top2 = document.body.scrollTop+200;
	// IE5 or DTD 3.2 
	
//		var top2 = document.body.scrollTop + 200;//+ ($('html,body').height()-o.height)/2;
		//alert(top2);
		document.getElementById('boxPedido').style.top = top2 + 'px';
	  }


function resultadoEliminar(datos,inicio,destino,cuantos){

				/*if(lng='en'){
					txt = 'Selected gift';
				}else{
					txt = 'Regalo seleccionado';
				}*/

        divResultado = document.getElementById(destino);
        //anterior = divResultado.innerHTML;
        
        ajax=objetoAjax();
        ajax.open("GET", datos);
        ajax.onreadystatechange=function() {
                if (ajax.readyState==4) {
                				cuantos--;
                        divResultado.innerHTML = ajax.responseText;
                        document.getElementById('elementos-carrito').innerHTML = '(' + cuantos + ')';
												//document.getElementById('elementos-boxpedido').innerHTML = cuantos;                        
                        if (cuantos == 0) document.location.href = inicio;
                        //if (anterior != divResultado.innerHTML) document.getElementById('carrito'+idprod).innerHTML = '<span class="bt_carrito-off">'+txt+'</span>';
                }
        }
        ajax.send(null);
}

function resultado_exec(datos,destino,seccion,item){

	// Esto especificamente lo qeu hace es activar el seccion e item adecuado para el calendario, con eval...

        divResultado = document.getElementById(destino);
        ajax=objetoAjax();
        ajax.open("GET", datos);
        ajax.onreadystatechange=function() {
                if (ajax.readyState==4) {
                        divResultado.innerHTML = ajax.responseText
                }
        }
        ajax.send(null);

	allamar = ' { inputField : "seccion_item_fecha", ifFormat : "%Y/%m/%d", button : "f_trigger_c" } ';

//	alert ("Seccion "+seccion+" e item "+item);

//	eval (' Calendar.topota('+seccion+','+item+'); '); 

//                   Calendar.setup({
//                    inputField     :    "seccion_item_fecha_<?php echo ($seccion."_".$parametro); ?>",
//                    ifFormat       :    "%Y/%m/%d",      // format of the input field
//                    button         :    "f_trigger_c_<?php echo ($seccion."_".$parametro); ?>",
//                    align          :    "Tl",           // alignment (defaults to "Bl")
//                    singleClick    :    true
//                   });



}



function resultadoForm(url, formid){

         var Formulario = document.getElementById(formid);
         var longitudFormulario = Formulario.elements.length;
         var cadenaFormulario = ""
         var sepCampos
         sepCampos = ""
         for (var i=0; i <= Formulario.elements.length-1;i++) {
                         //Si estamos en los checkbox de servicios, vemos cuales est?n checkeados
                         if (Formulario.elements[i].name == 'servicios') {
                                 if (Formulario.elements[i].checked == true) {
                                         cadenaFormulario += sepCampos+Formulario.elements[i].name+'='+encodeURI(Formulario.elements[i].value);
                                 }
                         }
                         //... si no, adjuntamos el par?metro=valor en la cadena
                         else {
                        cadenaFormulario += sepCampos+Formulario.elements[i].name+'='+encodeURI(Formulario.elements[i].value);
                         }
             sepCampos="&";
                  }
  peticion=objetoAjax(); // roma
  peticion.open("POST", url, true);
  peticion.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=ISO-8859-1');
  peticion.onreadystatechange = function () {
        document.location.href='#r';
        if (peticion.readyState == 4) {
     document.getElementById('resultados').innerHTML = peticion.responseText;
         //document.location.href='#r';
         tb_init($("#resultados")[0]); // roma
        }
  }

        peticion.send(cadenaFormulario);


}

function productosPedido(datos){
	
	divResultado = document.getElementById('div_carrito');         
	ajax=objetoAjax();
	ajax.open("GET", datos);
	ajax.onreadystatechange=function() {
		if (ajax.readyState==4) {
			divResultado.innerHTML = ajax.responseText;
			//divResultado.innerHTML = 'hola';
		}
	}
	ajax.send(null);

}

function carritoProductos(datos){

	divResultado = document.getElementById('carrito-cuerpo');     
        
	ajax=objetoAjax();
	ajax.open("GET", datos);
	ajax.onreadystatechange=function() {
		if (ajax.readyState==4) {
			divResultado.innerHTML = ajax.responseText;
			acordeon();
			elementosCarrito();
			updateBt($("#accion").val(),$("#id_elemento_tratado").val());
		}
	}
	ajax.send(null);
	
	if(datos.indexOf('?') != -1) acordeonScroll();

}

function updateBt(accion,idelemento){
	
	switch(accion){
		case 'insert':
			$("#carrito"+idelemento).html("<span class='bt_carrito-off'>"+obj.bt_off+"</span>");
			break;
		case 'delete':
			$("#carrito"+idelemento).html("<a class='bt_carrito' href='javascript:carritoProductos(\"http://www.regalosamedida.es/carrito-productos.php?accion=insert&amp;id_elemento="+idelemento+"\")'>"+obj.bt_on+"</a>");
			break;
	}
	
}

function elementosCarrito(){
	
	divResultado = document.getElementById('elementos-carrito');
        
	ajax=objetoAjax();
	ajax.open("GET", 'http://www.regalosamedida.es/elementos-carrito.php');
	ajax.onreadystatechange=function() {
		if (ajax.readyState==4) {
			divResultado.innerHTML = '('+ajax.responseText+')';
		}
	}
	ajax.send(null);
	
}

function acordeon(id) {
		$(".acor").click(function() {
			acordeon($(this).attr("id"));
		});
		
		if (!id) {
			$(".acor-content").hide();
			$(".acor").css('cursor','pointer');
			$("#acor-content1").slideDown();
			$("#acor-content1").parent().addClass('item-carrito-on');
			activo = 1;
		}
		if ((id != "acor"+activo) && id) {
			$("#acor-content"+activo).slideUp();
			$("#acor-content"+activo).parent().removeClass('item-carrito-on');
			activo = id.replace("acor","")
			$("#acor-content"+activo).slideDown();
			$("#acor-content"+activo).parent().addClass('item-carrito-on');
		};		

}

function acordeonScroll() {
	offset = $("#carrito-top").offset();
	$("html").animate({scrollTop:offset.top-30}, 700) 	
}

function actualizaUnidades(id_producto,unidades,op){
	
	cerrado = false;
	divCosteCompra = document.getElementById('coste_compra');
	divCreditoDisponible = document.getElementById('credito_disponible');
	
	unidades = parseInt(unidades);
	
	switch(op){
		case 'add':
			unidades = unidades + 1;
			break;
		case 'minus':
			if(unidades!=1){
				unidades = unidades - 1;
			}else{
				cerrado = true;
			}
			break;
	}
	
	if(!cerrado){

			ajax=objetoAjax();
			ajax.open("GET", 'http://www.regalosamedida.es/actualiza-unidades.php?id_producto='+id_producto+'&unidades='+unidades);
			ajax.onreadystatechange=function() {
				if (ajax.readyState==4) {
					cadenaRespuesta = ajax.responseText;
					
					if(cadenaRespuesta){
						divCreditoDisponible.innerHTML = cadenaRespuesta.substring(cadenaRespuesta.indexOf('{')+1,cadenaRespuesta.indexOf(':'));
						divCosteCompra.innerHTML = cadenaRespuesta.substring(cadenaRespuesta.indexOf(':')+1,cadenaRespuesta.indexOf('}'));
						
						inputUnidades = document.getElementById('unidades_'+id_producto);
						inputUnidades.value = unidades;
					}
					
				}
			}
			ajax.send(null);
	}
		
}

function productosCheques(id_producto,id_proveedor){
	
	datos = 'http://www.regalosamedida.es/productos-cheques.php?id_producto='+id_producto+'&id_proveedor='+id_proveedor;
	divProductos = document.getElementById('datos_cheque_'+id_proveedor); 
	
	ajax_p=objetoAjax();
	ajax_p.open("GET", datos);
	ajax_p.onreadystatechange=function() {
		if (ajax_p.readyState==4) {
			
			//divProductos.innerHTML = ajax_p.responseText;
			
			$('#datos_cheque_'+id_proveedor).fadeOut('normal', function(){
				//$('#datos_cheque_'+id_proveedor).html() = ajax_p.responseText;
				divProductos.innerHTML = ajax_p.responseText;
				$('#datos_cheque_'+id_proveedor).fadeIn();
			});
			
		}
	}
	
	ajax_p.send(null);

}

function compruebaDOC(doc,codigo) {

	datos = 'http://www.regalosamedida.es/comprueba_DNI.php?doc='+doc+'&codigo='+codigo;
	divDNI = document.getElementById('numero-documento'); 
	inputDNI = document.getElementById('dni'); 
	
	ajax_p = objetoAjax();
	ajax_p.open("GET", datos);
	ajax_p.onreadystatechange=function() {
		if (ajax_p.readyState == 4) {
			if (ajax_p.responseText == 0){
				divDNI.innerHTML = '<img src="http://www.regalosamedida.es/images/warning.png" alt="El tipo o el número de documento no son correctos" title="El tipo o el número de documento no son correctos" />';
				//$("#dni").addClass('error');
				$("#dni").val('');
			}else{
				divDNI.innerHTML = '<img src="http://www.regalosamedida.es/images/check.png" />';
			}
		}
	}
	
	ajax_p.send(null);
	
}
