var maxPause       = 5;
var numberOfSpeeds = 20;
var initSpeed      = 16;
var speed          = initSpeed;
var imageCourrante = 0 ;
var increment      = 0 ;
var imageNum       = 0 ;
var imageTot       = 1 ;
var backandfont    = "no";
var TotImage       = TotalImage;
var theImages      = new Array();
var click_play     = 0;
var loadedImg		 = 0;
var numImgLoaded   = 0;
var imageTotText;
var pause;

function Config_File (type) {
  var  info ;
  info  = "/model_forecast/imageview/viewImage.conf";
  return info ;
}

function Lunch_Info (lang) {
  var verbose ;
  //var verbose = document.animation.src ;
  var verbose = document.getElementById('mainImage').src ;

  vloc = '/cgi-bin/viewerimg.cgi?Info=' + verbose + '&conf=' + Config_File ("conf") + '&Type=aucun' + '&lang=' + lang;

   cgiWindow=open(vloc,"info","resizable=no,scrollbars=yes,menubar=no,height=470,width=550,left=10,top=10");

   if (cgiWindow.opener == null)
    cgiWindow.opener=self;
}

function set_theImages(deselectRadio) {
    //
    // set_theImages: fill the array "theImages" with
    //                a list of images based on the start and
    //                end times in the SELECT widgets

    // set increment to 0 to stop the animation loop
	 loadedImg = 1;
    increment = 0;

    imageTot     = TotImage;
    imageTotText = padTextPrefix('' + imageTot,'0',3);
    setPause();

    // set the theImages array to the list of images
    for (imageCourrante=0; imageCourrante<imageTot; imageCourrante++) {
        theImages[imageCourrante] = new Image();
        theImages[imageCourrante].src = TabImagesComplete[imageCourrante];
		  theImages[imageCourrante].onload = imageCounter;
    }

  // set the display to the first image in the list

    imageNum = 0;
    nextFrame(0);
}
function imageCounter(e) {
	/*
	var targ = 0;
	if (!e) var e = window.event;
	if (e.target) targ = e.target;
	else if (e.srcElement) targ = e.srcElement;
	if (targ.nodeType == 3) // defeat Safari bug
		targ = targ.parentNode
	*/
	numImgLoaded++;
	//alert("src : " + this.src);
	//alert("Num Img Loaded : " + numImgLoaded + " : " + theImages.length);
	//(numImgLoaded == imageTot)?animate(): false;
}

function setPause () {
    //
    // setPause: set the end of loop pause based on
    //           the number of frames in the animation
    //
        pause = maxPause;
    /*if (imageTot > maxPause) {
        pause = maxPause;
    } else {
        pause = imageTot-1;
    }*/
}

function animate() {
   var Nav   = navigator.appName;
   var isIe4 = (navigator.appName.indexOf("Microsoft") !=-1);
  //
  // animate: start animation loop
  //
  if (backandfont == "yes") {
	 if (imageNum == imageTot )
		change_direction(-1);
	 if (imageNum < 0)
	   change_direction(1);
  }
  if (increment != 0) {
    nextFrame(increment);
	 if (Nav != "Netscape"  &&  !isIe4 && Nav != "Konqueror")
      animeTimer = setTimeout("animate ()",delay);
  }
}

function nextFrame(inc) {
    var Nav      = navigator.appName;
    //
    // nextFrame: display the next image in the array theImages
    //
    imageNum += inc;
		
	 //if (imageTot == null) imageTot = 0;
	 if (typeof pause == 'undefined') setPause();
	 
	 if (typeof pause != 'undefined') {
    	if (Nav == "Konqueror") {
      	// go back to the first image
     		if(imageNum >= imageTot)
         imageNum = 0;
         // go to the last image
         if(imageNum < 0)
         	imageNum = imageTot - 1;
    	} else {
      	// go back to the first image
      	if(imageNum >= imageTot+pause)
         	imageNum = 0;
			// go to the last image
         if(imageNum < 0-pause)
         	imageNum = imageTot - 1;
    	}

    	if(imageNum >= imageTot) {
      	// display the last image
      	imageCourrante=imageTot - 1;
    	} else if(imageNum <0) {
      	// display the first image
      	imageCourrante = 0;
    	} else 
      	imageCourrante=imageNum;
	 
	 	if (theImages[imageCourrante]!=null)
    		document.getElementById('mainImage').src = theImages[imageCourrante].src;
    		//document.animation.src = theImages[imageCourrante].src;
    
	 	if(imageNum < imageTot) 
      	updateFrameText();
	}
}

function slower() {
    //
    // slower: increase the delay between images
    //
    if (speed > 1 && click_play > 0) {
        speed-=1;
        setDelay();
    }
}
function faster() {
    //
    // faster: decrease the delay between images
    //
    if (speed < numberOfSpeeds && click_play > 0) {
        speed+=1;
        setDelay();
    }

}

function lastImage() {
   //
   // lastImage: display the last image in the array
   //
		
	if (click_play > 0) {    
		stopPlay();
   	imageNum = imageTot-1;
   	nextFrame(0);
	}
}
function firstImage() {
    //
    // firstImage: display the first image in the array
    //
   if (click_play > 0) { 
		stopPlay();
    	imageNum = 0;
    	nextFrame(0);
	}
}

function stepBackward() {
    //
    // backward: display the previous image
    //
   if (click_play > 0) { 
		stopPlay();
    	if (imageNum > 0)
      	nextFrame(-1);
    	else if(imageNum == 0) {
      	imageNum = imageTot;
      	nextFrame(-1);
    	}
	}	
}

function stepForward() {
    //
    // forward: display the next image
    //
   if (click_play > 0) { 
		stopPlay();
    	if (imageNum == imageTot -1 ) {
      	imageNum = 0;
      	nextFrame(0);
    	} else if (imageNum < imageTot -1 )
      	nextFrame(1);
	}
}

function setDelay() {
    //
    // setDelay: set delay based on speed
    //

    delay = (numberOfSpeeds - speed) * 100;

    if (delay == 0) delay = 50;
}
function speedReset() {
    //
    // speedReset: reset the frame delay to its initial value
    //
   if (click_play > 0) { 
		speed = initSpeed;
    	setDelay();
	}
}

function stopPlay() {
    //
    // stopPlay: turn off the animation loop
    //
    clearTimeout (animeTimer);
    increment = 0;
}

function updateFrameText() {
    //
    // updateFrameText: update the text widget with the current frame status
    //
    var imageCourranteText= imageCourrante + 1;

    // add leading zero(s)
    imageCourranteText = padTextPrefix('' + imageCourranteText,'0',3);
	if (typeof imageTotText != 'undefined')
    document.myform.FrameText.value = imageCourranteText + "/" + imageTotText;
}

function startup() {
    //
    // startup: update the speed and frame text widgets
    //
	 document.getElementById('mainImage').onload = imgLoaded; 
	 
    //set_theImages(0);
	 updateFrameText();
	 var a = 0;
	 var b = 0;
	 if (imageCourrante+1 >= 10){
		a = "0" + (imageCourrante+1);
	 } else {
		a = "00" + (imageCourrante+1);
	 }
	 if (TotImage >= 10){
		b = "0" + TotImage;
	 } else {
		b = "00" + TotImage;
	 }
	 document.myform.FrameText.value = a + "/" + b;
    setDelay();
	 preloadimages('/images/animation_buttons/slowdown_over.gif','/images/animation_buttons/speedup_over.gif', '/images/animation_buttons/speedreset_en_over.gif','/images/animation_buttons/speedreset_fr_over.gif','/images/animation_buttons/loop_bkwd_over.gif','/images/animation_buttons/loop_fwd_bkwd_over.gif','/images/animation_buttons/loop_fwd_over.gif','/images/animation_buttons/pause_over.gif', '/images/animation_buttons/first_over.gif','/images/animation_buttons/prev_over.gif', '/images/animation_buttons/next_over.gif', '/images/animation_buttons/last_over.gif');

}
function imgLoaded(e){
	document.getElementById('mainTable').style.visibility = "visible";

	animeTimer=setTimeout('animate()', delay);

	var targ;
	if (!e) e = window.event;
	if (e.target) targ = e.target;
	else if (e.srcElement) targ = e.srcElement;
	if (targ.nodeType == 3) // Defeat Safari bug
		targ = targ.parentNode;
	
	targ.onload = function () {animeTimer=setTimeout('animate()', delay)};

}
function setMouseOver(img,number) {
  if (click_play == 1) { 
	 img.src='/images/animation_buttons/' + img.name + '_over.gif';
	 popup (number);
 } else
	 img.src='/images/animation_buttons/' + img.name + '_greyed.gif';
}
function setMouseOut(img) {
   if (click_play == 1) {
     img.src='/images/animation_buttons/' + img.name + '.gif';
	  kill();
   } else
     img.src='/images/animation_buttons/' + img.name + '_greyed.gif';
}
function drawButton(name, alt, clickFunction,over_img) {
	   // NS 4 doesn't support image button
   var browser = navigator.appName;
   var version = parseInt(navigator.appVersion);
	if ((browser=='Netscape') &&  (version == 4)) {
		if(name == 'loop_fwd' || name == 'loop_bkwd' || name == 'loop_fwd_bkwd') {
			document.writeln('<td nowrap align=center><a href="javascript:'+ clickFunction+ '"><img name="' + name + '" src="/images/animation_buttons/' + name + '.gif" alt="' + alt + '" ');
			document.writeln('onMouseOver=document.myform.' + name + '.src="/images/animation_buttons/' + name + '_over.gif";' + + over_img + ';return true;');
			document.writeln('onMouseOut=document.myform.' + name + '.src="/images/animation_buttons/' + name + '.gif";kill();return true;');
		} else {
			document.writeln('<td nowrap align=center><a href="javascript:'+ clickFunction+ '"><img name="' + name + '" src="/images/animation_buttons/' + name + '_greyed.gif" alt="'+ alt + '" ');
	   }
		document.writeln('onClick="' + clickFunction + '" border="0"></a></td>');
	} else {
		 if(name == 'loop_fwd' || name == 'loop_bkwd' || name == 'loop_fwd_bkwd') {
			document.writeln('<td nowrap align=center><img name="' + name + '" src="/images/animation_buttons/' + name + '.gif" alt="' + alt + '" ');
			document.writeln('onMouseOver=document.myform.' + name + '.src="/images/animation_buttons/' + name + '_over.gif";' + over_img + ';return true;' );
			document.writeln('onMouseOut=document.myform.' + name + '.src="/images/animation_buttons/' + name + '.gif";kill();return true;');
		 } else {
         document.writeln('<td nowrap align=center><img name="' + name + '" src="/images/animation_buttons/' + name + '_greyed.gif" alt="' + alt + '"');
			document.writeln('onMouseOver="javascript:setMouseOver(this,'+over_img+');"');
			document.writeln('onMouseOut="javascript:setMouseOut(this);"');
	 	 }
		 document.writeln('onClick="' + clickFunction + '"></td>');
   }
}
function drawControlButtons() {

	// Modified March 8 2010 to include French alt text for control buttons.
	if (lang == 'en') {
		drawButton('loop_bkwd', 'Play Backward', 'startPlay(\'bkwd\',\'animate\',-1)','popup(0)');
		drawButton('loop_fwd_bkwd', 'Play Forward-Backward', 'startPlay(\'fwd_bkwd\',\'back\',1)','popup(2)');
		drawButton('loop_fwd', 'Play Forward', 'startPlay(\'fwd\',\'animate\',1)','popup(3)');
		drawButton('pause', 'Pause', 'stopPlay()','10');
		drawButton('first', 'First image', 'firstImage()','4');
		drawButton('prev', 'Previous image', 'stepBackward()','5');
		drawButton('next', 'Next image', 'stepForward()','6');
		drawButton('last', 'Last image', 'lastImage()','7');
		drawButton('slowdown', 'Slower', 'slower()','8');
		drawButton('speedup', 'Faster', 'faster()','9');
		drawButton('speedreset_en', 'Reset', 'speedReset()','11');
	}
	else {
		drawButton('loop_bkwd', 'Jouer arrière', 'startPlay(\'bkwd\',\'animate\',-1)','popup(0)');
		drawButton('loop_fwd_bkwd', 'Jouer arrière-avant', 'startPlay(\'fwd_bkwd\',\'back\',1)','popup(2)');
		drawButton('loop_fwd', 'Jouer avant', 'startPlay(\'fwd\',\'animate\',1)','popup(3)');
		drawButton('pause', 'Pause', 'stopPlay()','10');
		drawButton('first', 'Première image', 'firstImage()','4');
		drawButton('prev', 'Image précédente', 'stepBackward()','5');
		drawButton('next', 'Image suivante', 'stepForward()','6');
		drawButton('last', 'Dernière image', 'lastImage()','7');
		drawButton('slowdown', 'Plus lent', 'slower()','8');
		drawButton('speedup', 'Plus vit', 'faster()','9');
   	drawButton('speedreset_fr', 'Vitesse initiale', 'speedReset()','11');
	}

   document.writeln('<td><input class="textframe" type="text" name="FrameText" size=8 readonly="readonly"></td>');
}

function startPlay(animation, type, direction) {
	 if (loadedImg < TotImage){
		 set_theImages(0);
	 }
	 //var newDiv = document.createElement('div');
	 //var divName = 'waitMessage';
	 //newDiv.setAttribute('id',divName);
	 //newDiv.innerHTML = "Loading image sequence... Please wait!";
	 //var mainImage = document.getElementById('mainImage');
	 //mainImage.parentNode.insertBefore(newDiv,mainImage);
	 //console.debug("addding div!!!");
	 var myInterval = setInterval(
			 function(){
			 	if(numImgLoaded >= (imageTot - 1)){
					clearInterval(myInterval);
					startPlay1(animation,type,direction);
//					mainImage.parentNode.removeChild(newDiv);
				}// else {
				//	infoChange();
				//}
			 }
			 ,500);
}
function infoChange(){
	var infoMessage = document.getElementById('waitMessage');

	
	if(infoMessage.innerHTML == "Loading image sequence    Please wait!"){
		infoMessage.innerHTML = "Loading image sequence.   Please wait!";
	} else if(infoMessage.innerHTML == "Loading image sequence.   Please wait!"){
		infoMessage.innerHTML = "Loading image sequence..  Please wait!";
	} else if(infoMessage.innerHTML == "Loading image sequence..  Please wait!"){
		infoMessage.innerHTML = "Loading image sequence... Please wait!";
	} else {
		infoMessage.innerHTML = "Loading image sequence    Please wait!";
	}
}
function startPlay1(animation,type,direction) {
    //
    // startPlay: change the direction of the animation
    //
	 if(click_play == 0) {
		document.myform.pause.src=icon_dir+'/pause.gif';
		document.myform.first.src=icon_dir+'/first.gif';
		document.myform.last.src=icon_dir+'/last.gif';
		document.myform.prev.src=icon_dir+'/prev.gif';
		document.myform.next.src=icon_dir+'/next.gif';
		document.myform.slowdown.src=icon_dir+'/slowdown.gif';
		document.myform.speedup.src=icon_dir+'/speedup.gif';
		if (lang == 'en') {
		  document.myform.speedreset_en.src=icon_dir+'/speedreset_en.gif';
		} else {
		  document.myform.speedreset_fr.src=icon_dir+'/speedreset_fr.gif';
		}
   }
	if (lang == 'en') {
     if (animation == "bkwd")
       document.direction.animbutton.value = "Backward animation";
     else if (animation == "fwd_bkwd")
	    document.direction.animbutton.value = "Backward and Forward animation";
     else if (animation == "fwd")
	   document.direction.animbutton.value = "Forward animation";
     document.direction.direcbutton.value = "Direction:" + animation;
   }else {
     if (animation == "bkwd"){
	    document.direction.animbutton.value = "Animation inverse";
       document.direction.direcbutton.value = "Direction: inv";
     }else if (animation == "fwd_bkwd") {
	    document.direction.animbutton.value = "Animation avant et inverse";
       document.direction.direcbutton.value = "Direction: avt-inv";
     }else if (animation == "fwd"){
	    document.direction.animbutton.value = "Animation vers l'avant";
       document.direction.direcbutton.value = "Direction: avt";
     }
   }
   click_play = 1;

   stopPlay();
   change_direction(direction);
   if (TotImage >= 2) {
     if (type == "animate")
		 backandfont = "no";
     else 
		 backandfont = "yes";
     animate     ();
   }
}
function over_effect(e,state,bgcolor){
  if (document.all)
    source4=event.srcElement
  else if (document.getElementById)
    source4=e.target
  if (source4.className=="menulines" || source4.className=="menuanim" || source4.className=="menulines1") {
    source4.style.borderStyle=state
   source4.style.backgroundColor=bgcolor
 } else{
    while(source4.tagName!="TABLE"){
       source4=document.getElementById? source4.parentNode : source4.parentElement
       if (source4.className=="menulines" || source4.className=="menuanim" || source4.className=="menulines1") {
         source4.style.borderStyle=state
         source4.style.backgroundColor=bgcolor
       }
    }
  }
}
function change_direction(value) {
    //
    // change_direction: change the direction of the animation
    //
    increment = value;
}

function padTextPrefix (InString, PadChar, DefLength)  {
        if (InString.length>=DefLength)
                return (InString);
        var OutString=InString
        for (var Count=InString.length; Count<DefLength; Count++)  {
                OutString=PadChar+OutString;
        }
        return (OutString);
}

function new_Image (arg) {
    rslt = new Image();
    rslt.src = arg;
    return rslt;
}
function switchImage(whichImage,imageNumber){
	   document.images[whichImage].src = PreLoadedImages[imageNumber].src
}
function change_Img(nomImg,newimg){
  document[nomImg].src   = newimg ;
}
function preloadimages(){
	for (var i = 0; i < arguments.length; i++){
		PreLoadedImages[i] = new Image();
		PreLoadedImages[i].src = arguments[i];
	}
	 /*
	 for (i=0;i<preloadimages.arguments.length;i++){
		PreLoadedImages[i]=new Image();
		PreLoadedImages[i].src=preloadimages.arguments[i];
	}
	*/
}

function PreloadImages () {
   var speed = new Array(),i;

	for (i = 0 ; i < TabImagesComplete.length ; i++) 
	   speed[i] = new_Image(TabImagesComplete[i]);

}

