/* -------------------------------------------------------------------- */
/* NET4VISIONS.COM SIMPLEVIEWER - simpleViewer.js 04-10-2009 */
/* Version: 1.0 */
/* Created by: net4visions.com */
/* Last edited: 05-07-2009 */
/* Requirements: mootools 1.2.2.js
/* -------------------------------------------------------------------- */

var SimpleViewer = new Class({
	Implements: [Options, Events, Chain],
	
	options: {
		// onAutoPlay: 		$empty,
		// onStop: 			$empty,
		// onShow:			$empty,
		// onNext:			$empty,
		// onPrev:			$empty,
		start:				0,
		elPrev:				'btn-left',
		elNext:				'btn-right',
		itemClass:			'item',
		fadeTime:			500,
		stayTime:			4000,			
		autoplay:			true,
		replay:				true,
		preload:			true,
		debug:				false
	},
	
	initialize: function(element, options) {
		this.setOptions(options);
		if (this.options.debug) dbug.enable();
		
		if (!$chk($(element))) return false;			// NO BOX CONTAINER DEFINED
		
		this.pictureContainer	= $(element);
		this.thumbsContainer	= $('thumb-wrapper-div');	
		this.index 				= this.options.start || 0;
		this.previousIndex 		= this.index;
		
		this.prepare();
	},
	
	init: function() {
		if (!this.thumbs || !this.thumbs.length) {
			this.thumbsContainer.getParent().getParent().hide();
			this.pictureContainer.set('html', '<p>No pictures available... </p>');
			return false;
		}
		this.pictureContainer.empty();
		this.show();
		if (this.options.autoplay) this.play(this.options.stayTime + this.options.fadeTime, this);
	},
	
	prepare: function() {
		this.prepareHTML();
		this.preparePictures();
		
		this.attachEvents();
	},
	
	// PREPARE - SETUP PICTURES
	preparePictures: function() {
		var els = this.thumbsContainer.getElements('a.' + this.options.itemClass);
		if (!els.length) return false;
		
		// SET THUMBNAILS
		// set thumbs
		this.thumbs = els.map(function(item, index){
			item.setStyle('cursor','pointer');
			item.addEvents({
				click: function(e) {
					e.stop();
					this.stop();
					this.index = index-1;
					this.next();
				}.bind(this),
				mouseenter: function(e) {
					e.stop();
					this.stop();
				}.bind(this),
				mouseleave: function(e) {
					e.stop();
					if (this.restart) { this.play(); }
				}.bind(this)
			})		
			return item;
		}, this);
		
		// preload all thumbs
		this.loader.show();
		this.counter.inject(this.pictureContainer);
		new Asset.images( els.map(function(item){ return item.getFirst().get('src'); }), {
			onProgress: function(counter, index) {
				this.counter.set('text', 'Please wait while loading... ' + ((counter + 1) * (100 / els.length)).toInt()  + '%');
			}.bind(this),
			onComplete: function() {
				this.thumbsContainer.getParent().getParent().show();
				this.loader.hide()
				this.init();
			}.bind(this)
		});
		
		this.thumbsPerScroll = this._thumbsPerScroll();			// need to be before hiding the container
		this.thumbsContainer.getParent().getParent().hide();
		
		// SET PICTURES
		this.loadedPictures = [];
		this.pictures = els.map(function(item, index){
			return new Element('img', {
				src: 	item.get('href'),
				width:	'100%',
				height: '100%',
				styles: { cursor: 'pointer' },
				events: {
					click: function(e) {
						e.stop();
						this.toggle();
					}.bind(this),
					mouseenter: function(e) {
						e.stop();
						this.toggler.addClass('hover');
					}.bind(this),
					mouseleave: function(e) {
						e.stop();
						this.toggler.removeClass('hover');
					}.bind(this)
				},
				tween: { duration: this.options.stayTime }
			})
		}, this);
	},
	
	prepareHTML: function() {
		// loader
		var path = './assets/site/images/ajax-loader.gif';
		this.loader = new Element ('img', {
			id:			'loader',
			src: 		path,
			'class':	'loader',
			styles: {
				position:	'absolute',
				top:		'50%',
				left:		'50%',
				margin:		'-12px 0 0 -12px',
				'z-index':	999
			}
		}).inject(this.pictureContainer.getParent()).hide();
		
		this.counter = new Element('p', {
			'class': 'small'
		});

		// toggle autoplay button
		this.toggler =  new Element('div', {
			'class': 'btnToggle',
			events: {
				click: function(e) {
					e.stop();
					this.toggle();
				}.bind(this)
			}
		}).inject(this.pictureContainer.getParent());
	},

	attachEvents: function() {
		$(this.options.elNext).addEvent('click', function(e){
			e.stop();
			this.index = this.move('next');
			this.stop().next();
		}.bind(this));

		$(this.options.elPrev).addEvent('click', function(e){
			e.stop();
			this.index = this.move('prev');
			this.stop().previous();
		}.bind(this));
	},
	
	show: function() {
		var pi = this.previousIndex;	// pi - previous index
		var ci = this.index;			// ci - current index
		
		if (this.options.preload) {
			var file = this.pictures[ci].get('src');
			
			if (!this.loadedPictures.contains(file)) {
				this.stop();
				var picture = new Asset.image(file, {
					onload: function () {
						this.loadedPictures.push(file);
						this.pictures[ci].fade('hide').inject(this.pictureContainer).fade('in');
						if (this.restart) this.play();
					}.bind(this)
				},this)
			} else {
				this.pictures[ci].fade('hide').inject(this.pictureContainer).fade('in');
			}
		} else {
			this.pictures[ci].fade('hide').inject(this.pictureContainer).fade('in');
		}
		
		// update scroller
		this.fxScroll = this.fxScroll || new Fx.Scroll(this.thumbsContainer, {
			offset: { x: 0, y: 0 }
		}).toElement(this.thumbs[ci].getParent());
		
		if (this.move('step')) this.fxScroll.toElement(this.thumbs[ci].getParent());
		
		// highlight current scroll image (thumbnail)
		var hlight = function() {
			this.thumbs[pi].getParent().removeClass('current');
			this.thumbs[ci].getParent().addClass('current');
		};
		hlight.delay(this.options.fadeTime, this);
				
		this.previousIndex = this.index;
		
		this.fireEvent('onShow');
	},
	
	move: function(direction) {
		var count = Math.floor(this.index/this.thumbsPerScroll);
		switch(direction) {
			case 'next':
				return count * this.thumbsPerScroll + this.thumbsPerScroll -1;
				break;
			case 'prev':
				return count * this.thumbsPerScroll - this.thumbsPerScroll +1;
				break;
			case 'step':
				return count == Math.floor(this.previousIndex/this.thumbsPerScroll) ? false : true;
			default:
				return false;
		}
	},
	
	next: function() {
		this.index++;
		if (this.index > this.pictures.length-1) {
			if (!this.options.replay) this.stop();
			this.pictureContainer.empty();
			this.index = 0;
		}
		
		this.show();
		this.fireEvent('onNext');	
	},
	
	previous: function() {
		this.index--;
		this.index = this.index < 0 ? 0 : this.index;
		this.show();
		this.fireEvent('onPrev');	
	},
		
	// autoplay
	play: function() {
		this.intObj = this.next.periodical(this.options.stayTime + this.options.fadeTime, this);
		this.autoplay = true;
		this.fireEvent('onAutoPlay');
		return this;
	},
	
	stop: function() {
		this.restart = this.autoplay;
		this.autoplay = false;
		$clear(this.intObj);
		this.intObj = null;
		this.fireEvent('onStop');
		return this;
	},
	
	toggle: function() {
		this.autoplay ? this.stop() : this.play();
		return this;
	},
		
	_thumbsPerScroll: function() {
			var sw = this.thumbs[0].getParent().getDimensions({ computeSize: true, styles: ['margin', 'padding', 'border'] }).totalWidth; 		// thumb width
			this.thumbsContainer.getFirst().hide();
			var cw = this.thumbsContainer.getSize().x;	// container width
			this.thumbsContainer.getFirst().show();
			this.thumbsContainer.setStyle('width', cw);
	
			return Math.floor(cw / sw); 				// thumbs per scroll width
		}
	});