/*
	+-------------------------------------------------------------------------------------------------------+
   	 | 		Copyright 2006-2007 Kahiloa Solutions et Communication											|
   	 | 		Nikon Europe Project / Nikon Widgets Slideshow Javascript 											|
   	 |		Version 1.0  																					|
   	 | 		Last Update 29.03.2007																			|
   	+-------------------------------------------------------------------------------------------------------+ 
*/

var Slideshow = {
	
	initialize: function(idGallery, idViewer, nwdFile) {	
				 		
		this.idGallery = idGallery;
		this.idViewer = idViewer;
		// xml file of data 
		this.nwdFile = nwdFile;	
  		this.options = Object.extend({
  			opacity: 0.8,
  			padding: 10,
   			transition: 0.3,
   			delay: 3.0,
			keyboard: false,
			loop: false,
			draggable: false,
			autoPlay: false,
			bgcolor: '#ffffff'
 		 }, arguments[3] || {});
		
	this._activeButtons();
	
	  	this.gallery = $(this.idGallery.toLowerCase());		
	  	this.viewer = $('viewer');
	  	this.viewerToolbar = $('viewerToolbar');
	  	this.viewerContent = $('viewerContent');
	  	this.viewerVisual = $('viewerVisual');
	  	this.viewerImage = $('viewerImage');
		this.viewerCopyright = $('viewerCopyright');
		
		this.currentWidth = 618;	  		  
		this.imagesList = new Array();
		this.imagesNb = 0;
		this.imagesCount = 0;
		this.isPlaying = true;
		this.imagePath = '/resources/styles/15_gallery_summary_block_gallery_page/images/nw/';
		this.currentImage = 0;
		this.pays = null;
		this.overlay;
		this.flashMap;
		this.dataExist = false;
		
		// actions
		
		window.slideshow = this; 						// reference to slideshow
		this.viewer.hide(); 							// hide the viewer
		this._activeNav(false);							// desactive navigation
		this._getImages();								// get all images
		this.tabSelected = 0;							
		this.changeTab(1);								
		this.delay(this.options.delay);
		if(this.options.autoPlay) { this.play(); }		
	},	
	
	/*
	 * Open the viewer with the image who have the id passed.
	 * @param {String} id
	 */
	open: function(id) {			
		try{  	
			this._showImage(id);
			this._initMap();					
			this.overlay = new Overlay('viewerOverlay','viewer', { 
				alpha: this.options.opacity, 
				duration: 0,
				bgcolor: this.options.bgcolor 
				});		
				
			this.overlay.open(50,100);	
			this._activeNav(true);					
		}
		catch(e) { window.status = e; }		
		return false;
	},
	
	/*
	 * Start and Stop the slide show
	 */
	playpause: function() {
		if(this.isPlaying == false) { 
			this.play(); 
			//this._activeNav(false);
		}
		else { 
			this.pause();
			this._activeNav(true); 
		}
		return false;
	 },	
	
	/*
	 * Show next image
	 */ 
	previous: function() {
		this._showImage("-");
		return false;
	},
		
	/*
	 * Show previous image
	 */	
	next: function() {
		this._showImage("+");
		return false;
	},
	
	/*
	 * Apply a delay to the slideshow (3, 5, 7)
	 */
	delay: function(second) {		
		var className = "nw_viewer_seconds";
		this.options.delay = parseInt(second*1000);
		$("btn_delay_3").className = className;
		$("btn_delay_5").className = className;
		$("btn_delay_7").className = className;
		$("btn_delay_"+second).className = className+'_selected';		
		return false;
	},	
	
	/*
	 * Close the viewer
	 */
	close: function() {
		this.pause();
		this.overlay.close();
		return false;
	},		
    
	/*
	 * Change current tab
	 */
    changeTab: function(tabIndex) {		
		switch(tabIndex) {			
			case 2:
				if(this.tabSelected != 2) {
					this.tabSelected = 2;								
					$("viewerTab.box."+2).show();
					$("viewerTab."+1).removeClassName("selected");
					$("viewerTab."+2).addClassName("selected");		
					this.currentWidth = this.currentWidth + 320 + this.options.padding;
					this.overlay.resize();
				}											
			break;
			default: 
				if(this.tabSelected != 1) {
					this.tabSelected = 1;
					$("viewerTab.box."+2).hide();								
					$("viewerTab."+1).addClassName("selected");
					$("viewerTab."+2).removeClassName("selected");	
					this.currentWidth = this.currentWidth - 320 - this.options.padding;
				}							
			break;			
		}	
		this.viewer.style.width = this.currentWidth+"px";	
		return false;	                 
    },
	
	/*
	 * Start the slideshow 
	 */
	play: function() {	
		this.isPlaying = true; 
		$('btn_playpause').firstChild.src= this.imagePath+'btn_pause.gif';
		this._showImage("+");
		this.timoutId = self.setTimeout("this.slideshow.play();", this.options.delay);
	},
	
	/*
	 * Stop the slideshow
	 */
	pause: function() {
		this.isPlaying = false; 
		$('btn_playpause').firstChild.src= this.imagePath+'btn_play.gif';
		clearTimeout(this.timoutId);
	},
	
	/*
	 * Get the current pays (called by flash map)
	 */
	getPays: function() {
	 	return String(this.pays);
	 },
	
	/*
	 * Preload all image of gallery
	 */
	_getImages: function() {
		var thumbnails, i, a, rel, preloadImage;	
		try {			
			this.viewerImage.src = this.imagePath+"ajax-loader.gif";						
			if (!document.getElementsByTagName){ return; }						
			if(this.gallery) { 
				thumbnails = this.gallery.getElementsByTagName('a'); 
			}
			else { 
				thumbnails = document.getElementsByTagName('a'); 
			}		
			this.imagesNb = thumbnails.length;	
			for (i=0; i<thumbnails.length; i++) {
				a = thumbnails[i];
				// THD - race condition during preloading + XML loading
				a.onclick = 'return false;';		
				rel = String(a.getAttribute('rel'));	
				rel = rel.split(":");							
				if (a.getAttribute('href') && (rel[0].toLowerCase()==this.idGallery.toLowerCase())) {		
					preloadImage = new Image();										
					preloadImage.id = rel[1];										
					preloadImage.onload = this._onImageLoaded.bind(this, i, a, preloadImage);															
					preloadImage.onerror = this._onImageFailure.bind(this,i, a, preloadImage);	
					preloadImage.src = a.getAttribute('href');
				// THD - race condition during preloading + XML loading
					a.href = '';					      																										
				}
			}									
		}		
		catch(e) { this._setError('Error[_getImages]: '+e.message); }
	},	
	
	/*
	 * Handler of loaded image. When all images are loaded, get the data.
	 */
	_onImageLoaded: function(i, a, preloadImage) {		
		this.imagesList[i] = preloadImage;		
		a.onclick = this.open.bind(this, i);
		this.imagesCount++;		
		if(this.imagesCount == this.imagesNb) { 
			this._getData();
			this._activeNav(true); 
		}		
	},	
	
	_onImageFailure: function(a, i, preloadImage) {
		this.imagesCount++;
		//alert("Image "+i + " can't be loaded...");
	},
	
	/*
	 * Get the data for all images in nwdFile (Nikon Widget Data File)
	 */
	_getData: function() {	
		new Ajax.Request(this.nwdFile,{ 
			onSuccess:this._onDataSuccess.bind(this), 
			onFailure:this._onDataFailure.bind(this)
			});
	},	
	/*
	 * When data has been receive, parse them with NwdParser
	 * @param {Object} xhr
	 */
	_onDataSuccess: function(xhr) {
		this.dataExist = true;
		var nwd, x, theItem;
        try{            
			this.openActive = true;
			nwd = xhr.responseXML.documentElement;			
			this.parser = new NwdParser(nwd, { fallback: false });							
			// for each images
			for(x=0; x < this.imagesList.length; x++){
				theItem = this.parser.getItem(x);	
				// data of photo section						
				this.imagesList[x].photo = this.parser.getElementsOfSectionByName("photo",theItem);		
				//alert(this.imagesList[x].photo);		 
				// data of map section
				this.imagesList[x].map = this.parser.getElementsOfSectionByName("map",theItem);											
			}		
		}
		catch(e){ this._setError('Error[_loadData]: '+e.message); }						
	},	
	
	/*
	 * if data can not be loaded, we don't activate tab navigation 
	 */
	_onDataFailure: function(xhr){
		this._setError('Error[_canotLoadData] : ' + xhr.status + ' -- ' + xhr.statusText);
		this.dataExist = false;
		this._activeNav(true);
		this._activeButton('viewerTab.2', 'changeTab', false, '2');		
	},
	
	/*
	 * Construct the flash map
	 */
	_initMap: function() {
		if(this.dataExist) {
			try{			
				if(Flash.have()) {							
					//this.flashMap = new FlashTag('../images/css/nw/viewerFlashMap.swf', 318, 160, {id:'viewerFlashMap', version: '8,0,0,0'});
					this.flashMap = new FlashTag(flashMapLocation, 318, 160, {id:'viewerFlashMap', version: '8,0,0,0'});
					$("viewerMap").innerHTML = this.flashMap.get();
				}		
			}
			catch(e){ 
				this._setError('Error[_initMap]: '+e.message);
				$('viewerMap').hide();
			}
		}
	},
	
	/*
	 * In fact this method should be named _updateUI ! It update the html interface with data.
	 * @param {int} imageIndex
	 */
	 _updateData: function(imageIndex) {
	 	if(this.dataExist) {
		 	try{				
				if(this.imagesList[imageIndex].photo) {
					if(this.imagesList[imageIndex].photo["copyright"]) {
						this.viewerCopyright.innerHTML = this.imagesList[imageIndex].photo["copyright"].value;
					}					        				
				}else {					
					this.viewerCopyright.innerHTML = '';
				}     
				if(this.imagesList[imageIndex].map) {
					this._updateMapTab(imageIndex);
				} 									
				else {
					//this._activeButton('viewerTab.2', 'changeTab', false, '2');	
				}
			}
			catch(e){this._setError('Error[updateData]: '+e.message);}			
		}
	 },
     
	 /*
	  * Update the data in map tab interface
	 * @param {int} imageIndex
	  */
     _updateMapTab: function(imageIndex) {
        var img, strMap; 
		if(!imageIndex) { imageIndex = this.currentImage; }
        img = this.imagesList[imageIndex];
		strMap = '';		         				            
		if(img.map["pays"]){
			this.pays = img.map["pays"].value;
			$('viewerMap').show();
		}
		else {
			this.pays = null;
			$('viewerMap').hide();
		}							
		if(img.map["country"] || img.map["title"]) {	
			strMap += '<div class="nw_viewer_map_tit">';
			if(img.map["country"]){ strMap += '<h4>'+img.map["country"].value+'</h4>'; }	
			if(img.map["title"]){ strMap +=  '<h3>'+img.map["title"].value+'</h3>'; }
			strMap += '</div>';
		}
		if(img.map["description"]){
			strMap += '<div class="nw_viewer_map_text">'+img.map["description"].value+'</div>';
		}					
		$("viewerMapInfos").innerHTML = strMap;	
		this._activeButton('viewerTab.2', 'changeTab', true, '2');		
     },
	
	/*
	 * Display the image with index passed and resize the viewer consequencly
	 * @param {int} imageIndex
	 */
	_showImage: function(imageIndex) {		
        var type, imageNum;
		try{		
			type = typeof imageIndex;
			if(type == "string") {
				if(imageIndex=="-") { imageIndex = parseInt(this.currentImage-1); }
				else { imageIndex = parseInt(this.currentImage+1); }
			}		
			if(imageIndex < 0) {
				if(this.options.loop && this.isPlaying) { imageIndex = this.imagesList.length-1;}
				else { if(this.isPlaying) { this.pause(); } return false; } 
			}
			else if(imageIndex >= this.imagesList.length) {
				if(this.options.loop && this.isPlaying) { imageIndex = 0; }
				else { if(this.isPlaying) { this.pause();} return false; }
			}					
			var imageNum = imageIndex + 1;							
			this.currentImage = imageIndex;
			Element.update('viewerCount', imageNum+'/'+this.imagesList.length);																	
						
			this.viewerImage.style.height = this.imagesList[this.currentImage].height;
			this.currentWidth = this.imagesList[this.currentImage].width + (this.options.padding*2) + 20;
			
			if(this.tabSelected==2){ this.currentWidth = this.currentWidth + 320 + this.options.padding }						
			this.viewer.style.width = this.currentWidth + "px";			
			this.viewerImage.src = this.imagesList[this.currentImage].src;
														
			if(this.options.transition > 0) { this.viewerImage.hide(); Effect.Appear(this.viewerImage, { duration: this.options.transition });}
			else { this.viewerImage.show();	}					
			if(this.dataExist) { this._updateData(imageIndex); }			
		}
		catch(e) { this._setError('Error[showImage]: '+e.message); }
	},
	
	/*
	 * Active or desactive the nav.
	 * @param {boolean} bool
	 */ 
	_activeNav: function(bool) {	
		if(bool==false) { document.onkeydown = ''; }
		else { 
			this._activeButtons();
			if(this.options.keyboard == true) {
				document.onkeydown = this._setKeyboard.bind(this);
			} 			
		}		
	},
	
	/*
	 * Active all button off interface
	 */
	 _activeButtons: function() {
	 	this._activeButton('btn_playpause', 'playpause', true);
		this._activeButton('btn_previous', 'previous', true);
		this._activeButton('btn_next', 'next', true);
		this._activeButton('btn_close', 'close', true);		
		this._activeButton('btn_delay_3', 'delay', true, '3');
		this._activeButton('btn_delay_5', 'delay', true, '5');
		this._activeButton('btn_delay_7', 'delay', true, '7');		
		this._activeButton('viewerTab.1', 'changeTab', true, '1');
		this._activeButton('viewerTab.2', 'changeTab', true, '2');
	},
	
	/*
	 * Active a button of interface
	 * 
	 */
	_activeButton: function(idButton, callback, active) {
		if(active==false) {
   	 		$(idButton).onclick = '';
			if($(idButton).hasClassName('selected')) { $(idButton).removeClassName('selected'); }
			$(idButton).addClassName('disabled');   	 			
   	 	}
   	 	else {   	 										
			if(arguments[3]) {var params = arguments[3]}
			else {params = '';}
			$(idButton).onclick = eval("this."+callback+".bind(this,"+arguments[3]+");");
			$(idButton).removeClassName('disabled');
		}
	},
	
	/*
	 * Active Keybord shortcut (space, left, right, escape and X)
	 */
	_setKeyboard: function(e) {		
		if (e == null) {	 keycode = event.keyCode; }
		else { keycode = e.which; }		
		switch(keycode) {
			case(80): this.playpause(); break;
			case(Event.KEY_LEFT): this.previous(); break;		
			case(Event.KEY_RIGHT): this.next(); break;	
			case(Event.KEY_ESC): this.close(); break;
			case(88): this.close(); break;
		}
	},
	
	/*
	 * Debug Message
	 */
	_setError: function(Message){
		if(Browser.ff) {
			//console.log('Slideshow Error: %d', Message);
		}
		else{
			this.errors += Message+'\n';
			window.status = this.errors;
		}
	}
}
