
var ImageScrollCollection = Class.create(
{
		initialize: function() //speed, step, type, direction
		{
			this.collection   = new Array();
		},
		addImageScroll: function(elm, direction, autoscroll, animation, carrousel, centerthumb, items)
		{
			// elm must be a HTML Element, it is not allowed whitin the Navigator Object to use an id or something 
			var elm     = (Object.isElement(elm)) ? elm : $(elm);
				
			// does this key already exists in our collection, sorry we have to throw an exception...
			this.collection.each(function(item){
				  if (item.elm.id == elm.id ) { throw "Key already in use whitin the ImageScrollCollection::collection"; }
			});
			
			// key is available, so we just add a new Imagescroll object
			this.collection.push(new ImageScroll(elm, direction, autoscroll, animation, carrousel,centerthumb, items));	
		  
		},
		getImageScroll: function()
		{
			// elm must be a HTML Element, it is not allowed whitin the Navigator Object to use an id or something 
			var elm     = (Object.isElement(elm)) ? elm : $(elm);
				
			// does this key already exists in our collection, sorry we have to throw an exception...
			this.collection.each(function(item){
				  if (item.elm.id == elm.id ) { return item; }
			});
		},
		scroll: function(elm, direction)
		{
		var elm     = (Object.isElement(elm)) ? elm : $(elm);
            // find the Imagescroll object in the collection
            this.collection.each(function(item){
             
                  if (item.elm.id == elm.id ) { item.scroll(direction); }
            });
		
		}
});

var ImageScroll = Class.create
(
    {
        initialize: function(elm, direction, autoscroll, animation, carrousel,centerthumb, items)
        {
			
        	//	stoppen wanneer de containrdiv niet bestaat
			if(!$(elm))
			{
				return false;
			}
			
			
			
			this.btn_up 		= $('button_up');
			this.btn_down 		= $('button_down');			
			
            this.direction 		= direction;   //  richting axis //	LR, RL, TB, BT
            //this.stepX	    	= 0;           	//  breedte van de thumbs	
            //this.stepY	    	= 63;           //  hoogte van de te nemen stappen
            //this.speed	    	= 5;	        //  scroll-snelheid
            this.autoscroll  	= autoscroll;        //  plaatjes automatisch laten scrollen?
            this.elm 			= elm;  //	id van de container div
			this.animation		= animation;
			this.arrayKey		= 0;			// 	bijhouden welk plaatje er wordt verplaatst
			this.parentHeight	= $(this.elm.parentNode).getHeight();	//	hoogte van de wrapper 
			this.height			= $(this.elm).getHeight();				//	hoogte van de containerdiv
			this.parentWidth	= $(this.elm.parentNode).getWidth();	//	hoogte van de wrapper 
			this.width			= $(this.elm).getWidth();				//	hoogte van de containerdiv
			this.carrousel 		= carrousel;
			this.centerthumb	= centerthumb;	//	true, wanneer de thumbs richting het midden moeten als je er op klikt
			this.index			= 0;	//	bijhouden op welke scrollpositie de gallery staat
			this.isSliding		= false;	//	bijhouden of de slide nog actief is
            this.count			= 0;
           
			//	alle divs bekijken binnen de container
			images = this.elm.getElementsByTagName('img');
			
			this.imgWidth 	= $(images[0]).offsetWidth;
			this.imgHeight 	= $(images[0]).offsetHeight;
		
			//	aantal items dat zichtbaar is
			if(this.direction == 'lr' || this.direction == 'rl')	//	horizontaal
			{
				this.galleryItems 	= Math.round(this.parentWidth / this.imgWidth);
			}
			else	//	verticaal
			{
				this.galleryItems 	= Math.round(this.parentHeight / this.imgHeight);
			}
			
			// alle plaatjes uit de gallery (ook de onzichtbare)
			this.totalItems		= images.length;
			this.galleryItems	= items;
			
			//	aantal items dat onzichtbaar, maar wel aanwezig is
			this.extraItems		= this.totalItems - this.galleryItems;
			
            //  er zijn geen plaatjes buiten het zichtbare gebied
            if(this.extraItems < 1) 
            {
                // niet scrollen na een klik op de thumb
                this.centerthumb = false;
                this.carrousel = false;
            }
			//	alle thumbs bij langs
			for (i=0;i<images.length;i++)
			{
				//	in de gaten houden of er op de thumbs geklikt wordt.
				
				//var_dump(this);	// $(images[i]).offsetWidth
				this.addBehaviour($(images[i]));
				this.addOnClick($(images[i]))
			}
			
			if(this.autoscroll)
			{
				//	uit te voeren wanneer autoscroll aan staat
			}
			
			if(!this.carrousel)
			{
				this.btn_up.addClassName('disabled_up');
				if(this.totalItems - this.galleryItems <= 0)
				{
					this.btn_down.addClassName('disabled_down');
				}
			}
        },
		addBehaviour: function(image)
		{
			//	klikbaar maken van de div die rondom het plaatje zit + cursorveranderingen
			Event.observe(image, 'click', this.swap.bindAsEventListener(this));
			
			Event.observe(image, 'mouseover', function() {
				document.body.style.cursor = 'pointer';
			});	
			Event.observe(image, 'mouseout', function() {
				document.body.style.cursor = 'default';
			});			
		},
		addOnClick: function(image)
		{
			
			Event.observe(image, 'click', this.swap.bindAsEventListener(this));
		},
		swap: function(element, id, src)
		{
        
			//	als de slide nog bezig is, niet swappen
			if(this.isSliding == true)
			{
				return;
			
			}
			//	lezen wat het nieuwe plaatje wordt
			newImgSrc	= element.target.longDesc;
			if(!newImgSrc)
            {
                return;
            }
			//	kijken welk plaatje (binnen de container) de active class heeft
			activeImg 	= $(this.elm).getElementsByClassName('active');
			
			//	als de geklikte thumbnail niet de "active" is 
			if(activeImg[0].id != element.target.id || 1 == 1)
			{
				
				
				//	de huidige active class verwijderen
				$(activeImg[0].id).removeClassName('active');
				
				//	nieuw element de class toewijzen
				$(element.target.id).addClassName('active');
				//alert($(element.target.id).parentNode.previousSiblings().length + 1);
				
				//	als de thumb richting het midden moet
				if(this.centerthumb)
				{
					//var_dump($(element.target.id));
					if(($(element.target.id).parentNode.previousSiblings().length +1 ) != Math.round(this.galleryItems /2))
					{
						if( $(element.target.id).parentNode.previousSiblings().length < (this.galleryItems /2))
						{
							//	bij een horizontale 
							if(this.direction == 'lr' || this.direction == 'rl')
							{
								this.scroll('lr');
							}
							else
							{
								this.scroll('tb');
							}
						}						
						else
						{
							if(this.direction == 'lr' || this.direction == 'rl')
							{
								this.scroll('rl');
							}
							else
							{
								this.scroll('bt');
							}
						}
					}
				}
				//if($(element.target.id).parentNode.previousSiblings().length);
				//this.scroll('rl');
			}
		},
        scroll: function(direction)
        {
        	if(this.count >= this.galleryItems)
			{
				this.count 	= 0
				images 		= this.elm.select('img.small');
				
				images.each(function(image, x)
				{
					if( x >= this.galleryItems )
					{
						image.hide();
					}				
				});
			}
			else
			{
				//	wanneer geen carrousel actief is, mag er bij bepaalde momenten niet meer gescrolled worden
				if(!this.carrousel)
				{
					//	kijken of het de uiteindes zijn bereikt, voor alle directions
					if((this.index == 0 && direction == 'lr') || (((this.index + this.galleryItems) ==  this.totalItems) && direction == 'rl')||
					   (this.index == 0 && direction == 'tb') || (((this.index + this.galleryItems + 1) >  this.totalItems) && direction == 'bt'))
					{
						//	leave before scrolling
						return;
					}
				}
	            //  als er geen items zijn om naar te scrollen
	            if(this.extraItems < 1)
	            {   
	                return false;
	            }
				
				if(!this.isScrolling == true)
				{
					
					this.isScrolling = true;
					
					//	get all images from container
					images 		= this.elm.getElementsByTagName('img');
					this.elm.select('img.small').invoke("show")
					amount 		= images.length;					
					firstImg	= images[0];
					lastImg 	= images[amount-1];			
					
					switch(direction)
					{
						case 'lr':
							
							imgclone = lastImg
							this.imgclone = lastImg					
							if(this.animation)
							{
								if(firstImg.id != imgclone.id)
								{
									$(imgclone).hide();
									new Insertion.Before(firstImg.id, imgclone);	
									
									new Effect.SlideRightIn(imgclone.id,{duration: 0.2, queue: {position:'end', scope: 'lr',limit: 1},
											
										afterFinish: function()
										{
																				
											this.isSliding = false;
											
											this.count = this.count +1	
											this.scroll(direction)	
										}.bind(this),
										
										beforeStart: function()
										{
											this.isSliding = true;
										}.bind(this)
										
									});
								}							
							}
							else	//	geen animatie
							{		
								var_dump(firstImg.id);						
								new Insertion.Before(firstImg.id, imgclone);
															
								this.elm.removeChild(lastImg);							
							}
							//this.addOnClick(this.elm.firstDescendant());
	
							if(this.index == 0)
							{
								this.index = this.totalItems;
							}
							else
							{
								this.index = this.index - 1;	
							}
						break;
						case 'rl':
							
							imgclone = firstImg.cloneNode(true)
							imgclone.id = "clone"
							new Insertion.Before(firstImg, imgclone)
							new Insertion.After(lastImg, firstImg)						
							if(this.animation)
							{
								
								if(lastImg.id != imgclone.id)
								{
									Effect.SlideLeftOut(imgclone,
										{duration: 0.2,queue: {position:'end', scope: 'rl',limit: 1},
										afterFinish: function()
										{
											
											this.isSliding = false;
											$("clone").remove();
											this.count = this.count +1	
											this.scroll(direction)									
										}.bind(this),
										
										beforeStart: function()
										{
											
											
											this.isSliding = true;
											
										}.bind(this)
									});
								}
								//new Effect.Move(this.elm, { x: -this.stepX, y: -this.stepY });
								//this.elm.removeChild(firstImg);
								/*new Effect.Move(this.elm, {
									x: this.stepX, y: this.stepY,
									transition: Effect.Transitions.full
								});*/
							}
							else
							{
								this.elm.appendChild(imgclone);
								
								this.elm.removeChild(images[0]);
								
							}
							if(this.index == this.totalItems - 1)
							{
								this.index = 0;
							}
							else
							{
								this.index++;
							}
						break;
						case 'tb':
							
							imgclone = lastImg
							
							if(this.animation)
							{	//	animation
								
								if(firstImg.id != imgclone.id)
								{
									$(imgclone).hide();
									
									new Insertion.Before(firstImg.id, imgclone);	
									
									Effect.SlideDown(imgclone,{duration: 0.2,queue: {position:'end', scope: 'tb',limit: 1},
										
										afterFinish: function()
										{
										
											this.isSliding = false;
											this.count = this.count +1	
											this.scroll(direction)
										}.bind(this),
										beforeStart: function()
										{
											this.isSliding = true;
										}.bind(this)
									});
								}
								//new Effect.Move(this.elm, { x: this.stepX, y: this.stepY });	//,duration:0.5 
													
							}
							else	//	geen animatie
							{									
								new Insertion.Before(firstImg.id, imgclone);
								this.elm.removeChild(lastImg);							
							}				
							if(this.index == 0)
							{
								this.index = this.totalItems;
							}
							else
							{
								this.index = this.index - 1;	
							}
						break;
						case 'bt':						
							imgclone = firstImg
							
							//	nieuwe plaatje klikgedrag geven
							if(this.animation)
							{						
								if(lastImg.id != imgclone.id)
								{
									Effect.SlideUp(firstImg,
										{duration: 0.2,queue: {position:'end', scope: 'bt',limit: 1},
										afterFinish: function()
										{
											new Insertion.After(lastImg.id,imgclone);
											this.isSliding = false;
											this.count = this.count +1	
											this.scroll(direction)
										}.bind(this),
										beforeStart: function()
										{
											//var_dump(this);
											this.isSliding = true;
										}.bind(this)
									});
								}							
							}
							else
							{
								this.elm.appendChild(imgclone);
								
								this.elm.removeChild(images[0]);
								
							}
							
							if(this.index == this.totalItems - 1)
							{
								this.index = 0;
							}
							else
							{
								this.index++;
							}
						break;					
					}
					
						
					this.isScrolling = false;				
					imgclone = '';
					
					//	buttons disabled class geven wanneer carrousel aanstaat en het uiteinde van de gallery is bereikt
					if(this.carrousel == false && this.index == 0)
					{
						this.btn_up.addClassName('disabled_up'); //alert('begin');
					}
					else
					{
						this.btn_up.removeClassName('disabled_up');	
					}
					if(this.carrousel == false && this.index == (this.totalItems - this.extraItems)-1)
					{
						this.btn_down.addClassName('disabled_down'); //alert('begin');
					}
					else
					{
						this.btn_down.removeClassName('disabled_down');	
					}
				}
			}
        }
        
        /* Einde class imagescroll*/	
    }
);

/* from SlideUp */
Effect.SlideLeftOut = function(element) {
	//var_dump(element)
/*
	SlideLeftOut needs to have the content of the element wrapped in a container element with fixed width
	otherwise any text or images begin to wrap in strange ways!
*/
	element = $(element).cleanWhitespace();
	return new Effect.Scale(element, window.opera ? 0 : 1,
		Object.extend({ 
			scaleContent: false, 
			scaleY: false, 
			scaleMode: 'box',
			scaleFrom: 100,
			restoreAfterFinish: true,
			beforeStartInternal: function(effect) {
				effect.element.makePositioned();
				effect.element.makePositioned();
				if(window.opera) effect.element.setStyle({left: ''});
				effect.element.makeClipping().show();
			},  
			afterUpdateInternal: function(effect) {
				effect.element.setStyle(
					{right: (effect.dims[1] - effect.element.clientWidth) + 'px' }
				);
			},
			afterFinishInternal: function(effect) {
				effect.element.hide().undoClipping().undoPositioned();
				effect.element.undoPositioned();
			}
		}, arguments[1] || {})
	);
}

/* from SlideDown */
Effect.SlideRightIn = function(element) {
/*
	SlideRightIn needs to have the content of the element wrapped in a container element with fixed width!
*/
	element = $(element).cleanWhitespace();
	var elementDimensions = element.getDimensions();
	return new Effect.Scale(element, 100, 
		Object.extend({ 
			scaleContent: false, 
			scaleY: false, 
			scaleFrom: window.opera ? 0 : 1,
			scaleMode: {originalHeight: elementDimensions.height, originalWidth: elementDimensions.width},
			restoreAfterFinish: true,
			afterSetup: function(effect) {
				effect.element.makePositioned();
				effect.element.makePositioned();
				if(window.opera) effect.element.setStyle({left: ''});
				effect.element.makeClipping().setStyle({width: '0px'}).show(); 
			},
			afterUpdateInternal: function(effect) {
				effect.element.setStyle({right: (effect.dims[1] - effect.element.clientWidth) + 'px' }); 
			},
			afterFinishInternal: function(effect) {
				effect.element.undoClipping().undoPositioned();
				effect.element.undoPositioned();
			}
		}, arguments[1] || {})
	);
}

