//
// WMW GALLERY
// 
// @author: Nik Van Looy
// @version: 14 april 2008
//
//
 
var wmwGallery = {
 	initialize: function(element, options) {
		this.setOptions({
			gallerySelector: 'div.galleryEl',
			albumSelector: 'div.albumEl',
			categorySelector: 'div.categoryEl',
			groupSelector: 'div.groupEl',
			imageSelector: 'div.imageEl',
			albumTitleSel: 'h1',
			categoryTitleSel: 'h2',
			groupTitleSel: 'h3',
			imageTitleSel: 'h4',
			albumDescriptionSel: 'p.albumDscriptEl',
			categoryDescriptionSel: 'p.categoryDscriptEl',
			groupDescriptionSel: 'p.groupDscriptEl',
			imageDescriptionSel: 'p.imageDscriptEl',
			imageLinkSel: 'p.imageLinkEl',
			imageAuteurSel: 'p.imageAuteurEl',
			imageCopyrightSel: 'p.imageCopyrightEl',
			
			albumlinkClass: 'default',
			
			albumThumbSel: 'img.albumThumb',
			categoryThumbSel: 'img.categoryThumb',
			groupThumbSel: 'img.groupThumb',
			imageThumbSel: 'img.imageThumb',
			imageFullSel: 'img.imageFull',
			
			displayOptions: ['full'],
			galleryClass: 'wmwgallery',
			imageContainerClass: 'imagecontainer',
			imagenavContainerClass: 'imagenav',
			dscriptContainerClass: 'dscriptcontainer',
			albumContainerClass: 'albumcontainer',
			categoryContainerClass: 'categorycontainer',
			groupContainerClass: 'groupcontainer',
			imageNavlinkClass: 'default',
			
			destroyAfterPopulate: true,
			
			albumDisplay: {gallerytitle: '', 
				show: true, 
				fade: true, 
				transition: 'fade', 
				dutation: 600, 
				pages: false, 
				perpage: 20, 
				display: 'title', 
				spacer:'albumSpacer'},
			groupDisplay: {show: true, 
				fade: false, 
				transition: 'fade', 
				duration: 600, 
				ifade: false, 
				itransition: 'fade', 
				iduration: 4000, 
				pages: true, 
				perpage: 8, 
				display: 'thumb'},
			groupItemDisplay: {spacing: '0', 
				width:75, 
				height:75,
				spacing:5,
				groupElOver:'img/thumbover.png'},
			dscriptDisplay: {show: true, 
				fade: false, 
				transition: 'fade', 
				duration: 1000, 
				simple:true, 
				link:true,
				from: 'image'}, // image of group
			imageDisplay: {initfade: true, 
				inittransition: 'fade', 
				initduration: 1000, 
				fade: false, 
				timed: true, 
				delay: 8000, 
				transition: 'fade',
				fadeduration: 300,
				showArrows: true},
			imageNavDisplay: {show:true,
				type:'number',// number or thumb
				thumbheight:75,
				thumbwidth:75,
				thumbspacing:0}, 
			
			select: {images:''},
			preloader: false
		}, options);
		this.currAlbumId = 0;
		this.currCategoryId = 0;
		this.currGroupId = 0;
		this.currImageId = 0;
		this.lastImageId = 0;
		this.maxImageId = 0;
		this.maxAlbums = 0;
		
		this.imageNavClicked == true;
		
		if((!this.options.imageDisplay['delay']) || this.options.imageDisplay['delay'] < 4000)
			this.options.imageDisplay['delay'] = 8000;
		
        this.imagesInit = 1;
        this.data = Array();
        this.dataImages = Array();
        this.albumElements = Array();
        this.groupElements = Array();
        this.imageElements = Array();
        this.albumElLinks = Array();
        this.imageNavElements = Array();
        
        this.galleryElement = element;
		this.createGalleryElements();
        
        this.sourceElement = element;

        this.getHtmlData();
        this.constructImageElements();
  		
  		if(this.options.albumDisplay['show'])
        	this.initAlbumsNav();
		this.doImageShow(1);
		if(this.options.groupDisplay['show'])
		{
			this.showGroupEl();
			this.changeGroupElStatus();
		}
	},
	createGalleryElements: function(){
        this.galleryElement.addClass(this.options.galleryClass);
        
		this.imageContainerEl = new Element('div').addClass(this.options.imageContainerClass).injectInside(this.galleryElement);
		this.loadingElement = new Element('div').addClass('loadEl').injectInside(this.imageContainerEl);
		
		if(this.options.imageNavDisplay['show'])
		{
			if(this.options.imageNavDisplay['type'] == 'number')
				this.imageNavEl = new Element('div').addClass(this.options.imagenavContainerClass).injectInside(this.galleryElement);
			else
			{
				this.imageNavElContainer = new Element('div').addClass(this.options.imagenavContainerClass).injectInside(this.galleryElement);
				imageNavElWrapper = new Element('div').addClass('imagenavwrapper').injectInside(this.imageNavElContainer);
				this.imageNavElWrapper = new Fx.Styles(imageNavElWrapper, {transition: Fx.Transitions.expoOut});
				this.imageNavEl = new Element('div').addClass('imagenavinner').setStyles({'width':'1000px'}).injectInside(imageNavElWrapper);	
				
				this.imageNavElWrapper.scroller = new Scroller(imageNavElWrapper, {
					area: 80,
					velocity: 0.2
				})
				
				this.imageNavElWrapper.elementScroller = new Fx.Scroll(imageNavElWrapper, {
					duration: 400,
					onStart: this.imageNavElWrapper.scroller.stop.bind(this.imageNavElWrapper.scroller),
					onComplete: this.imageNavElWrapper.scroller.start.bind(this.imageNavElWrapper.scroller)
				});
				this.imageNavElWrapper.scroller.start();
			}	
		}
			
		if(this.options.dscriptDisplay['show'])
			this.createDescriptionElements();
		this.albumEl = new Element('div').addClass(this.options.albumContainerClass).injectInside(this.galleryElement).setProperties({id:'albumwrapper'});
		
		if(this.options.albumDisplay['gallerytitle'])
			gallerytitle = new Element('div').addClass(this.options.albumDisplay['gallerytitle']).injectInside(this.albumEl);
		
		if(this.options.groupDisplay['show'])
		{
			groupElContainer = new Element('div').addClass(this.options.groupContainerClass).injectInside(this.galleryElement);
			groupElWrapper = new Element('div').addClass('groupwrapper').injectInside(groupElContainer);
			this.groupEl = new Element('div').addClass('groupinner').setStyles({'width':'1000px'}).injectInside(groupElWrapper);	
		}
	},
	
	// ---- IMAGE ELEMENT ----
	constructImageElements: function(){
		//console.log("constructelements");
		if(this.data[this.currAlbumId]['hascategories'] == 1)
			this.dataImages = this.data[this.currAlbumId]['categories'][this.currCategoryId]['groups'][this.currGroupId]['images'];
		else
			this.dataImages = this.data[this.currAlbumId]['groups'][this.currGroupId]['images'];

		if(this.data[this.currAlbumId]['hascategories'] == 1)
			this.dataGroups = this.data[this.currAlbumId]['categories'][this.currCategoryId]['groups'];
		else
			this.dataGroups = this.data[this.currAlbumId]['groups'];
			
		el = this.imageContainerEl;
		el.empty();
		
		var currentImg;
		this.maxImageId = this.dataImages.length;
		this.imageElements.length = 0;
		
		for(i=0;i<this.dataImages.length;i++)
		{				
			var currentImg = new Fx.Styles(
				new Element('div').addClass('imageEl').setStyles({
					'position':'absolute',
					'left':'0px',
					'right':'0px',
					'margin':'0px',
					'padding':'0px',
					'backgroundPosition':"center center",
					'opacity':'0'
				}).injectInside(el),
				'opacity',
				{duration: this.options.imageDisplay['fadeduration']}
			);
			if (this.options.preloader)
			{
				currentImg.source = this.dataImages[i].image;
				currentImg.loaded = false;
				currentImg.load = function(imageStyle) {
					if (!imageStyle.loaded)	
					{
						new Asset.image(imageStyle.source, {
                            'onload': function(img){
								img.element.setStyle(
								'backgroundImage',
								"url('" + img.source + "')"),
								img.loaded = true;
							}.bind(this, imageStyle)
						});
					}
				}.pass(currentImg, this);
			} 
			else 
			{
				currentImg.element.setStyle('backgroundImage',
					"url('" + this.dataImages[i].image + "')");
			}
			this.imageElements[parseInt(i)] = currentImg;
		}
		
		if(this.dataImages.length > 1 || this.options.imageNavDisplay['type'] == 'thumb')
		{
			if(this.options.imageNavDisplay['show'])
			{
				this.initImagesNav();
				this.changeImageNavElStatus();
			}
		}
		else
			this.clearImagesNav();
		
		if ((this.dataImages.length>1)&&(this.options.imageDisplay['showArrows']))
		{
			
			var leftArrow = new Element('a').addClass('left').addEvent(
				'click',
				this.prevImage.bind(this)
			).injectInside(this.galleryElement);
			var rightArrow = new Element('a').addClass('right').addEvent(
				'click',
				this.nextImage.bind(this)
			).injectInside(this.galleryElement);
		}
	},
	doImageShow: function(position) {
		//console.log("doImageShow");
		if (this.imagesInit == 1) // eerste keer
		{
			imgPreloader = new Image();
			imgPreloader.onload=function(){
				this.startImageShow.delay(10, this);
			}.bind(this);
			imgPreloader.src = this.dataImages[0].image;
			if(this.options.preloader)
				this.imageElements[0].load();
		}
		else
		{
			if(this.options.dscriptDisplay['show'])
				this.changeDescriptionEl();
			if(this.dataImages.length > 0 && this.options.imageNavDisplay['show'])
				this.changeImageNavElStatus();
		}

	},
	startImageShow: function() {
		//console.log("startImageShow");
		this.loadingElement.style.display = "none";
		this.lastImageId = this.maxImageId - 1;
		this.currImageId = 0;
		this.imagesInit = 0;

		if(this.options.imageDisplay['initfade'])
			this.imageElements[parseInt(this.currImageId)].start({opacity: 1});
		else
			this.imageElements[parseInt(this.currImageId)].set({opacity: 1});
		if(this.options.dscriptDisplay['show'])
			this.showDescriptionEl();
		// this.showDescriptionEl.delay(1000, this);
		if(this.dataImages.length > 1)
			this.prepareTimer();
	},
	prepareTimer: function() {
		//console.log("prepare timer");
		if (this.options.imageDisplay['timed'])
			this.timer = this.nextImage.delay(this.options.imageDisplay['delay'], this);
	},
	clearTimer: function() {
		//console.log("clear timer");
		if (this.options.imageDisplay['timed'] && this.dataImages.length > 1)
			$clear(this.timer);
	},
	nextImage: function() {
		//console.log("next image");
		//console.log('max: '+this.maxImageId+' - curr: '+ this.currImageId);
		this.nextImageId = this.currImageId+1;
		if (this.nextImageId >= this.maxImageId)
			this.nextImageId = 0;
		this.imagesInit = 0;
		this.gotoImage(this.nextImageId);
	},
	prevImage: function() {
		//console.log("prev image");
		this.nextImageId = this.currImageId-1;
		if (this.nextImageId <= -1)
			this.nextImageId = this.maxImageId - 1;
		this.imagesInit = 0;
		this.gotoImage(this.nextImageId, 5);
	},
	gotoImage: function(num) {
		//console.log("gotoImage");
		this.clearTimer();
		if(this.options.preloader)
		{
			
			this.imageElements[num].load();
			if (num==0)
				this.imageElements[this.maxImageId - 1].load();
			else
				this.imageElements[num - 1].load();
			if (num==(this.maxImageId - 1))
				this.imageElements[0].load();
			else
				this.imageElements[num + 1].load();
		}
		this.currentChangeDelay = this.changeItem.delay(100, this, num);

		if(this.dataImages.length > 1)
			this.prepareTimer();
		
	},
	changeItem: function(num) {
		//console.log("changeItem");
		this.imagesInit = 0;
		if (this.currImageId != num)
		{
			for(i=0;i<this.maxImageId;i++) // alles onzichtbaar maken behalve current image
			{
				if (i != this.currImageId) 
					this.imageElements[i].set({opacity: 0}); 
			}
			wmwGallery.Transitions[this.dataImages[num].transition].pass([
				this.imageElements[this.currImageId],
				this.imageElements[num],
				this.currImageId,
				num,
				this.options.imageDisplay['fadeduration']], this)();
			this.currImageId = num;
		}

		this.doImageShow.bind(this)();
	},
	
	// ---- DESCRIPTION ELEMENT ----
	createDescriptionElements: function(){
		if(this.options.dscriptDisplay['fade'])
		{
			this.descriptEl = new Fx.Styles(new Element('div').addClass(this.options.dscriptContainerClass).injectInside($(this.galleryElement))).set({'opacity':0});
			if(!this.options.dscriptDisplay['simple'])
				var infoTitle = new Element('h2').injectInside(this.descriptEl.element);
			var infoDescription = new Element('p').injectInside(this.descriptEl.element);
		}
		else
		{
			this.descriptEl = new Element('div').addClass(this.options.dscriptContainerClass).injectInside(this.galleryElement);
			arrow = new Element('div').addClass('pijl');
			arrow.injectInside(this.descriptEl);
			if(!this.options.dscriptDisplay['simple'])
				var infoTitle = new Element('h2').injectInside(this.descriptEl);
			var infoDescription = new Element('p').injectInside(this.descriptEl);
		}
		if(this.options.dscriptDisplay['link'])
			this.descriptLinkEl = new Element('div').addClass('linkcontainer').injectInside(this.galleryElement);
	},
	changeDescriptionEl: function()
	{
		if(this.options.dscriptDisplay['fade'])
		{
			this.hideDescriptionEl.delay(10, this);
			this.showDescriptionEl.delay(500, this);
		}
		else
			this.showDescriptionEl.delay(100, this);
	},
	hideDescriptionEl: function() {
		if(this.options.dscriptDisplay['fade'])
		{
			this.descriptEl.clearTimer();
			this.descriptEl.start({'opacity': 0});
			this.descriptLinkEl.setHTML('');
		}
		else
		{
			if(!this.options.dscriptDisplay['simple'])
				this.descriptEl.getElement('h2').setHTML("");
			this.descriptEl.getElement('p').setHTML("");
			this.descriptLinkEl.setHTML('');
		}
		return this.descriptEl;
	},
	showDescriptionEl: function() {
		if(this.options.dscriptDisplay['fade'])
		{
			this.descriptEl.clearTimer();
			el = this.descriptEl.element;
		}
		else
			el = this.descriptEl;
			//console.log(this.options.dscriptDisplay['simple']);
		if(this.options.select['images'] != 'all')
		{
			if(this.options.dscriptDisplay['from'] == 'image')
			{
				var title = this.dataImages[this.currImageId].title;
				var description = this.dataImages[this.currImageId].description;
				var link = this.dataImages[this.currImageId].link;
			}
			else
			{
				var title = this.dataGroups[this.currGroupId].title;
				var description = this.dataGroups[this.currGroupId].description;
				var link = this.dataImages[this.currImageId].link;
			}
			//this.descriptLinkEl.setHTML(this.dataImages[this.currImageId].link);
			if(link != '' && link != undefined)
			{
				this.descriptLinkEl.innerHTML = '';
				var link = new Element('a').addClass('link').injectInside(this.descriptLinkEl);
				link.setProperties({href: this.dataImages[this.currImageId].link, target: '_blank'});
				//var linkicon = new Element('div').addClass('linkicon').injectInside(this.descriptLinkEl);
			}
		}
		else
		{
			var title = this.dataImages[this.currImageId].title;
			var description = this.dataImages[this.currImageId].description;
		}
		if(this.options.dscriptDisplay['simple'])
		{
			el.getElement('p').setHTML(title);
			if(this.dataGroups[this.currGroupId].description != '')
				el.getElement('p').innerHTML += " - " +description;
		}
		else
		{
			el.getElement('h2').setHTML(title);
			el.getElement('p').setHTML(description);
		}
		
		if(this.options.dscriptDisplay['fade'])
			this.descriptEl.start({'opacity': [0, 1]});
		//if (this.options.showCarousel)
		//	this.slideInfoZone.chain(this.centerCarouselOn.pass(this.currentIter, this));
		return this.descriptEl;
	},

	// ---- ALBUM ELEMENT ----
	initAlbumsNav: function(){	
		if(this.options.albumDisplay['spacer'] != '')
			spacerEl = new Element('div').addClass(this.options.albumDisplay['spacer']);
		this.albumElements.length = 0;
		for(i=0;i<this.maxAlbums;i++)
		{
			var currAlbumLink = new Element('a').addClass(this.options.albumlinkClass).setProperties({
					id: 'g'+this.data[i]['title'].toLowerCase(),
					title: this.data[i]['title']
				}).injectInside(this.albumEl);

			currAlbumLink.addEvents({
			'click': function(i){
				if(!this.albumElements[i].hasClass('active'))
					this.gotoAlbum(i);
				}.pass(i, this)});
			currAlbumLink.setHTML("<span>"+this.data[i]['title']+"</span>");
			if(this.options.albumDisplay['spacer'] != '' && i<this.maxAlbums-1)
				spacerEl.injectInside(this.albumEl);
			if(i == 0)
			{
				if(currAlbumLink.hasClass('default'))
					currAlbumLink.removeClass('default');
				if(!currAlbumLink.hasClass('active'))
					currAlbumLink.addClass('active');
			}
				
			this.albumElements[i] = currAlbumLink;
		}
		//console.log(this.data);
	},
	changeAlbumElStatus: function()
	{
		for(i=0;i<this.maxAlbums;i++)
		{
			if(this.currAlbumId != i)
			{
				if(!this.albumElements[i].hasClass('default'))
					this.albumElements[i].addClass('default');
				if(this.albumElements[i].hasClass('active'))
					this.albumElements[i].removeClass('active');
			}
			else
			{
				if(!this.albumElements[i].hasClass('active'))
					this.albumElements[i].addClass('active');
				if(this.albumElements[i].hasClass('default'))
					this.albumElements[i].removeClass('default');
			}
		}
	},
	gotoAlbum: function(albumId){
		//console.log("ANDER ALBUM");
		this.clearTimer();
		this.hideDescriptionEl();
		this.currAlbumId = albumId;
		this.currCategoryId = 0;
		this.currGroupId = 0;
		this.currImageId = 0;
        this.constructImageElements();
        this.imagesInit = 1;
        if(this.options.groupDisplay['show'])
		{
			this.showGroupEl();
			this.changeGroupElStatus();
		}
        this.doImageShow(1);
        this.changeAlbumElStatus();
	},
		
	// ---- GROUP ELEMENT ----
	createGroupElements: function(){
		if(this.options.groupDisplay['fade'])
		{
			this.groupEl = new Fx.Styles(new Element('div').addClass(this.options.dscriptContainerClass).injectInside($(this.galleryElement))).set({'opacity':0});
		}
		else
		{
			this.groupEl = new Element('div').addClass(this.options.groupContainerClass).injectInside(this.galleryElement);
		}
	},
	clearGroupsNav: function(){
		this.groupEl.setHTML();
	},
	showGroupEl: function() {
		this.clearGroupsNav();
		if(this.options.groupDisplay['fade'])
		{
			this.groupEl.clearTimer();
			el = this.groupEl.element;
		}
		else
			el = this.groupEl;
			
		this.groupElements.length = 0;
		for(i=0;i<this.dataGroups.length;i++)
		{
			var currGroupEl = new Element ('div').addClass("groupEl").setStyles({
					backgroundImage: "url('" + this.dataGroups[i].thumb + "')",
					backgroundPosition: "center center",
					backgroundRepeat: 'no-repeat',
					marginLeft: this.options.groupItemDisplay['spacing'] + "px",
					width: this.options.groupItemDisplay['width'] + "px",
					height: this.options.groupItemDisplay['height'] + "px"
				}).injectInside(el);

			var thumbover = new Fx.Style(new Element ('div').addClass("groupElOver").setStyles({
				backgroundPosition: "center center",
				backgroundRepeat: 'no-repeat',
				width: this.options.groupItemDisplay['width'] + "px",
				height: this.options.groupItemDisplay['height'] + "px"
			}).injectInside(currGroupEl), "opacity", {duration: 200}).set(0);
			
			currGroupEl.addEvents({
			'mouseover': function (myself) { 
				if(myself.element.get('opacity') != 1)
				{
					myself.clearTimer();
					myself.start(0.9);
				}
			}.pass(thumbover, this),
			'mouseout': function (myself) { 
				if(myself.element.get('opacity') != 1)
				{
					myself.clearTimer();
					myself.start(0);
				}
			}.pass(thumbover, this),
			'click': function(i){
				if(!this.groupElements[i].hasClass('active'))
					this.gotoGroup(i);
				}.pass(i,  this)});
			
			//currGroupEl.addEvent('click', this.gotoGroup.bind(this, i) );
			
			this.groupElements[i] = currGroupEl;
			this.groupElements[i]['groupElOver'] = thumbover;
		}
		return this.groupEl;
	},
	changeGroupElStatus: function()
	{
		for(i=0;i<this.dataGroups.length;i++)
		{
			var thumbover = this.groupElements[i]['groupElOver'];

			if(this.currGroupId != i)
			{
				if(!this.groupElements[i].hasClass('default'))
					this.groupElements[i].addClass('default');
				if(this.groupElements[i].hasClass('active'))
					this.groupElements[i].removeClass('active');
				thumbover.clearTimer();
				thumbover.set(0);
			}
			else
			{
				if(this.groupElements[i].hasClass('default'))
					this.groupElements[i].removeClass('default');
				this.groupElements[i].addClass('active');
				thumbover.clearTimer();
				thumbover.set(1);
			}
		}
	},
	gotoGroup: function(groupId)
	{	
		var myFunction = function() {
			if(this.dataImages.length > 1)
				this.clearTimer();
			this.hideDescriptionEl();
			this.currCategoryId = 0;
			this.currGroupId = groupId;
			this.changeGroupElStatus();
			this.currImageId = 0;
	        this.constructImageElements();
	        this.imagesInit = 1;
	        this.doImageShow(0);
		};
		var delay = (- ((parseInt(this.imageElements[parseInt(this.currImageId)].element.get('opacity')) -1) *300));
		myFunction.delay(delay, this);
        //console.log(this.currGroupId);
	},
	hideGroupEl: function() {
		this.groupEl.clearTimer();
		this.groupEl.start({'opacity': 0});
		return this.groupEl;
	},
	
	// ---- IMAGENAV ELEMENT ----
	clearImagesNav: function(){
		this.imageNavEl.setHTML("");
	},
	initImagesNav: function(){
		this.clearImagesNav();
		
		this.imageNavElements.length = 0;
		for(i=0;i<this.dataImages.length;i++)
		{
			if(this.options.imageNavDisplay['type'] == 'number')
			{
				var currImageLink = new Element('a').addClass(this.options.imageNavlinkClass).setProperties({
						id: i
					}).injectInside(this.imageNavEl);
	
				currImageLink.addEvents({
				'click': function(i){
					if(!this.imageNavElements[i].hasClass('active'))
						this.imagesNavAction(i);
					}.pass(i, this)});
				currImageLink.setHTML(i+1);
	
				if(i == 0)
				{
					if(currImageLink.hasClass('default'))
						currImageLink.removeClass('default');
					if(!currImageLink.hasClass('active'))
						currImageLink.addClass('active');
				}
					
				this.imageNavElements[i] = currImageLink;
			}
			else
			{
				var currImageLink = new Element ('div').addClass("imagenavEl").setStyles({
						backgroundImage: "url('" + this.dataImages[i].thumb + "')",
						backgroundPosition: "center center",
						backgroundRepeat: 'no-repeat',
						marginLeft: this.options.imageNavDisplay['thumbspacing'] + "px",
						width: this.options.imageNavDisplay['thumbwidth'] + "px",
						height: this.options.imageNavDisplay['thumbheight'] + "px"
					}).injectInside(this.imageNavEl);
					
				currImageLink.setProperty('id', 'imagenavid'+i);
				
				var ornament = new Element ('div').addClass("imagenavElOrnament").setStyles({
					backgroundPosition: "center center",
					backgroundRepeat: 'no-repeat',
					width: this.options.imageNavDisplay['thumbwidth'] + "px",
					height: this.options.imageNavDisplay['thumbheight'] + "px"
				}).injectInside(currImageLink);
				
				var thumboverel = new Element ('div').addClass("imagenavElOver").setStyles({
					backgroundPosition: "center center",
					backgroundRepeat: 'no-repeat',
					width: this.options.groupItemDisplay['width'] + "px",
					height: this.options.groupItemDisplay['height'] + "px"
				}).injectInside(ornament);
				
				var thumbover = new Fx.Tween(thumboverel, 'opacity', {duration: 200, link:'cancel'});
				thumbover.set(0);

				currImageLink.addEvents({
				'mouseover': function (myself) { 
					if(myself.element.get('opacity') != 1) {
						myself.set(0.9);
					}
				}.pass(thumbover, this),
				'mouseout': function (myself) { 
					if(myself.element.get('opacity') != 1) {
						myself.set(0);
					}
				}.pass(thumbover, this),
				'click': function(i){
					if(!this.imageNavElements[i].hasClass('active'))
						this.imagesNavAction(i);
					}.pass(i,  this)});
				
				//currGroupEl.addEvent('click', this.gotoGroup.bind(this, i) );
				
				this.imageNavElements[i] = currImageLink;
				this.imageNavElements[i]['imagenavElOver'] = thumbover;
			}
		}

		if(this.options.imageNavDisplay['type'] == 'thumb')
		{
			var thumbwidth = this.options.imageNavDisplay['thumbwidth'];
			var thumbspacing = this.options.imageNavDisplay['thumbspacing'];
			this.imageNavEl.normalWidth = ((this.maxImageId * (thumbwidth + thumbspacing))) + "px";
			this.imageNavEl.style.width = this.imageNavEl.normalWidth;
		}
	},
	imagesNavAction: function(i){
		this.options.imageNavClicked = true;
		
		this.gotoImage(i);

		/*if(this.dataImages.length > 0 && this.options.imageNavDisplay['show'])
			this.changeImageNavElStatus();*/
			
		if(this.options.dscriptDisplay['from'] == 'image')
		{
			if(this.options.dscriptDisplay['show'])
			{
				this.hideDescriptionEl();
				this.showDescriptionEl();
			}
		}
	},
	changeImageNavElStatus: function()
	{
		//console.log('change');
		for(i=0;i<this.dataImages.length;i++)
		{
			if(this.options.imageNavDisplay['type'] == 'thumb')
				var thumbover = this.imageNavElements[i]['imagenavElOver'];
					
			if(this.currImageId != i)
			{
				if(!this.imageNavElements[i].hasClass('default'))
					this.imageNavElements[i].addClass('default');
				if(this.imageNavElements[i].hasClass('active'))
					this.imageNavElements[i].removeClass('active');
				if(this.options.imageNavDisplay['type'] == 'thumb')
				{
					thumbover.clearTimer();
					thumbover.set(0);
				}
			}
			else
			{
				if(this.imageNavElements[i].hasClass('default'))
					this.imageNavElements[i].removeClass('default');
				this.imageNavElements[i].addClass('active');
				if(this.options.imageNavDisplay['type'] == 'thumb')
				{
					thumbover.clearTimer();
					thumbover.set(1);
					if(!this.options.imageNavClicked)
						this.imageNavElWrapper.elementScroller.toElement('imagenavid'+i);
					this.options.imageNavClicked = false;
				}
			}
		}
	},
	// ---- GET DATA FROM HTML ----
	getHtmlData: function(){
		// variabelen
		var albums = [];
		var categories = [];
		var albumTeller = 0;
		var categoryTeller = 0;
		var hasCategory = false;
		
		options = this.options;
		element = this.sourceElement;
		
		if(this.options.select['images'] != 'all')
		{
			// elementen uit de div halen (albumEl, categoryEl, groupEl en imageEl)
			// ALBUMS
			element.getElements(options.albumSelector).each(function(albumEl){
				// CATEGORIES
				categoryTeller = 0;
				categories = [];
				albumEl.getElements(options.categorySelector).each(function(categoryEl){
					category = {
						id: categoryTeller,
						title: categoryEl.getElement(options.categoryTitleSel).innerHTML,
						description: categoryEl.getElement(options.categoryDescriptionSel).innerHTML
					};
					
					groups = this.getImageGroups(categoryEl);
	
					category['imagegroups'] = groups;
					categories.extend([category]);
					categoryTeller++;
				});
				
				if(categoryTeller > 0)
				{
					album = {
						id: albumTeller,
						title: albumEl.getElement(options.albumTitleSel).innerHTML,
						description: albumEl.getElement(options.albumDescriptionSel).innerHTML,
						hascategories: 1
					};
				}
				else
				{
					album = {
						id: albumTeller,
						title: albumEl.getElement(options.albumTitleSel).innerHTML,
						description: albumEl.getElement(options.albumDescriptionSel).innerHTML,
						hascategories: 0
					};
				}
				//data.extend([album]);
				
	
				
				if(categoryTeller != 0)
				{
					hasCategory = true;
					album['categories'] = categories;
				}
				else
				{
					groups = this.getImageGroups(albumEl);
					album['groups'] = groups;
				}
							
				
				albums.extend([album]); 
				albumTeller++;
				if (this.options.destroyAfterPopulate)
					albumEl.remove();
			}.bind(this));
			
			this.data = albums;
			this.maxAlbums = albumTeller;
		}
		else
		{
			var categories = [];
			var album = [];
			var group = [];
			var groups = [];
			this.maxAlbums = 0;
			images = this.getImages(element);
			group['images'] = images;
			groups.extend([group]);
			album['groups'] = groups;
			albums.extend([album]);
			this.data = albums;
			element.getElements(options.albumSelector).each(function(albumEl){albumEl.remove();});
			element.getElements(options.groupSelector).remove();
			//console.log("test");		
		}

		//console.log(albums);
	},
	getImageGroups: function(el){
		var group = [];
		var image = [];
		var groups = [];
		var images = [];
		
		var groupTeller = 0;
		var imageTeller = 0;
		
		// GROUPS
		groupTeller = 0;
		groups = [];
		el.getElements(options.groupSelector).each(function(groupEl){
			group = {
				id: groupTeller,
				title: groupEl.getElement(options.groupTitleSel).innerHTML,
				description: groupEl.getElement(options.groupDescriptionSel).innerHTML,
				thumb: groupEl.getElement(options.groupThumbSel).getProperty('src'),
				init: 1
			};
			
			images = this.getImages(groupEl);
			
			group['images'] = images;
			groups.extend([group]);
			groupTeller++;
		}.bind(this));
		//console.log(groups);
		return groups;
	},
	getImages: function(groupel){
		// IMAGES
		imageTeller = 0;
		images = [];			
		groupel.getElements(options.imageSelector).each(function(imageEl){
			image = {
				id: imageTeller,
				image: imageEl.getElement(options.imageFullSel).getProperty('src'),
				thumb: imageEl.getElement(options.imageThumbSel).getProperty('src'),
				title: imageEl.getElement(options.imageTitleSel).innerHTML,
				description: imageEl.getElement(options.imageDescriptionSel).innerHTML,
				link: imageEl.getElement(options.imageLinkSel).innerHTML,
				auteur: imageEl.getElement(options.imageAuteurSel).innerHTML,
				copyright: imageEl.getElement(options.imageCopyrightSel).innerHTML,
				inittransition: this.options.imageDisplay['inittransition'],
				transition: this.options.imageDisplay['transition']
			};
			
			images.extend([image]);
			imageTeller++;
		});
		return images;
	}
	
};
 
wmwGallery = new Class(wmwGallery);
wmwGallery.implement(new Events);
wmwGallery.implement(new Options);
 
wmwGallery.Transitions = new Abstract ({
	fade: function(oldFx, newFx, oldPos, newPos, fadeDuration){
		oldFx.options.transition = newFx.options.transition = Fx.Transitions.linear;
		oldFx.options.duration = newFx.options.duration = fadeDuration;
		if (newPos > oldPos) newFx.start({opacity: 1});
		else
		{
			newFx.set({opacity: 1});
			oldFx.start({opacity: 0});
		}
	},
	crossfade: function(oldFx, newFx, oldPos, newPos, fadeDuration){
		oldFx.options.transition = newFx.options.transition = Fx.Transitions.linear;
		oldFx.options.duration = newFx.options.duration = fadeDuration;
		newFx.start({opacity: 1});
		oldFx.start({opacity: 0});
	},
	fadebg: function(oldFx, newFx, oldPos, newPos, fadeDuration){
		oldFx.options.transition = newFx.options.transition = Fx.Transitions.linear;
		oldFx.options.duration = newFx.options.duration = fadeDuration / 2;
		oldFx.start({opacity: 0}).chain(newFx.start.pass([{opacity: 1}], newFx));
	}
});


/* All code copyright 2007 Jonathan Schemoul */

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
 * Follows: Preloader (class)
 * Simple class for preloading images with support for progress reporting
 * Copyright 2007 Tomocchino.
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

var Preloader = new Class({
  
  Implements: [Events, Options],

  options: {
    root        : '',
    period      : 100
  },
  
  initialize: function(options){
    this.setOptions(options);
  },
  
  load: function(sources) {
    this.index = 0;
    this.images = [];
    this.sources = this.temps = sources;
    this.total = this. sources.length;
    
    this.fireEvent('onStart', [this.index, this.total]);
    this.timer = this.progress.periodical(this.options.period, this);
    
    this.sources.each(function(source, index){
      this.images[index] = new Asset.image(this.options.root + source, {
        'onload'  : function(){ this.index++; if(this.images[index]) this.fireEvent('onLoad', [this.images[index], index, source]); }.bind(this),
        'onerror' : function(){ this.index++; this.fireEvent('onError', [this.images.splice(index, 1), index, source]); }.bind(this),
        'onabort' : function(){ this.index++; this.fireEvent('onError', [this.images.splice(index, 1), index, source]); }.bind(this)
      });
    }, this);
  },
  
  progress: function() {
    this.fireEvent('onProgress', [Math.min(this.index, this.total), this.total]);
    if(this.index >= this.total) this.complete();
  },
  
  complete: function(){
    $clear(this.timer);
    this.fireEvent('onComplete', [this.images]);
  },
  
  cancel: function(){
    $clear(this.timer);
  }
  
});

Preloader.implement(new Events, new Options);

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
 * Follows: formatString (function)
 * Original name: Yahoo.Tools.printf
 * Copyright Yahoo.
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

function formatString() {
	var num = arguments.length;
	var oStr = arguments[0];
	for (var i = 1; i < num; i++) {
		var pattern = "\\{" + (i-1) + "\\}"; 
		var re = new RegExp(pattern, "g");
		oStr = oStr.replace(re, arguments[i]);
	}
	return oStr; 
}
