/***** Cargar datos principales ****/
		//var Cajas=["Localidades","Maritima","Satelite","MedioPrazo","Modelos","Estacions","Novas","Mareas"];
		var Cajas=["Localidades","Satelite","Novas","Estacions","Modelos","Maritima","Mareas","MedioPrazo"];
		var estados=new Array();
		var estadosApertura=new Array();
		initArray(estados,0,Cajas.length);
		initArray(estadosApertura,0,Cajas.length);
		for (var i=3;i<Cajas.length;i++){
			estadosApertura[i]=1;
		}
		
		var editMarea=dojo.cookie("editMarea");
		editMarea=inArray(editMarea,6);
		
		var editLoc=dojo.cookie("editLoc");
		editLoc=inArray(editLoc,1);
		
		var editMar=dojo.cookie("editMar");
		editMar=inArray(editMar,3);
		
		var editMp=dojo.cookie("editMp");
		editMp=inArray(editMp,1);
		
		var editModelosTipo=dojo.cookie("editModelosTipo");
		editModelosTipo=inArray(editModelosTipo,10);
		var editModelosZona=dojo.cookie("editModelosZona");
		editModelosZona=inArray(editModelosZona,11);
		
		
		//var nEst;
		//var estArr;
		var idMitad=4;
		var estacionesEstadoActual;
		var editEstacion=dojo.cookie("editEstacion");
		//arrayEstaciones();


		
		
/* Función que llena los contendores. 
Recibe:		nada
Devuelve:	nada
*/
function init() {
	/*node_creator, a partir de un data genera una caja*/
	var node_creator = function(data) {
		var texto="";
		var imgClose="images/principal/bullet.png";
		var imgOpen="images/principal/bulletUp.png";
		var img=imgOpen;
		var alt;
		
		/*Si el estado es 1, la caja debe estar cerrada*/	
		if (estadosApertura[devuelveIndice(Cajas,data)]==1){
			dojo.addClass(dojo.byId(data), "hide");
			dojo.byId('img'+data).src=imgClose;
		}else{
			switch (data){
				case "Modelos":
					cargarModelos();
					break;
				case "MedioPrazo":
					cargarMPrazo();
					break;
				case "Localidades":
					cargarLocalidad();
					break;
				case "Maritima":
					cargarMaritima();
					break;
				case "Estacions":
					cargarPrimeraEstacion(editEstacion);
					break;
				case "Mareas":
					cargarMarea();
					break;
			}	

		}	
		

		switch(data){
			case "dragNode":
				alt=dojo.dnd.manager().dragAlt;
				if (alt==0){alt=200;}
				texto="<div class=\"dojoDndDragNode\" style=\"height:"+alt+"px\"></div>";
				break;
			
			case "Localidades":
				texto=dojo.byId('divLocalidades').innerHTML;
				break;
			case "Satelite":
				texto=dojo.byId('divSatelite').innerHTML;
				break;
			case "Novas":
				texto=dojo.byId('divNovas').innerHTML;
				break;
			case "Estacions":
				texto=dojo.byId('divEstaciones').innerHTML;
				break;
			case "MedioPrazo":
				texto=dojo.byId('divMedioPlazo').innerHTML;
				break;
			case "Maritima":
				texto=dojo.byId('divMaritima').innerHTML;
				break;
			case "Modelos":
				texto=dojo.byId('divModelos').innerHTML;
				break;
			case "Mareas":
				texto=dojo.byId('divMareas').innerHTML;
				break;
		}

		var node = dojo.doc.createElement("div");
		if (texto.length>0) node.innerHTML = texto;
		node.id = dojo.dnd.getUniqueId();
		
		if (data=="dragNode"){
			node.id ="dragNode";
		}
		               
       	return {node: node, data: data, type: [""]};
 	};
	
	/*Crea contenedores(objetos Source)*/
	ce1 = new dojo.dnd.Source("c1", {creator: node_creator,accept: [""], withHandles:"true",delay:2,singular:"true"});
	ce2 = new dojo.dnd.Source("c2", {creator: node_creator,accept: [""], withHandles:"true",delay:2,singular:"true"});
	ce3 = new dojo.dnd.Source("c3", {creator: node_creator,accept: [""], withHandles:"true",delay:2,singular:"true"});
	
	/*Lectura de cookies*/
	var col1=dojo.cookie("c1");
	var col2=dojo.cookie("c2");
	var col3=dojo.cookie("c3");
	/*console.debug("columna 1 is "+col1);
	console.debug("columna 2 is "+col2);
	console.debug("columna 3 is "+col3);*/
    
    /*Rellena los contenedores con las cajas de las cookies*/
	addCajasCookie(col1,ce1);
	addCajasCookie(col2,ce2);
	addCajasCookie(col3,ce3);
	
	//si no hay cookies se cargan los contenedores por defecto
	if ((col1==null && col2==null && col3==null) 
		|| (col1.length==0 && col2.length==0 && col3.length==0) 
		|| (!dojo.cookie.isSupported())) {
		

		llenarContenedores(Cajas);
		initArray(estados,1,Cajas.length);
	}
	
	/*Comprueba que cajas de las que se deben mostrar no se han añadido y las añade*/
	//var ar=hashCajasPer.keys();
	var j=0,i=0;
	var array1 = new Array(); 
	
	for (i in estados){
		if (estados[i]==0){
			array1[j]=Cajas[i];
			estados[i]=1;
			j++;
		}
	}
	/*for (i in array1){
		//hashCajasEstado.put(ar[i],0);
		
	}*/	
	llenarContenedores(array1);	
	
	/*Actualizo cookies despues de cargar los contenedores*/
	UpdateCookie(ce1);
	UpdateCookie(ce2);
	UpdateCookie(ce3);

	//si pongo esta función dentro del init, la ejecuta antes de terminar el dragAndDrop
 	dojo.subscribe("/dnd/drop", 
		function(){
			UpdateCookie(ce1);
			UpdateCookie(ce2);
			UpdateCookie(ce3);
		}
	);
};    

/*Función que recorre los elementos de la columna después de leer la cookie.
Convierte un string recibido en un array, recorre el array, extrae el nombre de la caja y el 
estado y si la caja no existe en hashCajasEstado, la añade y modifica el estado a añadido. 
También añade la caja al contenedor
Recibe:	un string con el contenido de la cookie
Devulver: nada.
*/
function addCajasCookie(col,contenedor){
	if (col!=null && col.length>0){
		var acol = col.split("::");
		var i;
		for (i=0;i<acol.length;i++){
			var unaCaja=acol[i];
			var caja= unaCaja.substring(0,unaCaja.indexOf(','));
			var est=unaCaja.substring(unaCaja.indexOf(',')+1);
			var id=devuelveIndice(Cajas,caja);
	
			if (estados[id]==0){
				//console.debug("estados[id]:"+estados[id]+' '+id);
				estados[id]=1;
				estadosApertura[id]=est;
				contenedor.insertNodes(null,[caja]);
			}
		}
	 }
}

/*Función que llena los contenedores en orden(una al uno, otra al dos y otra al tres)
Redibe:		array con cajas para llenar
Devuelve:	nada*/
function llenarContenedores(array){
		var n=parseInt(array.length/3);
		var r=array.length % 3;
		var i=0;
		
		while(i<n*3){
			ce1.insertNodes(null,[array[i]]);
			ce2.insertNodes(null,[array[i+1]]);
			ce3.insertNodes(null,[array[i+2]]);
			i+=3;
		}
		
		if (r==1){
			ce3.insertNodes(null,[array[i]]);
		}else if (r==2){
			ce3.insertNodes(null,[array[i]]);
			ce1.insertNodes(null,[array[i+1]]);
		}
}


function initArray(array,v,tope){
var i=0;
	while(i<tope){
		array[i]=v;
		i++;
	}
}

function devuelveIndice(array,key){
var i=0;
	for(i in array){
		if (array[i]==key){
			return i;
		}
	}
	return -1;
}


  	
/**Función que permite que se desplieguen y replieguen. Además de modificar la imagen que se
muestra en las cajas, actualiza la tabla hashCajasEstado y la cookie del contenedor actual.
Recibe: 	el id de la caja, y la imagen.
Devuelve:	nada.
*/
function doAnimation(nombre,img) {
  	var wipeOut = dojo.fx.wipeOut({node: nombre,duration: 500});
  	var wipeIn = dojo.fx.wipeIn({node: nombre,duration: 500});
  	var currentAnimation;
  	var imgClose="images/principal/bullet.png";
  	var imgOpen="images/principal/bulletUp.png";
  	
  	var caja =document.getElementById(nombre);
  
  	//estado: 0--> deplegado
	//		  1--> replegado
		
    //Si la caja se acaba de cargar, no tiene asignada la clase hide, 
    //hay que poner el display  a none.
  	if (caja.className.indexOf("hide")!=-1 ){
	  	dojo.removeClass(caja, "hide");
		caja.style.display="none";	
  	}
  	
  	if ( caja.style.display=="none"){
  		currentAnimation = wipeIn;
		img.src=imgOpen;
		/*hashCajasEstado.remove(nombre);
		hashCajasEstado.put(nombre,0);*/
		estadosApertura[devuelveIndice(Cajas,nombre)]=0;

		dojo.query("."+nombre).forEach(
			function(i,index) {
        			dojo.removeClass(i, "hide");
   			});
		
		switch (nombre){
			case "Modelos":
				cargarModelos();
				break;
			case "MedioPrazo":
				cargarMPrazo();
				break;
			case "Localidades":
				cargarLocalidad();
				break;
			case "Maritima":
				cargarMaritima();
				break;
			case "Estacions":
				cargarPrimeraEstacion(editEstacion);
				break;
			case "Mareas":
				cargarMarea();
				break;
		}	
  	}else{
  		currentAnimation = wipeOut;
		img.src=imgClose;
		estadosApertura[devuelveIndice(Cajas,nombre)]=1;

		dojo.query("."+nombre).forEach(
			function(i,index) {
				if (index==1){
        			dojo.addClass(i, "hide");
        		}
   			});
  	}
    
    //Play the animation. Without this call, it will not run.
    currentAnimation.play();
	
	switch (caja.parentNode.parentNode.id){
		case "c1":
			UpdateCookie(ce1);
			break;
		case "c2":
			UpdateCookie(ce2);
			break;
		case "c3":
			UpdateCookie(ce3);
			break;
	}
};

/*Función que actualiza la cookie que guarda la posición y el estado de las cajas.
Recibe: 	el contenedor que se va a guardar
Devuelve:	nada
*/
function UpdateCookie(contenedor){
	var cad ="";
	
	var nodos = contenedor.getAllNodes();
	var tam = nodos.length;
	
	for(var i = 0; i < tam; ++i){
		if (nodos[i].id!="dragNode"){
			var caja=contenedor.map[nodos[i].id].data;
			cad += "::"+caja;
			if (estadosApertura[devuelveIndice(Cajas,caja)]==1){
				cad += ",1"
			}else
				cad +=",0";
		}
	}
	cad=cad.substring(2);
	dojo.cookie(contenedor.parent.id,cad,{expires: 1460}); //cookie caduca a los 4 años
}

function modelosseleccion(){
	
	formu=dojo.byId("formModelos");
	
	  for (i=0;i<formu.zona.length;i++){
						  	
			if (formu.zona[i].value==editModelosZona){
				formu.zona[i].checked=true;
				break;
	    	} 	
	    }
	    
	  for (i=0;i<formu.tipo.length;i++){
			if (formu.tipo[i].value==editModelosTipo){
				formu.tipo[i].checked=true;
				break;
	    	} 	
	    }
}

/*Función que comprueba si las zonas son correctas.
  Recibe: 	idZona y el tipo de zona
  Devuelve:	idZona si es correcto y un id por defecto en otro caso*/
function inArray(id,tipo){
	var array;
	var idBase;
	switch (tipo){
		case 1: //Localidades
			array=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,30,38,39];
			idBase=3;
			break;
		case 3: //Mar
			array=[31,32,33,34];
			idBase=31;
			break;
		case 7: //MedioPlazo
			array=[35,36,37];
			idBase=35;
			break;
		case 6: //Mareas
		    array=[1,3,4,5,6,7,8,9,10,11,12,13];
			idBase=1;
			break;
		/*case 8://Estaciones
			array=Estaciones;
			idBase=10045;
			break;*/
		case 11: //ModelosZonas
			array=[35,31,32,33,34];
			idBase=35;
			break;
		case 10: //ModelosTipo
			array=[1,2,3]; //(1->tmax, 2->tmin,3->precipitacion)
			idBase=1;
			break;
	}

	for(i in array) {
		if (id==array[i]){
			return id;
		}
	}

	return idBase;
}

function arrayEstaciones(){
		if (!editEstacion || editEstacion==0){
			//estArr=Estaciones;
			cargarPrimeraEstacion(-1);
		}else{
			//estArr=[inArray(editEstacion,8)];
			cargarPrimeraEstacion(editEstacion);
		}
}

function aceptarModelo(formu){
	formu=dojo.byId("formModelos");

		for (i=0;i<formu.tipo.length;i++){
			if (formu.tipo[i].checked){
				editModelosTipo=formu.tipo[i].value;
				break;
	    	} 	
	    }
	    for (i=0;i<formu.zona.length;i++){
			if (formu.zona[i].checked){
				editModelosZona=formu.zona[i].value;
				break;
	    	} 	
	    }
	    
	    cargaModelo(editModelosTipo,editModelosZona);
	}

function cargarCajas(){
	/*cargarModelos();
	cargarMPrazo();
	cargarLocalidad();
	cargarMaritima();
	cargarPrimeraEstacion(editEstacion);
	cargarMarea();*/
	
}


function cargarMarea() { 
	dojo.byId("linkRSSMareas").href="RSS/rssMareas.action?idPorto="+editMarea;
	dojo.xhrGet( {
        url: "principal/listMareas.action", 
        content:{idPorto:editMarea, request_locale:locale},
        handleAs: "text",
        timeout: 8000, // Time in milliseconds

        // The LOAD function will be called on a successful response.
        load: function(response, ioArgs) { 
          	dojo.query(".aMareas").forEach(
			function(i) {
        		i.innerHTML = response;
   			});
          	return response; 
        },

        // The ERROR function will be called in an error case.
        error: function(response, ioArgs) { 
          	console.error("HTTP status code: ", ioArgs.xhr.status); 
          	dojo.query(".aMareas").forEach(
        			function(i) {
                		i.innerHTML = dojo.byId("divError").innerHTML; 
           			});
          	return response;
        }
     });
}


function cargarLocalidad() { 
	dojo.byId("linkRSSloc").href="RSS/rssLocalidades.action?idZona="+editLoc+"&dia=-1";
	dojo.xhrGet( {
        url: "principal/listLocalidades.action", 
        content:{idZona:editLoc,idTipo:"1",dia:"0", request_locale:locale},
        handleAs: "text",
        timeout: 8000, // Time in milliseconds

        // The LOAD function will be called on a successful response.
        load: function(response, ioArgs) { 
          	dojo.query(".aLocalidades").forEach(
			function(i) {
        		i.innerHTML = response;
   			});
          	return response; 
        },

        // The ERROR function will be called in an error case.
        error: function(response, ioArgs) { 
          	console.error("HTTP status code: ", ioArgs.xhr.status); 
          	dojo.query(".aLocalidades").forEach(
        			function(i) {
                		i.innerHTML = dojo.byId("divError").innerHTML; 
           			});
          	return response;
        }
     });
}
function cargarMaritima() {
	dojo.byId("linkRSSmar").href="RSS/rssMaritima.action?idZona="+editMar+"&dia=-1";
   	dojo.xhrGet( {
        url: "principal/listMaritima.action", 
        content:{idZona:editMar,idTipo:"3",dia:"0",request_locale:locale},
        handleAs: "text",
        timeout: 8000, // Time in milliseconds

        // The LOAD function will be called on a successful response.
        load: function(response, ioArgs) { 
          	dojo.query(".aMaritima").forEach(
			function(i) {
        		i.innerHTML = response;
   			});
          	return response; 
        },

        // The ERROR function will be called in an error case.
        error: function(response, ioArgs) {
          	console.error("HTTP status code: ", ioArgs.xhr.status); 
        	dojo.query(".aMaritima").forEach(
        			function(i) {
                		i.innerHTML = dojo.byId("divError").innerHTML; 
           			});
          	return response; 
        }
     });
}

function cargarMPrazo() {
	dojo.byId("linkRSSmp").href="RSS/rssLocalidades.action?idZona="+editMp+"&dia=-1";
	dojo.xhrGet( { 
        //content:{idZona:editMp,idTipo:"7",dia:"-1" },
        url: "principal/listMPrazo.action", 
        content:{idZona:editMp, request_locale:locale},
        handleAs: "text",
        timeout: 8000, // Time in milliseconds
		
        // The LOAD function will be called on a successful response.
        load: function(response, ioArgs) { 
          	dojo.query(".aMPrazo").forEach(
			function(i) {
        		i.innerHTML = response;
   			});
          	return response; 
        },

        // The ERROR function will be called in an error case.
        error: function(response, ioArgs) { 
          	console.error("HTTP status code: ", ioArgs.xhr.status);
          	dojo.query(".aMPrazo").forEach(
        			function(i) {
                		i.innerHTML = dojo.byId("divError").innerHTML; 
           			});
          	return response; 
        }
     });
}
   
function cargarEstacionesPorProvincia(p) {
	dojo.xhrGet( { 
        url: "principal/listIdEstProvincia.action", 
        content:{prov:p,request_locale:locale},
        handleAs: "text",
        timeout: 8000, // Time in milliseconds

        // The LOAD function will be called on a successful response.
        load: function(response, ioArgs) { 
        	dojo.byId("aEstaciones").innerHTML = response; 
        	return response; 
        },

        // The ERROR function will be called in an error case.
        error: function(response, ioArgs) { 
          	console.error("HTTP status code: ", ioArgs.xhr.status); 
          	dojo.query(".aEstaciones").forEach(
        			function(i) {
                		i.innerHTML = dojo.byId("divError").innerHTML; 
           			});
          	return response; 
        }
     });
} 
  

function cargarPrimeraEstacion(idEst) {
	if (idMitad==1){
		idMitad=2;
	}else if (idMitad==2) {
		idMitad=3;
	}else if (idMitad==3) {
		idMitad=4;
	}else if (idMitad==4) {
		idMitad=1;
	}
	dojo.xhrGet( { 
        url: "observacion/json.action", 
        content:{mitad:idMitad,idEstacion:idEst},
        handleAs: "json",
        timeout: 8000, // Time in milliseconds

        // The LOAD function will be called on a successful response.
        load: function(response, ioArgs) { 
		        estacionesEstadoActual=response;
		        /********/
		    	dojo.xhrGet( { 
		            url: "principal/listUnaEstacion.action", 
		            content:{idEst:estacionesEstadoActual.estacionesEstadoActual[0].idEstacion, nEst:estacionesEstadoActual.estacionesEstadoActual.length,request_locale:locale},
		            handleAs: "text",
		            timeout: 8000, // Time in milliseconds

		            // The LOAD function will be called on a successful response.
		            load: function(response, ioArgs) { 
		            	dojo.query(".aEstaciones").forEach(
		            			function(i) {
		            				i.innerHTML = response; 
		               			});	
		              	initBanner();
		              	return response; 
		            },

		         // The ERROR function will be called in an error case.
		            error: function(response, ioArgs) { 
		              	dojo.query(".aEstaciones").forEach(
		            			function(i) {
		                    		i.innerHTML = dojo.byId("divError").innerHTML; 
		               			});
		              	console.error("HTTP status code: ", ioArgs.xhr.status);
		              	return response;
		            }
		         });
		        /*******/
		        
		        return response; 
		},
		// The ERROR function will be called in an error case.
        error: function(response, ioArgs) { 
        	console.debug("Estoy aquí2"+ dojo.byId("divError").innerHTML);
           	dojo.query(".aEstaciones").forEach(
        			function(i) {
                		i.innerHTML = dojo.byId("divError").innerHTML; 
           			});
          	console.error("HTTP status code: ", ioArgs.xhr.status); 
          	return response;
        }
 	});
	
}
   
function cargarModelos() {
		var zonaModeloV;
		var tipoModeloV;
		var imgModeloV="Web_wrf_arw_d";
	
		switch (editModelosZona){
			case '35': //galicia
				zonaModeloV="galicia";
				break;
			case '31': //coruña
				zonaModeloV="coru";
				break;
			case '32': //lugo
				zonaModeloV="lugo";
				break;
			case '33': //ourense
				zonaModeloV="ourense";
				break;
			case '34': //pontevedra
				zonaModeloV="pontevedra";
				break;
			default:
				zonaModeloV="galicia";
		}
		imgModeloV=imgModeloV+editModelosZona;
		switch (editModelosTipo){
			case '1': //tmax
				tipoModeloV="tmax";
				imgModeloV=imgModeloV+"_tmax";
				break;
			case '2': //tmin
				tipoModeloV="tmin";
				imgModeloV=imgModeloV+"_tmin";
				break;
			case '3': //precipitacion
				tipoModeloV="prec";
				imgModeloV=imgModeloV+"_prec_24h";
				break;
			default:
				tipoModeloV="tmax";
				imgModeloV=imgModeloV+"_tmax";
				
		}
		imgModeloV=imgModeloV+"_sfc_f048.png";
		
	

        dojo.xhrGet( {
        url: "principal/listModelos.action", 
        content:{zonaModelo:zonaModeloV,tipoModelo:tipoModeloV,imgModelo:imgModeloV},
        handleAs: "text",
        timeout: 8000, // Time in milliseconds
		
        // The LOAD function will be called on a successful response.
        load: function(response, ioArgs) { 
          	dojo.query(".aModelos").forEach(
			function(i) {
        		i.innerHTML = response;
   			});
          	return response; 
        },

        // The ERROR function will be called in an error case.
        error: function(response, ioArgs) { 
          	console.error("HTTP status code: ", ioArgs.xhr.status);
        	dojo.query(".aModelos").forEach(
        			function(i) {
                		i.innerHTML = dojo.byId("divError").innerHTML; 
           			});
          	return response; 
        }
     });
}   
      
function editarCaja(data){
	if (data=="Estaciones" && pe!=null) bStop();

	dojo.byId("a"+data).innerHTML=dojo.byId("edit"+data).innerHTML;
	if (data=="Modelos"){
		modelosseleccion();
	}
}

function cargaMarea(marea){
	editMarea=inArray(marea,6);
	
	cargarMarea();
	dojo.cookie("editMarea",editMarea,{expires: 1460});
}

function cargaLocalidad(loc){
	editLoc=inArray(loc,1);
	
	cargarLocalidad();
	dojo.cookie("editLoc",editLoc,{expires: 1460});
}

function cargaZonaMar(z){
	editMar=inArray(z,3);
	
	cargarMaritima();
	dojo.cookie("editMar",editMar,{expires: 1460});
}

function cargaZonaMp(z){
	editMp=inArray(z,1);
	
	cargarMPrazo();
	dojo.cookie("editMp",editMp,{expires: 1460});
}

function cargaEstacion(e){
	dojo.byId("aEstaciones").innerHTML=dojo.byId("cargando").innerHTML;
	editEstacion=e;
	arrayEstaciones();
	dojo.cookie("editEstacion",editEstacion,{expires: 1460});
	bStart();
}


function cargaModelo(tipo,zona){
	dojo.byId("aModelos").innerHTML=dojo.byId("cargando").innerHTML;
	editModelosTipo=tipo;
	editModelosZona=zona;
	cargarModelos();
	dojo.cookie("editModelosTipo",editModelosTipo,{expires: 1460});
	dojo.cookie("editModelosZona",editModelosZona,{expires: 1460});
	
}

function muestraProvincias(){
	var div=dojo.byId("divProvincias");

	if ( div.className.indexOf("hide")!=-1 ){
		dojo.removeClass(div, "hide");
	}else{
		dojo.addClass(div, "hide");
	}
}

function cargaProvinciaEstacion(p){
	dojo.byId("aEstaciones").innerHTML=dojo.byId("cargando").innerHTML;
	cargarEstacionesPorProvincia(p);
}




var pe;
var estIndex = 0;
var tamano;
var finUnaEstacion=50;
var unaEstacion=0;

var delay =3000;

function initBanner(){
	tamano=estacionesEstadoActual.estacionesEstadoActual.length;
	estIndex = 0;
	unaEstacion=0;
	cargarEstacion();
   			
	//Arranca o banner
	bannerEstacions();
}

function bStop(){
	if (pe) {
		setBoton(false);
		pe.stop();
		pe=null;
	}
} 

function bStart(){
	if (!pe){
		setBoton(true);
		bannerEstacions();
	}
} 

function bNext(){
	estIndex++;

	if (estIndex > tamano -1 ){
		estIndex=0;
	}

	 cargarEstacion();
} 

function bPrev(){

	estIndex--;
	if (estIndex <0  ){
		estIndex=tamano-1;
	}

	cargarEstacion();
} 

function cargarEstacion(){
	var est=estacionesEstadoActual.estacionesEstadoActual[estIndex];
	dojo.byId("enlaceEstacion").href="http://www2.meteogalicia.es/galego/observacion/estacions/estacions.asp?idEst="+est.idEstacion;
	
	dojo.byId("tituloEstacion").firstChild.nodeValue=est.nombreEstacion;
	dojo.byId("tituloConcello").firstChild.nodeValue="("+est.concello+")";
	
	var s=dojo.byId("imgIconoCeo").src;
	var ruta=s.substring(0,s.lastIndexOf("/"));
	var sDato=est.iconoCeo;
	var img=sDato.substring(sDato.lastIndexOf("/"),sDato.length);
	dojo.byId("imgIconoCeo").src=ruta+img;
	
	sDato=est.iconoVento;
	img=sDato.substring(sDato.lastIndexOf("/"),sDato.length);
	dojo.byId("imgIconoVento").src=ruta+img;
	
	s=dojo.byId("imgIconoTemp").src;
	ruta=s.substring(0,s.lastIndexOf("/"));
	sDato=est.iconoTemperatura;
	img=sDato.substring(sDato.lastIndexOf("/"),sDato.length);
	dojo.byId("imgIconoTemp").src=ruta+img;
	
	dojo.byId("valorTemp").firstChild.nodeValue=est.valorTemperatura;
	dojo.byId("valorSensacionTermica").firstChild.nodeValue=est.valorSensTermica;
	var ind=est.data.indexOf("T")+1;
	dojo.byId("textoData").firstChild.nodeValue=est.data.substring(ind,ind+5); ;
	
}

function bannerEstacions(){
	if (pe) {
		pe.stop();
		pe=null;
	}
	pe = null;
	pe = new dojox.timing.Timer();
	pe.setInterval(delay);
	pe.onTick =function() {

		if (estIndex > tamano - 2 ){
			estIndex=-1;
			if (editEstacion>-1 && unaEstacion<finUnaEstacion){
				unaEstacion++;
			}else{
				arrayEstaciones();
				unaEstacion=0;
			}
  		}else{
			estIndex++;	
			cargarEstacion();
		}		
	}
	pe.start();
}


function setBoton( running ){
	var idStart ="start";
	var idStop ="stop";
	if(running){
		dojo.query(".stop").forEach(
			function(i) {
        		i.src = i.src.replace( "_on.png",".png" );
   			});	
   		dojo.query(".start").forEach(
			function(i) {
        		i.src = i.src.replace( ".png","_on.png" );
   			});
	}else{
		dojo.query(".stop").forEach(
			function(i) {
    			i.src = i.src.replace( ".png","_on.png" );
   			});	
   		dojo.query(".start").forEach(
			function(i) {
        		i.src = i.src.replace( "_on.png",".png" );
   			});	
	}
}

//Extensión del manager de dojo
dojo.declare("dojo.dnd.Manager", dojo.dnd.Manager, {
	// Añado los cambios necesarios para que se muestre un dragNode 
		// summary: the manager of DnD operations (usually a singleton)
		constructor: function(){
			this.avatar  = null;
			this.source = null;
			this.nodes = [];
			this.copy  = true;
			this.target = null;
			this.canDropFlag = false;
			this.events = [];
			//**********************
			this.ModoDrag=true;
			if (this.ModoDrag){
				this.dragDato=null;
				this.theNodeCheck=null;
				this.theNodeBefore=null;
				this.dragAlt=null;
				this.dragCont=null;
				
				this.dragEspacioX=null;
				this.dragEspacioY=null;
			}
			//**********************
		},

		// avatar's offset from the mouse
		OFFSET_X: 2,
		OFFSET_Y: 2,
		
		// methods
		startDrag: function(source, nodes, copy,e){
			// summary: called to initiate the DnD operation
			// source: Object: the source which provides items
			// nodes: Array: the list of transferred items
			// copy: Boolean: copy items, if true, move items otherwise
			
			this.source = source;
			this.nodes  = nodes;
			this.copy   = Boolean(copy); // normalizing to true boolean
			this.avatar = this.makeAvatar();
			dojo.body().appendChild(this.avatar.node);
			dojo.publish("/dnd/start", [source, nodes, this.copy]);
			this.events = [
				dojo.connect(dojo.doc, "onmousemove", this, "onMouseMove"),
				dojo.connect(dojo.doc, "onmouseup",   this, "onMouseUp"),
				dojo.connect(dojo.doc, "onkeydown",   this, "onKeyDown"),
				dojo.connect(dojo.doc, "onkeyup",     this, "onKeyUp")
			];
			var c = "dojoDnd" + (copy ? "Copy" : "Move");
			dojo.addClass(dojo.body(), c); 
			
			//****************
			if (this.ModoDrag){
				//Crear el nodo dragNode;
				this.dragDato=source.getItem(nodes[0].id).data;
				this.dragAlt=nodes[0].offsetHeight;
				//console.debug('alt: '+nodes[0].id+', '+(nodes[0]).offsetHeight);
		
				this.dragEspacioX=e.pageX-(nodes[0].offsetLeft+nodes[0].offsetParent.offsetLeft);
				this.dragEspacioY=e.pageY-(nodes[0].offsetTop+nodes[0].offsetParent.offsetTop);
				//console.debug(e.pageY+', '+nodes[0].offsetTop+', '+nodes[0].offsetParent.offsetTop);

				this.dragCont=this.source;
				this.source.insertNodes(false, ['dragNode'],true, nodes[0]);
			
				this.source.deleteSelectedNodes();
			}
			//************
		},
			stopDrag: function(){
			// summary: stop the DnD in progress
			dojo.removeClass(dojo.body(), "dojoDndCopy");
			dojo.removeClass(dojo.body(), "dojoDndMove");
			dojo.forEach(this.events, dojo.disconnect);
			
			this.events = [];
			this.avatar.destroy();
			this.avatar = null;
			this.source = null;
			this.nodes = [];
			//**************************
			if (this.ModoDrag){

				if (this.dragCont.getItem('dragNode')){
					this.dragCont.delItem('dragNode');
					dojo._destroyElement('dragNode');
					this.dragCont._removeSelection();
				}
				
				this.dragDato=null;
				this.theNodeCheck=null;
				this.theNodeBefore=null;
				this.dragAlt=null;
				this.dragCont=null;
			
				this.dragEspacioX=null;
				this.dragEspacioY=null;
			}
			//****************************
		},
		// keyboard event processors
		onKeyDown: function(e){
			// summary: event processor for onkeydown:
			//	watching for CTRL for copy/move status, watching for ESCAPE to cancel the drag
			// e: Event: keyboard event
			if(this.avatar){
				switch(e.keyCode){
					case dojo.keys.CTRL:
						var copy = Boolean(this.source.copyState(true));
						if(this.copy != copy){ 
							this._setCopyStatus(copy);
						}
						break;
					case dojo.keys.ESCAPE:
						dojo.publish("/dnd/before/cancel");
						dojo.publish("/dnd/cancel");
						this.stopDrag();
						break;
				}
			}
		},
		onMouseUp: function(e){
			// summary: event processor for onmouseup
			// e: Event: mouse event
		
			if(this.avatar && (!("mouseButton" in this.source) || this.source.mouseButton == e.button)){
				if(this.target && this.canDropFlag){
					var params = [this.source, this.nodes, Boolean(this.source.copyState(dojo.dnd.getCopyKeyState(e))), this.target];
					dojo.publish("/dnd/drop/before", params);
					dojo.publish("/dnd/drop", params);
				}else{
					dojo.publish("/dnd/before/cancel");
					dojo.publish("/dnd/cancel");
				}
				this.stopDrag();
			}
		},
		onMouseMove: function(e){
			// summary: event processor for onmousemove
			// e: Event: mouse event
			var a = this.avatar;
			if(a){
				
				//*************************** Inicio
				if (this.ModoDrag){
				//	Buscamos el nodo justo anterior al puntero del ratón
					that = this;
					theNode = null;
					theNodeInsertar=0;
					theBestDist = NaN;
					if (this.target){
					//console.debug('entro:'+this.target.parent.id+', '+this.target.getAllNodes().length);
					/*if (this.target && !this.target.current && this.target.getAllNodes().length==0) {
						//console.debug('estoy vacio');
								that.source.delItem('dragNode');
								dojo._destroyElement('dragNode');
								
								this.dragCont._changeState("Container", "");
								this.dragCont=this.target;
								this.dragCont._changeState("Container", "Over");
								this.target.insertNodes(false, ['dragNode']);
					}*/
						if ((this.target && !this.target.current && this.target.getAllNodes().length==0) //si el contenedor está vacio
						||(that.theNodeCheck && this.target.current  
							&& (that.theNodeCheck!=this.target.current  //sólo se inserta el dragNode si el current es distinto al de referencia, para evitar insercciones innecesarias
								|| that.theNodeBefore!=this.target.before) 
							&& this.target.current.id!='dragNode')){//sólo se inserta si el current no es el dragNode
						
						//console.debug('entro tb');
						
							if (this.target.current){
								/*if (that.theNodeCheck){
									console.debug('---'+that.theNodeCheck.id+', '+this.target.current.id+', '+that.thenNodeBefore+', '+this.target.before);
								}else{
									console.debug('theNodecheck no existe');}*/

								that.source.delItem('dragNode');
								dojo._destroyElement('dragNode');						
								this.dragCont._changeState("Container", "");
								this.dragCont=this.target;
								this.dragCont._changeState("Container", "Over");
								this.target.insertNodes(false, ['dragNode'],this.target.before, this.target.current);
							}else{
								that.source.delItem('dragNode');
								dojo._destroyElement('dragNode');
								
								this.dragCont._changeState("Container", "");
								this.dragCont=this.target;
								this.dragCont._changeState("Container", "Over");
								this.target.insertNodes(false, ['dragNode']);
							}
						}
						
						if (this.target.current && this.target.current.id!='dragNode'){that.theNodeCheck=this.target.current;}
						that.theNodeBefore=this.target.before;
					}
				}
				//*************************** Fin

				dojo.dnd.autoScroll(e);
				var s = a.node.style;
				/*if (this.ModoDrag && this.dragEspacioX && this.dragEspacioY){
				
					s.left = e.pageX - this.dragEspacioX + "px";
					s.top  = e.pageY - this.dragEspacioY + "px";
					//console.debug('e: '+e.pageX+', dragEspacio: '+this.dragEspacioX+', s.left: '+s.left);
					//console.debug('e: '+e.pageY+', dragEspacio: '+this.dragEspacioY+', s.top: '+s.top);
				}else{*/
					s.left = (e.pageX + this.OFFSET_X) + "px";
					s.top  = (e.pageY + this.OFFSET_Y) + "px";
				//}
				var copy = Boolean(this.source.copyState(dojo.dnd.getCopyKeyState(e)));
				if(this.copy != copy){ 
					this._setCopyStatus(copy);
				}
				
			}
		}
	});
