var dateslist = null;
var updateSlider = true;

Piv2Viewer = function(info) {
		// chain the constructors
		Piv2Viewer.superclass.constructor.call(this, info);
};
YAHOO.lang.extend(Piv2Viewer, PivViewer);

Piv2Viewer.prototype.init = function(info){
	  Piv2Viewer.superclass.init.call(this, info);
		_pivViewer.btnNavInventaires = _pivViewer.createButton("btn-piv-fonds-span", "push", "btn-piv-fonds");
		cotesInit();
};

Piv2Viewer.prototype.resetMnuPrint = function(image){
	  Piv2Viewer.superclass.resetMnuPrint.call(this, image);
		var m = _pivViewer.mnuPrint;
		// On le vide pour le reconstruire
		m.clearContent();
		// Un lien vers l'impression de l'image complète
		var item = new YAHOO.widget.MenuItem("dummy", {text: pivGetMessage("mnu_print_complete_text"), url: image.baseUrl + "/" + image.getNameWithoutQueryString() + ".pdf", target: "_blank"});
		m.addItem(item);
		// Un lien vers l'impression de l'image telle qu'affichée (le lien sera complété dans une autre méthode)
		item = new YAHOO.widget.MenuItem("dummy", {text: pivGetMessage("mnu_print_asviewed_text"), url: image.baseUrl + "/" + image.getNameWithoutQueryString() + ".pdf?w=200", target: "_blank"});
		m.addItem(item);
		// On reconstruit le menu visuellement
		m.render("btn-print");
		// On met à jour le second item pour l'image telle qu'affichée
		_pivViewer.updateMnuPrintAsViewed();
}

reinitLists = function() { };
reinitLists.prototype = {
	    reinitLists: function(pos) {
				//console.log('DEPUIS reinitLists...');
				if( $("piv-nav-opt-thema-slct") ){
					//console.log('Mise à jour de la liste thema, position=' + pos);
					var mValue=null;
					var myhash = new Hash();
					$A( $("piv-nav-opt-thema-slct") ).each(function(n){
						myhash.set(parseInt(n.value),n);
					});
					var mykeys = myhash.keys().sort(function(a,b){return a - b;});
					mykeys.each( function(v){ 
						if(v>pos){
							throw $break;
						}
						mValue = v;
						if(v==pos){
							throw $break;
						}
					});
					//console.log($$('#piv-nav-opt-thema-slct option[value='+mValue+']'));
					var mOpts = $$('#piv-nav-opt-thema-slct option[value='+mValue+']');
					//console.log(mOpts);
					if(mOpts.length > 0){
						var position = (mOpts.length > 1) ? mOpts.length - 1 : 0;
						var mPos = mOpts[position].index;
						var mVal = mOpts[position].value;
						$("piv-nav-opt-thema-slct").selectedIndex = mPos;
						updateListsAndTitle(mVal);
					}
					
					if( $("piv-nav-opt-chrono-slct") ){
						//console.log('Mise à jour de la liste chrono, position=' + pos);
						var c = -1;
						$A( $("piv-nav-opt-chrono-slct") ).each(function(n){
							c++;
							//console.log('Traitement de l\'option ' + n.text + ' de valeur ' + n.value + '(iteration ' + precedent + ')');
							if(n.value > pos){
									$("piv-nav-opt-chrono-slct").selectedIndex = (c-1);
									throw $break;
							} else if(n.value == pos){
									//console.log('La valeur de pos ('+pos+') est égale à la valeur en cours ('+n.value+'). L\'option sélectionnée est ' + (c));
									$("piv-nav-opt-chrono-slct").selectedIndex = (c);
									if(n.label!=null && n.label!=''){
										throw $break;
									}
							}
						});
					}
					
				} else if( $("piv-nav-opt-chrono-slct") ){
					//console.log('Mise à jour de la liste chrono, position=' + pos);
					/*var c = -1;
					$A( $("piv-nav-opt-chrono-slct") ).each(function(n){
						c++;
						//console.log('Traitement de l\'option ' + n.text + ' de valeur ' + n.value + '(iteration ' + precedent + ')');
						if(n.value > pos){
								$("piv-nav-opt-chrono-slct").selectedIndex = (c-1);
								throw $break;
						} else if(n.value == pos){
								//console.log('La valeur de pos ('+pos+') est égale à la valeur en cours ('+n.value+'). L\'option sélectionnée est ' + (c));
								$("piv-nav-opt-chrono-slct").selectedIndex = (c);
							  if(n.label!=null && n.label!=''){
									throw $break;
								}
						}
					});*/
					
					var mValue=null;
					var myhash = new Hash();
					$A( $("piv-nav-opt-chrono-slct") ).each(function(n){
						myhash.set(parseInt(n.value),n);
					});
					var mykeys = myhash.keys().sort(function(a,b){return a - b;});
					mykeys.each( function(v){ 
						if(v>pos){
							throw $break;
						}
						mValue = v;
						if(v==pos){
							throw $break;
						}
					});
					//console.log('mValue: ' + mValue);
					var mOpts = $$('#piv-nav-opt-chrono-slct option[value='+mValue+']');
					//console.log(mOpts);
					if(mOpts.length > 0){
						var position = (mOpts.length > 1) ? mOpts.length - 1 : 0;
						var mPos = mOpts[position].index;
						//var mVal = mOpts[position].value;
						$("piv-nav-opt-chrono-slct").selectedIndex = mPos;
						//updateListsAndTitle(mVal);
					}

					
				}
				//console.log('FIN DE reinitLists...');
	    }
	}	;

YAHOO.lang.augment(PivViewer, reinitLists);

Piv2Viewer.prototype.sliderEnd = function(info){
	  Piv2Viewer.superclass.sliderEnd.call(this, info);
		if ( 	updateSlider ){
			var source = _pivViewer.slider.xslider.valueChangeSource;
			n = ( ( source == 1 ) ?  _pivViewer.slider.getImageNo() : _pivSeries.getCurrentImage() );
			_pivViewer.reinitLists(n);
		}else{
				updateSlider = true;
		}
};

/** TODO: Malo doit voir avec eux ce qu'on supprime exactement comme infos */
Piv2Viewer.prototype.updateStatus = function(info){
	  //Piv2Viewer.superclass.updateStatus.call(this, info);
		//pivSetStatus("Zoom : " + Math.floor(100 * _pivViewer.currentZoom) + "%");
		pivSetStatus(" ");

};

Piv2Viewer.prototype.adjustMoveButtons = function(info){
	  Piv2Viewer.superclass.adjustMoveButtons.call(this, info);
		if ( this.currentImageNo == _pivSeries.getSize() ) {
			if(this.btnMvChronoPrevious) this.btnMvChronoPrevious.set("disabled", false);
			if(this.btnMvChronoNext) this.btnMvChronoNext.set("disabled", true);
			if(this.btnMvThemaPrevious) this.btnMvThemaPrevious.set("disabled", false);
			if(this.btnMvThemaNext) this.btnMvThemaNext.set("disabled", true);
		} else if (this.currentImageNo == 1) {
			if(this.btnMvChronoPrevious) this.btnMvChronoPrevious.set("disabled", true);
			if(this.btnMvChronoNext) this.btnMvChronoNext.set("disabled", false);
			if(this.btnMvThemaPrevious) this.btnMvThemaPrevious.set("disabled", true);
			if(this.btnMvThemaNext) this.btnMvThemaNext.set("disabled", false);
		} else {
			if(this.btnMvChronoPrevious) this.btnMvChronoPrevious.set("disabled", false);
			if(this.btnMvChronoNext) this.btnMvChronoNext.set("disabled", false);
			if(this.btnMvThemaPrevious) this.btnMvThemaPrevious.set("disabled", false);
			if(this.btnMvThemaNext) this.btnMvThemaNext.set("disabled", false);
		}
}

function cotesInit() {
	new Ajax.Request( _pivViewer.baselink + "functions/navigation-cotes.json", {
		method: "GET",
		parameters: {value: _pivViewer.url},
		onSuccess: function(result){
			$('piv-nav-cotes').update(result.responseText);
			var naviCotes = YAHOO.util.Dom.get('btn-mv-cote-previous-span');
			if( naviCotes ){
					initCotesButtons();
			}
		}
		//TODO: erreur?
	});

	//piv-body-hmenu-nav-opt
	new Ajax.Request( _pivViewer.baselink + "functions/get-nav-index/" + _pivViewer.url + "/index.json", {
		method: "GET",
		onSuccess: function(result){
			$('piv-body-hmenu-nav-opt').update(result.responseText);
			var naviTheme = YAHOO.util.Dom.get('piv-nav-opt-thema-slct');
			if( naviTheme ){
					initThemeButtons();
			}
			var chronoTheme = YAHOO.util.Dom.get('piv-nav-opt-chrono-slct');
			if( chronoTheme ){
					initChronoButtons();
			}
		}
		//TODO: erreur?
	});
}

// DEBUT: Boutons de navigation supplementaire
/* Navigation par cotes */
function initCotesButtons(){
		_pivViewer.btnMvCotePrevious = _pivViewer.createButton("btn-mv-cote-previous-span", "push", "btn-nav-opt-cote-prev");
		_pivViewer.btnMvCoteNext = _pivViewer.createButton("btn-mv-cote-next-span", "push", "btn-nav-opt-cote-next");
}

function initChronoButtons(){
	_pivViewer.btnMvChronoPrevious = _pivViewer.createButton("btn-nav-opt-chrono-prev-span", "push", "btn-nav-opt-chrono-prev");
	_pivViewer.btnMvChronoNext = _pivViewer.createButton("btn-nav-opt-chrono-next-span", "push", "btn-nav-opt-chrono-next");
}

/* Navigation thematique */
function initThemeButtons(){
	_pivViewer.btnMvThemaPrevious = _pivViewer.createButton("btn-nav-opt-thema-prev-span", "push", "btn-nav-opt-thema-prev");
	_pivViewer.btnMvThemaNext = _pivViewer.createButton("btn-nav-opt-thema-next-span", "push", "btn-nav-opt-thema-next");

	YAHOO.util.Event.addListener("btn-nav-opt-thema-prev", "click", function() {
		updateSlider = false;
		// le numero de l'image courante this.currentImageNo
		var n,s,l,c;
		s = $("piv-nav-opt-thema-slct");
		if(s==null);
		else{
			c = s.selectedIndex;
			if(c==0);
			else{
				if((c - 1)>=1){
					v = (c - 1);
					s.selectedIndex = v;
					v = $F("piv-nav-opt-thema-slct");
					_pivViewer.gotoImage(v);
					updateListsAndTitle(v);
				}
			}
		}
	});
	YAHOO.util.Event.addListener("piv-nav-opt-thema-slct", "change", function() {
		updateSlider = false;
		var v = $F("piv-nav-opt-thema-slct");
		if(v!=null) if(v!="") if(v!='001'){
			_pivViewer.gotoImage(v);
			updateListsAndTitle(v);
		}
	});
	YAHOO.util.Event.addListener("btn-nav-opt-thema-next", "click", function() {
		updateSlider = false;
		// le numero de l'image courante this.currentImageNo
		var n,s,l,c;
		s = $("piv-nav-opt-thema-slct");
		if(s==null);
		else{
			c = s.selectedIndex;
			l = s.options.length;
			if(c==(l-1));
			else{
				if((c + 1)<l){
					v = (c + 1);
					s.selectedIndex = v;
					v = $F("piv-nav-opt-thema-slct");
					_pivViewer.gotoImage(v);
					updateListsAndTitle(v);
				}
			}
		}
	});
}

function updateListsAndTitle(current){
	//console.log('DEPUIS updateListsAndTitle...');
	var select = $("piv-nav-opt-thema-slct");
	if( select != undefined && select != null){
		var option = (select.selectedIndex >= 0)?select[select.selectedIndex]:select[0];
		var optgroup = option.up('optgroup');

		// On affiche le nom du theme en cours
		$('thema-name-span').replace('<span id="thema-name-span">' + ((optgroup != undefined)?optgroup.label + '&#160;: ':'') + '</span>');

		// On vide le select pour la navigation chronologique
		$A( $("piv-nav-opt-chrono-slct") ).each(function(l){
			l.remove();
		});

		// ajout d'une pemiere entree dans la liste des chronos ; elle est vide mais pointe sur l'image selectionne par la navigation thematique
		if(option!=null && option.value!=null){
			$("piv-nav-opt-chrono-slct").insert(new Option('          ',option.value,false,false));
		}

		var entries = $A( dateslist.objet );
		// On boucle sur les objets obtenus et on construit pour chacun un noeud dans l'arbre
		if( optgroup != undefined ){
			entries.each(function(n) {
					if(n.nom == optgroup.label){
							var entry = $A( n.sous_objet );
							entry.each(function(m) {
									if(m.nom == option.text){
										$A( m.dates ).each(function(k){
												var el = new Element('option', { 'value': k.pos }).update( k.date );
												$("piv-nav-opt-chrono-slct").insert(el);
										});
									}
							});
					}
			});
		} else {
			entries.each(function(n) {
					if(n.nom == option.text){
							var entry = $A( n.sous_objet );
							entry.each(function(m) {
										$A( m.dates ).each(function(k){
												var el = new Element('option', { 'value': k.pos }).update( k.date );
												$("piv-nav-opt-chrono-slct").insert(el);
										});
							});
					}
			});
		}
			if( $("piv-nav-opt-chrono-slct") ){
				//console.log('Mise à jour de la liste chrono, position=' + current);
				var mValue=null;
				var myhash = new Hash();
				$A( $("piv-nav-opt-chrono-slct") ).each(function(n){
					myhash.set(parseInt(n.value),n);
				});
				var mykeys = myhash.keys().sort(function(a,b){return a - b;});
				mykeys.each( function(v){ 
					if(v>current){throw $break;}
					mValue = v;
					if(v==current){throw $break;}
				});
				//console.log(mykeys);
				//var toto = $$('#piv-nav-opt-chrono-slct');
				//console.log(toto);
				//console.log($$('#piv-nav-opt-chrono-slct option[value='+mValue+']'));
				var mOpts = $$('#piv-nav-opt-chrono-slct option[value='+mValue+']');
				//console.log('mValue: ' + mValue);
				//console.log(mOpts);
				if(mOpts.length > 0){
					var mPos = (mOpts.length > 1) ? mOpts[(mOpts.length - 1)].index : mOpts[0].index;
					$("piv-nav-opt-chrono-slct").selectedIndex = mPos;
				}
			}
			
		if ( option.value != '001' && _pivViewer.currentImageNo != 1 ) {
			_pivViewer.btnMvChronoPrevious.set("disabled", false);
			_pivViewer.btnMvChronoNext.set("disabled", true);
			_pivViewer.btnMvThemaPrevious.set("disabled", false);
			_pivViewer.btnMvThemaNext.set("disabled", true);
		} else {
			_pivViewer.btnMvChronoPrevious.set("disabled", true);
			_pivViewer.btnMvChronoNext.set("disabled", false);
			_pivViewer.btnMvThemaPrevious.set("disabled", true);
			_pivViewer.btnMvThemaNext.set("disabled", false);
		}
	}
	//console.log('FIN DE updateListsAndTitle...');
}

/* Navigation chronologique */
YAHOO.util.Event.addListener("btn-nav-opt-chrono-prev", "click", function() {
	updateSlider = false;
	// le numero de l'image courante this.currentImageNo
	var n,s,l,c;
	s = $("piv-nav-opt-chrono-slct");
	if(s==null);
	else{
		c = s.selectedIndex;
		if(c==0);
		else{
			if((c - 1)>=1){
				v = (c - 1);
				s.selectedIndex = v;
				v = $F("piv-nav-opt-chrono-slct");
				_pivViewer.gotoImage(v);
			}
		}
	}
});
YAHOO.util.Event.addListener("piv-nav-opt-chrono-slct", "change", function() {
	updateSlider = false;
	var v = $F("piv-nav-opt-chrono-slct");
	if(v!=null) if(v!=""){
		_pivViewer.gotoImage(v);
	}
});
YAHOO.util.Event.addListener("btn-nav-opt-chrono-next", "click", function() {
	updateSlider = false;
	// le numero de l'image courante this.currentImageNo
	var n,s,l,c;
	s = $("piv-nav-opt-chrono-slct");
	if(s==null);
	else{
		c = s.selectedIndex;
		l = s.options.length;
		if(c==(l-1));
		else{
			if((c + 1)<l){
				v = (c + 1);
				s.selectedIndex = v;
				v = $F("piv-nav-opt-chrono-slct");
				_pivViewer.gotoImage(v);
			}
		}
	}
});
// FIN: Boutons de navigation supplementaire


