/**
* Animation widget
* Equip de Productes, Servei Meteorològic de catalunya.
* 
*/

				dojo.require("dijit.form.Slider");
				dojo.require("dijit.form.Button");
				dojo.require("dojo.parser"); // scan page for widgets
				dojo.require("dojo.data.ItemFileReadStore");
				dojo.require("dijit.ProgressBar");
				//Animation images:
				var animation_images = new Array();
				var animation_titles = new Array();
				var num_frames;
				var active_frame=0;
				var animation_speed=1;
				var interval_var;
				var loader_interval;
				var reloader_interval;
				var animation_status=false;
				var imageItemStore;

				var reload_checkbox;
				var reload_img;

				var animation_text;
				var frameSlider;
				var speedSlider;
				var startStopButton;
				var header;
				var background;
				var img;
				var control_panel;
				var control_panel_container;
				var status_bar_node;
				var status_bar;
				
				var background_image;
				var background_div;
				var background_img;

				///Variables that MUST be initialitzed
				var json_file;
				var animation_div_id;
				var autostart;
				var reload;
				var reloading_time;
				/***************************************************************************/
				/*	This function inits all the html code and styles that show         */
				/*                          the animated images				   */
				/***************************************************************************/
				function init(){
				
				//Check if the variables have been initialized in the HTML, and initialize them if not.
				if(reload == null){reload=true;}
				if(reloading_time == null){reloading_time = 180;}
				if(autostart == null){autostart=true;}
				if(animation_div_id == null){animation_div_id="animation";}
				if(json_file == null){json_file="images.json";}
				//Create background
				//dojo.byId("animation").setAttribute("class","sidebox");
				dojo.toggleClass(dojo.byId("animation"),"sidebox",true);
				header = document.createElement('div');
				//header.setAttribute("class","boxhead");
				dojo.toggleClass(header,"boxhead",true);
				var h2 = document.createElement('h2');
				var text_header= document.createTextNode('Imatge de radar');
				h2.setAttribute("id","animation_img_title");
				h2.appendChild(text_header);
				header.appendChild(h2);
				dojo.byId("animation").appendChild(header);

				background = document.createElement('div');	
				//background.setAttribute("class","boxbody");
				dojo.toggleClass(background,"boxbody",true);
				//Append background to the animation div
				dojo.byId("animation").appendChild(background);
				
					

				//Creating background image if necessary
				if(background_image!=null){
				background_img = document.createElement('img');
				background_img.setAttribute("id","background_img");
				background_img.setAttribute("src",background_image+'?radn='+Math.random()); //Rand avoids IE6 and 7 mantaining the old background image size qhen it's changed!!
				dojo.toggleClass(background_img,"background_image",true);
				dojo.style(background_img,"visibility","hidden");
				background.appendChild(background_img);
				}

				//Creating image
				img = document.createElement('img');
				img.setAttribute("id","animation_img");
				img.setAttribute("src","./animation/images/loading.gif");
				dojo.toggleClass(img,"animation",true);		
				background.appendChild(img);
				
				//Creating the status bar
				status_bar_node = document.createElement('div');
				status_bar_node.setAttribute("id","status_bar_node");
				
				background.appendChild(status_bar_node);
				status_bar = new dijit.ProgressBar({
				annotate:"true",
				//style:"width:70%; left:15%",
				style:"width:200px; left:25px; top:40px",
				maximum:"1",
				progress:"0"
				},status_bar_node);

				//This reads the JSON file and starts the function that loads the animation issues.
				//var request = imageItemStore.fetch({query: {src:"*"}, onComplete: fillImageArray});
				//Rand avoids IE6 and 7 to take the json from the cache.
				imageItemStore = new dojo.data.ItemFileReadStore({
						url:json_file+'?radn='+Math.random()
					});

				var request = imageItemStore.fetch({onComplete: loadAnimation});
				
				
				}//Ends the init function

				/*Loads the animation images and adds the controls to the layer*/
				function  loadAnimation(items, request){
				  num_frames = items.length;
				  create_control_panel(); //Moved here the 9-9-2008 from the above block to avoid num_frames being set.
				  status_bar.update({maximum:num_frames});
				  for (var i = 0; i < items.length; i++){
					
       				    var item = items[i];
		//		    console.log("Loading image: " + item['src'] + " with the title '" + item['title'] + "'");
		
				    animation_images[i] = new Image();
				    animation_images[i].src =  item['src'];
				    animation_titles[i] = item['title'];
				    					
			          }
				loader_interval = setInterval("image_loading_control()",700);
				
		
				active_frame=0;


				  
				}
				/***********************************************************************************/
				/* This function looks how many images had been loaded and updates the status bar. */
				/* When all the images are loaded, launches the control panel creation             */
				/***********************************************************************************/
				function image_loading_control(){
				  
				  var images_loaded=0;
				  for(var i=0;i<num_frames;i++){
				   if(animation_images[i].width>0){images_loaded++;}
				  }
				
				if((animation_images[0].width>0) && dojo.byId("animation_img").src != animation_images[0].src){
				dojo.byId("animation_img").src = animation_images[0].src;
				dojo.byId("animation_img").width = animation_images[0].width;
				dojo.byId("animation_img").height = animation_images[0].height;
				
				
				
				dojo.byId("animation_img_title").firstChild.nodeValue=animation_titles[0];
				var animation_width = 60 + animation_images[0].width;
				
				if(background_image==null){				
				var box_height = 120 + animation_images[0].height; 
				var animation_height = 10 + animation_images[0].height;				
				} else {
				dojo.style(dojo.byId("background_img"),"visibility","visible");
				var box_height = 120 + dojo.byId("background_img").height; 
				var animation_height = 10 + dojo.byId("background_img").height;	
				}
				dojo.style(control_panel_container,"top",animation_height + "px");
				
				dojo.query(".sidebox").style("width",animation_width +"px");
				dojo.query(".boxbody").style("height",box_height +"px");
				
				dojo.style(control_panel_container,"left","30px")

				var animation_width = animation_images[0].width;
				dojo.query(".sidebox2").style("width",animation_width +"px");
				var animation_width = animation_width - 100;
				status_bar.setAttribute("style","width:" + animation_width + "px; left:30px; top:"+animation_height+"px");
				console.log("Image width: " + animation_width);
				//console.log("First image set!");
				 status_bar.update({progress:images_loaded});
				  console.log("Images loaded: " + images_loaded + " of" + num_frames);
				}
				if(images_loaded==num_frames){
				  clearInterval(loader_interval);
					console.log("all images loaded!");
					dojo.fadeOut({ node:"status_bar_node"
					}).play(1400);
				  activate_control_panel(); //Activates the control panel
				  if(autostart==true){start_animation();} //Starts the animation if demanded
				  if(reload==true){reloader_interval = setInterval("search_JSON()",reloading_time * 1000);}//Starts reloading JSON.	
				}
				
				}

				//Creates the control panel
				function create_control_panel(){

				//The container and header...
				control_panel_container = document.createElement('div');

				
				
				//control_panel_container.setAttribute("class","sidebox2");
				dojo.toggleClass(control_panel_container,"sidebox2",true);
				control_panel_container.setAttribute("id","control_panel_container");
				
				background.appendChild(control_panel_container);
				dojo.fadeOut({ node:"control_panel_container"
				}).play();
				
				control_panel_header = document.createElement('div');
				//control_panel_header.setAttribute("class","boxhead2");
				dojo.toggleClass(control_panel_header,"boxhead2",true);
				
				var h2 = document.createElement('h2');
				
				control_panel_header.appendChild(h2);

				control_panel_container.appendChild(control_panel_header);
				//The place for the controls
				control_panel = document.createElement('div');
				//control_panel.setAttribute("class","boxbody2");
				dojo.toggleClass(control_panel,"boxbody2",true);
				
				

				control_panel_container.appendChild(control_panel);
				
				
				var table = document.createElement('table');
				table.setAttribute("width","100%");
				control_panel.appendChild(table);
				var tbody = document.createElement('tbody'); //Necessary for IE!!!!
				table.appendChild(tbody);
				var tr = document.createElement('tr');
				tbody.appendChild(tr);
				var td = document.createElement('td');
				tr.appendChild(td);
				var text = document.createTextNode('Imatge');
				td.appendChild(text);
				animation_text = document.createElement("td");
				tr.appendChild(animation_text);
				var text = document.createTextNode('Inicia');
				animation_text.appendChild(text);
				var td = document.createElement("td");
				tr.appendChild(td);
				var text = document.createTextNode('Velocitat');
				td.appendChild(text);
				/*Reload section*/
				if(reload == true){
				var td = document.createElement("td");
				tr.appendChild(td);
				var text = document.createTextNode('Recarrega');
				td.appendChild(text);				
				}//Ends reload section
				var tr = document.createElement('tr');
				tbody.appendChild(tr);

				var frameSliderNode = document.createElement('div');
				dojo.style(frameSliderNode,"width","70px");
				//control_panel.appendChild(frameSliderNode);
				var td = document.createElement("td");
				tr.appendChild(td);
				td.appendChild(frameSliderNode);
				var frameRulesNode = document.createElement('div');
				frameSliderNode.appendChild(frameRulesNode);
					// setup the rules

				var frameSliderRules = new dijit.form.HorizontalRule({
						count:num_frames,
						style:"height:8px; z-index:1;" 
					},frameRulesNode);
				
				frameSlider = new dijit.form.HorizontalSlider({ 
						value:0,
						onChange: function(){
                                                    console.log(arguments);
						},
						name:"programaticSlider",
						slideDuration:0,
						onChange:function(val){img.src = animation_images[val].src; active_frame = val; dojo.byId("animation_img_title").firstChild.nodeValue=animation_titles[val];},
						style:"width:100%",
						minimum:0,
						maximum:(num_frames-1),
						discreteValues:num_frames,
						intermediateChanges:"true",
						showButtons:"true"
					},frameSliderNode);	
				frameSliderRules.startup();
				frameSlider.startup();		
				
				//Create the start/stop button
				
				startStopButton = document.createElement('img');
				startStopButton.setAttribute("src","./animation/images/start.gif");
				
				startStopButton.onclick = function (event) {swap_start_stop();};
				//control_panel.appendChild(startStopButton);
				var td = document.createElement("td");
				td.setAttribute("width","40px");
				tr.appendChild(td);
				td.appendChild(startStopButton);
				//Create the speed slide
				
				var speedSliderNode = document.createElement('div');
				
				//control_panel.appendChild(speedSliderNode);
				var td = document.createElement("td");
				tr.appendChild(td);
				td.appendChild(speedSliderNode);

				var speedRulesNode = document.createElement('div');
				speedSliderNode.appendChild(speedRulesNode);
				var speedRuleLabelsNode = document.createElement('ol');
				speedSliderNode.appendChild(speedRuleLabelsNode);	
				
				
				var li1 = document.createElement('li');
				var li1txt = document.createTextNode('0.5');
				li1.appendChild(li1txt);
				speedRuleLabelsNode.appendChild(li1);

				var li2 = document.createElement('li');
				var li2txt = document.createTextNode('1.0');
				li2.appendChild(li2txt);
				speedRuleLabelsNode.appendChild(li2);

				var li3 = document.createElement('li');
				var li3txt = document.createTextNode('1.5');
				li3.appendChild(li3txt);
				speedRuleLabelsNode.appendChild(li3);

				var li4 = document.createElement('li');
				var li4txt = document.createTextNode('2.0');
				li4.appendChild(li4txt);
				speedRuleLabelsNode.appendChild(li4);

				var li5 = document.createElement('li');
				var li5txt = document.createTextNode('2.5');
				li5.appendChild(li5txt);
				speedRuleLabelsNode.appendChild(li5);

				var li6 = document.createElement('li');
				var li6txt = document.createTextNode('3.0');
				li6.appendChild(li6txt);
				speedRuleLabelsNode.appendChild(li6);

				var li7 = document.createElement('li');
				var li7txt = document.createTextNode('3.5');
				li7.appendChild(li7txt);
				speedRuleLabelsNode.appendChild(li7);

				var li8 = document.createElement('li');
				var li8txt = document.createTextNode('4.0');
				li8.appendChild(li8txt);
				speedRuleLabelsNode.appendChild(li8);

				var speedSliderRuleLabels = new dijit.form.HorizontalRuleLabels({
						style:"height:1.2em;font-size:75%;color:gray; z-index:1;",
						container:"bottomDecoration"
					},speedRuleLabelsNode);			
				/*var speedSliderRules = new dijit.form.HorizontalRule({
						count:8,
						style:"height:5px"
					},speedRulesNode);
				*/
	
				speedSlider = new dijit.form.HorizontalSlider({ 
						value:1,
						onChange: function(){
                                                    console.log(arguments);
						},
						name:"speedSlider",
						onChange:function(val){change_speed(dojo.number.format(arguments[0],{places:2}));},
						style:"width:100%; height: 20px",
						minimum:0.5,
						maximum:4,
						discreteValues:34,
						intermediateChanges:"true",
						showButtons:"true"
					},speedSliderNode);	
				//speedSliderRules.startup();
				speedSlider.startup();	
				
				/*Reload section*/
				if(reload == true){
				var td = document.createElement("td");
				tr.appendChild(td);
				reload_img = document.createElement('img');
				reload_img.setAttribute("src","./animation/images/reload.gif");
				reload_img.setAttribute("align","absmiddle");
				reload_img.onclick = function (event) {search_JSON();};
				td.appendChild(reload_img);
				
				reload_checkbox = document.createElement('input');
				reload_checkbox.setAttribute("type","checkbox");
				reload_checkbox.defaultChecked=true;
				reload_checkbox.onclick = function (event) {swap_reload();};
				td.appendChild(reload_checkbox);
				td.setAttribute("width","40px");
				}//End of the reloading section	
					
				}//Ends control panel creation

				
				/*Makes visible the control panel. Separete from the creation in order to preload it before 
				the images and give the sensation of an immediate creation.*/
				function activate_control_panel(){
				
					dojo.fadeIn({ node:"control_panel_container",delay:1500
				}).play();

				}


				/***********************************/
				/* Animation control functions     */
				/***********************************/
				function move_frame(delta){
				 active_frame = active_frame + delta;
				 if(active_frame < 0){
					active_frame = num_frames - 1 + active_frame;
				 }
				 if(active_frame >= num_frames){
					active_frame = active_frame - num_frames;
				 }

				// dojo.byId("animation_img").src = animation_images[active_frame].src;
				frameSlider.setValue(active_frame);	
				}


				function start_animation(){
				var speed = 1000/animation_speed;
				
				 animation_status=true;
				 startStopButton.src = "./animation/images/stop.gif";
				animation_text.firstChild.nodeValue="Atura";
				 interval_var = setInterval("move_frame(1)",speed);
				}
				

				function stop_animation(){
				
				 animation_status=false;
				 startStopButton.src = "./animation/images/start.gif";
				animation_text.firstChild.nodeValue="Inicia";
				 clearInterval(interval_var);
				}

				function swap_start_stop(){
				 if(animation_status==true){stop_animation();} 
				 else {start_animation();}
				
				}

				function change_speed(speed){
				 animation_speed = speed.replace(",",".");
				
				 if(animation_status==true){
					
				   stop_animation();				 
				   start_animation();
				   }
				}
				/*Searches for a new JSON file and if it has new images, launches it's reload.*/
				function search_JSON(){
				console.log("searching for new images...");
				//Rand avoids IE6 and 7 to take the json from the cache.
				imageItemStore = new dojo.data.ItemFileReadStore({
						url:json_file+'?radn='+Math.random()
					});
				var request = imageItemStore.fetch({onComplete: reloadAnimation});
				}
				
				function  reloadAnimation(items, request){
				  var change_flag = false;
				 
				 
				  for (var i = 0; i < items.length; i++){
					
       				    var item = items[i];
				  
				   //console.log("Loading image: " + item['src'] + " with the title '" + item['title'] + "'");
					if(animation_images[i].src.indexOf(item['src'].toString().replace(".", ""))==-1){
					
					 	change_flag = true;				
					}
				   // animation_images[i] = new Image();
				   // animation_images[i].src =  item['src'];
				   // animation_titles[i] = item['title'];
									    					
			          }
				//loader_interval = setInterval("image_loading_control()",700);
				
				////If the file changed, we stop the animation, and launch the loading sequence.
				if(change_flag==true){
				 if(animation_status == true){autostart = true;} else {autostart = false;}
				 stop_animation();
				 clearInterval(reloader_interval);
				
				 dojo.fadeIn({ node:"status_bar_node"
					}).play();
				num_frames = items.length; 				
				status_bar.update({maximum:num_frames});
					for (var i = 0; i < items.length; i++){
					
       				         var item = items[i];			
				 	 animation_images[i] = new Image();
					 animation_images[i].src =  item['src'];
					 animation_titles[i] = item['title'];
					}
				loader_interval = setInterval("image_loading_control()",700);
				
				active_frame=0;
				frameSlider.setValue(active_frame);
				}
				//active_frame=0;


				  
				}
				///Activates/Desactivates automatic reloading of the JSON file (and animations)
				function swap_reload(){

				console.log("Swap reload:" + reload_checkbox.checked);
				if(reload_checkbox.checked){
				  reload_img.setAttribute("src","./animation/images/reload.gif");
				  reloader_interval = setInterval("search_JSON()",reloading_time * 1000);	//Starts reloading JSON.
				  reload_img.onclick = function (event) {search_JSON();};
				} else {
				  reload_img.setAttribute("src","./animation/images/reload_off.gif");
				  clearInterval(reloader_interval);
				  reload_img.onclick = null;
				}

				}

				dojo.addOnLoad(init);
				
				

				
				
