/**
 * Slideshow class that communicates with a flashslideshow
 */


var flashSlideshow = Class.create({

	appname: 	'slideshow',
	id: 		null, 
	init: 		false,   
	images: 	null,   
	ids: 		null,
	details:   	null,
	blank: 		null,  
	count: 		null,
	key: 		null,   
	offset: 	null, 
	content:    null,
	image:    	null,  
	loaded: 	null,     
	remotePosition: null,
	bottomHeight: null,
	
	initialize: function(id)
	{
		this.id 		= id;
		this.init 		= true;         
		this.imageKeys		= [];
		this.ids		= [];
		this.details	= [];
	    this.blank		= '&nbsp;';           
		this.loaded		= false;  
		this.offset		= 0;
		this.contentKey  	= 0;
		this.imageKey		= 0;             
		
		this.remotePosition	= 'bottom';       
		this.bottomHeight = ( $$('.box-bottomleft')[0] && $('projectdetails') ) ? $$('.box-bottomleft')[0].getDimensions().height : 0;
		                            
        this.keyboardAction = this.keyboardAction.bindAsEventListener(this);
        this.seek 			= this.seek.bindAsEventListener(this);     
            
	                           
		this.resizeContainer();    
		this.checkOverlapping();
		this.resetCounter();
		this.fetchImages();  
		this.getAddressStatus();     
		this.createFlash();        
		this.resizeContainer();   
		this.setAddressListener();  
		this.showContent(); 
		this.enableKeyboardNav();                          
	},  
	
	// swfobject
	createFlash: function()
	{                            
		var flashvars = {                           
		   offset: this.offset
		};

		var params = {
		  	allowScript: "true",    
			allowScriptAccess: "sameDomain",
			allowFullScreen: "true",          
			menu: "false", 
			bgcolor: "000000",
			wmode: "transparent"  
		};
		swfobject.embedSWF("fileadmin/templates/files/slideshow.swf?offset="+this.offset, this.id, "100%", "100%", "9.0.3", "files/expressInstall.swf", flashvars, params);
	},    
	
	showContent: function()
	{        
		// update project description
		if($('projectdetails')) {    
			var index = parseInt(this.contentKey,10);                
			var projectId = this.ids[index]; 
			
			if($('project_'+projectId)) {    
				$('projectdetails').update($('project_'+projectId).innerHTML);
				if($$('.box-bottomleft .buttons').length > 0) { 
					var buttonsHtml = $$('#projectdetails .buttons')[0].innerHTML;
					$$('#projectdetails .buttons')[0].remove();
					$$('.box-bottomleft .buttons')[0].innerHTML = buttonsHtml;
				}

				$$('.box-bottomleft .buttons a.youtube').each(function(item) {
					item.observe('click', function(e) {    
						Event.stop(e);
						var youtubeKey = e.target.href.substr(31);                                              
						_youtube.showPlayer(youtubeKey);
					}.bind(this));
				});
			}
		}  
	},

	updateStatus: function(key) 
	{                     
		this.key = key;   
		
		var cnt = 0;  
		var part1 = 0;
		var part2 = 0;
		for(var i=0; i<slideshowImages.length; i++) {
			for(var j=0; j<slideshowImages[i].length; j++) { 
				cnt++;
				if(cnt == this.key) {
					part1 = i;   
					part2 = j;
					this.contentKey = i; 
					this.showContent();   
				}
			}
		} 
		this.setAddressStatus("/"+(part1)+"/"+(part2));

		// update counter
		key = ""+key;
		if(key.length==1) {
			key = "0"+key; 
		}   
		cnt = ""+this.count;
		if(cnt.length==1) {
			cnt = "0"+cnt; 
		}     
			                         
			
		if($('switch-count')) {
			$('switch-count').update(key+'/'+cnt);
		} 	
	},
		    
	updateCnt: function(cnt, key) 
	{
		this.count = cnt;
		this.key = key;                              


		// update counter
		cnt = ""+cnt;
		if(cnt.length==1) {
			cnt = "0"+cnt; 
		}
		key = ""+key;
		if(key.length==1) {
			key = "0"+key; 
		}        
			                         
			
		if($('switch-count')) {
			$('switch-count').update(key+'/'+cnt);
		} 
		
		if(this.imageKeys.length == cnt) {
			this.loaded = true;
		}   	
	},
	
	// remote methods
	previous: function() 
	{                                                   
		$(this.id).previous();
	},
	
	next: function() 
	{                       
		$(this.id).next();
	},
	
	seek: function(index) 
	{
		if(!index) {
			index = 0;
		}
		$(this.id).seek(index);
	},  
	
	resetCounter: function()
	{     
		if($('switch-count')) {
			$('switch-count').update('00/00');
		}
	},
	
	fetchImages: function()
	{                    
		var previousClassname;       
                	      
		if(typeof slideshowImages == 'object') {         
			$(this.id).select('img').each(function(a) {   
				a.setStyle({display:'none'});          
			});
			
			for(var i=0; i<slideshowImages.length; i++) {
				for(var j=0; j<slideshowImages[i].length; j++) {
					this.imageKeys.push(slideshowImages[i][j]);
				}
			}
			 
			// get contents                    
			$$('.descriptions').each(function(a) {    
				this.ids.push(a.id.substr(8));
			}.bind(this));
		}else {
			$(this.id).select('img').each(function(a) {  
				this.imageKeys.push(a.src);
				if(previousClassname != a.className) {
					this.details.push(a.className);    
					previousClassname = a.className; 
				}	
			    this.ids.push(a.className);   
				a.setStyle({display:'none'});

				// empty src to prevent the browser loading the images twice
				// @todo add flash check here
				a.src = 'fileadmin/templates/images/blank.gif';
			}.bind(this));
		}

		// hide buttons if there is only one background
		if(this.imageKeys.length <= 1) {
			$$('.img-switch').each(function(a) {    
				a.setStyle({display:'none'}); 
			});
		}
                                                       
	},
	
	getImages: function()
	{        
		this.bindObservers();
		                    
		return this.imageKeys;
	},      
	
	// listeners     
	
	bindObservers: function()
	{
		// previous / next button 
		                               
		
		if($('switch-prev') && $('switch-next')) {         
			$('switch-prev').observe('click', function(e) {
				this.previous();
				Event.stop(e);
			}.bind(this));
			$('switch-next').observe('click', function(e) {
				this.next();
				Event.stop(e);
			}.bind(this));
		}
		
		// only on the all projects of a client page
		$$('#footer .project').each(function(element, index) {
			element.observe('click', function(e) {
				
				this.setAddressStatus(index+'/0');
				Event.stop(e);
			}.bind(this));
		}.bind(this));

		/*
		$$('a.youtube').each(function(item) {
			item.observe('click', function(e) {    
				Event.stop(e);
				var youtubeKey = e.target.href.substr(31);                                              
				_youtube.showPlayer(youtubeKey);
			}.bind(this));
		});
		*/
                        
		// resize container  
		Event.observe(window, 'resize', function(e) {      
			this.resizeContainer();   
			this.checkOverlapping();   
		}.bind(this));       

	},        
	
	// handler
	      
	resizeContainer: function()
	{                         
		var footerHeight = 0;//($('footer')) ? $('footer').getDimensions().height : 0;          
		//var footerHeight = 0;
		var headerHeight = ($('head')) ? $('head').getDimensions().height : 0;
		var viewPortHeight =  document.viewport.getHeight();      
		var height = viewPortHeight - headerHeight - footerHeight;   
		                      
		var contentHeight = 0;
		var boxes = $$('.boxes');
		for (var i=0; i < boxes.length; i++) {
			contentHeight = contentHeight + parseInt(boxes[i].getDimensions().height);
			//this.debug(contentHeight);
		};
		var boxestop = $$('.box-topleft');
		for (var k=0; k < boxestop.length; k++) {
			contentHeight = contentHeight + parseInt(boxestop[k].getDimensions().height);
			//this.debug(contentHeight);
		};
		var boxesbottom = $$('.box-bottomleft');
		for (var l=0; l < boxesbottom.length; l++) {
			contentHeight = contentHeight + parseInt(boxesbottom[l].getDimensions().height);
			//this.debug(contentHeight);
		};
		var paypal = $$('.paypal');
		for (var m=0; m < paypal.length; m++) {
			contentHeight = contentHeight + parseInt(paypal[m].getDimensions().height) + 50;
		};                                       

		/*
		this.debug('...');
		this.debug('height:');
		this.debug(height);
		this.debug('contentHeight:');
		this.debug(contentHeight);
		this.debug('...');
		*/

		if (Prototype.Browser.IE) {
			contentHeight += 120;
		}

		if(boxesbottom.length > 0) {
			footerHeight = 120;
		}
		if( contentHeight + 60 > height ) {   
			$(document.body).addClassName('page-news');
			$(document.body).setStyle({ overflow: 'scroll' });
			$('slideshowcontainer').style.height = (contentHeight + 60 + footerHeight + 20) + 'px';  	
			//this.debug($('slideshowcontainer').style.height);
		}else {                    
			$(document.body).removeClassName('page-news');
			$(document.body).setStyle({ overflow: 'hidden'});
			window.scrollTo( 0, 0 );             
			$('slideshowcontainer').style.height = height+ 'px'; 
		}
		
		/*
		if( $$('.boxes')[0] ) { 
			var contentHeight = ( $$('.boxes')[0] ) ? $$('.boxes')[0].getDimensions().height : 0;  
			if( contentHeight + 60 > height || $$('.flash')[0] ) {  
				$(document.body).addClassName('page-news');
				$(document.body).setStyle({ overflow: 'scroll' });
				$('slideshowcontainer').style.height = (contentHeight + 60) + 'px';  	
				this.debug($('slideshowcontainer').style.height);     
			}else {                    
				$(document.body).removeClassName('page-news');
				$(document.body).setStyle({ overflow: 'hidden'});
				window.scrollTo( 0, 0 );             
				$('slideshowcontainer').style.height = height+ 'px'; 
			}                        
			
		} 
		*/

		// temporary fix for ligaproduction
		/*
		if( $('slideshowcontainer').getDimensions().height === 0) {
			$('slideshowcontainer').style.height = height+ 'px';
			$(document.body).addClassName('page-news');
			$(document.body).setStyle({ overflow: 'scroll' });
		}
		*/
		//$('slideshowcontainer').style.height = '400px';
	},
	
	checkOverlapping: function()
	{                    
		if( $$('.box-bottomleft')[0] && $('projectdetails') ) { 
			
			var footerHeight = 0;//($('footer')) ? $('footer').getDimensions().height : 0;          
			var headerHeight = ($('head')) ? $('head').getDimensions().height : 0;
			var viewPortHeight =  document.viewport.getHeight();      
		                                                                                                
			var detailHeight = ($('projectdetails')) ? $('projectdetails').getDimensions().height : 0; 
			
			var paypal = $$('form.paypal');
			for (var m=0; m < paypal.length; m++) {
				detailHeight += 60;
			};

			var height = viewPortHeight - headerHeight - footerHeight;       
                                               
			if( ( detailHeight + 90 + this.bottomHeight ) > height  ) {              
				if( this.remotePosition	== 'bottom' ) { 
					$$('.box-bottomleft')[0].setStyle( { top:(detailHeight+90)+'px', bottom:'' } ); 
					$('content').setStyle( { height: (detailHeight + 180 + this.bottomHeight - footerHeight )+'px' } );
					this.remotePosition	= 'top';                       
					$(document.body).addClassName('page-news');       
                	$(document.body).setStyle({ overflow: 'scroll'}); 
                	if( $('footer') ) {
						$('footer').setStyle( { height:$('footer').getDimensions().height+'px', 'position':'fixed' } );
					}
				}
			} else {                        
				if( this.remotePosition	== 'top' ) {
					$$('.box-bottomleft')[0].setStyle( { bottom:'180px', top:'' } );           
					$('content').setStyle( { height: '100%' } );
					// $('content').setStyle( { height: (detailHeight + 180 + this.bottomHeight - footerHeight ) + 'px' } );
					this.remotePosition	= 'bottom';       
					$(document.body).removeClassName('page-news');
                	$(document.body).setStyle({ overflow: 'hidden'});   
                	if( $('footer') ) {      
                		$('footer').setStyle( { height:'', 'position':'absolute' } );  
					} 
					window.scrollTo( 0, 0 );
				}                          
			}
		}
		
	},  
	
	
	// swf address methods
	
	setAddressListener: function()
	{     
		if( typeof SWFAddress != 'undefined' ) {
			SWFAddress.addEventListener(SWFAddressEvent.CHANGE, this.updateAddressStatus.bind(this)); 
		}  
	},
	
	getAddressStatus: function()
	{       
		if( typeof SWFAddress != 'undefined' ) {
			var path = SWFAddress.getValue();         
			if(path != "/") { 
				var parts = path.split('/');    
				this.contentKey	= parts[1] !== undefined ? parts[1] : 0;
				this.imageKey	= parts[2] !== undefined ? parts[2] : 0;       
				
				var cnt = 0;          
				for(var i=0; i<=this.contentKey; i++) {
					for(var j=0; j<slideshowImages[i].length; j++) {   
						if(i==this.contentKey && j==this.imageKey) {
							this.offset = cnt;                      
						}
						cnt++;
					}
				}                                     
				  
			} else {            
				this.contentKey = 0;
				return;
			}               
		}     
	},
	
	setAddressStatus: function(path)
	{      
		if( typeof SWFAddress != 'undefined' && SWFAddress.getValue() != path) {     
			SWFAddress.setValue(path);              
		}   
	}, 
	
	updateAddressStatus: function()
	{        
		if( typeof SWFAddress != 'undefined') { 
			var path = SWFAddress.getValue();
			if(path != "/") { 
				var parts 		= path.split('/');    
			
				var content	= parts[1] !== undefined ? parts[1] : 0;
				var image	= parts[2] !== undefined ? parts[2] : 0; 
		    
				if(content != this.contentKey || image != this.imageKey) {
					this.contentKey 	= content;
					this.imageKey 		= image;                    
				
					this.showContent();        
				
					var cnt = 0;          
					for(var i=0; i<=this.contentKey; i++) {
						for(var j=0; j<slideshowImages[i].length; j++) {   
							if(i==this.contentKey && j==this.imageKey) {
								this.seek(cnt);                         
							}
							cnt++;
						}
					}
				}                      
			} else {
				return;
			}  
		}  
	},  
	
	//
    //  enableKeyboardNav()
    //
    enableKeyboardNav: function() 
	{      
		document.observe('keydown', this.keyboardAction);
    },

    //
    //  disableKeyboardNav()
    //
    disableKeyboardNav: function() 
	{                       
        document.stopObserving('keydown', this.keyboardAction);
    },

    //
    //  keyboardAction()
    //
    keyboardAction: function(event) {
        var keycode = event.keyCode;   
		
        var key = String.fromCharCode(keycode).toLowerCase();
                                                                         
        if ((key == 'p') || (keycode == 37)) { 
            this.previous();
        } else if ((key == 'n') || (keycode == 39)){
        	this.next();
        }
    },

  	// helpers

	debug: function(msg)
	{
		if(window.console) {
			window.console.log(this.appname+': '+msg);  
		}
	}, 

	getUniqueId: function()
	{
	     var dateObject = new Date();
	     var uniqueId = dateObject.getFullYear() + '' + dateObject.getMonth() + '' + dateObject.getDate() + '' + dateObject.getTime();

	     return uniqueId;
	}
	
});
