/**
 * File: http://www.garagemahals.com/gallery/js/scripts.js
 */

var Thumbs = new Class({
	
	initialize: function() {
		this.ajax_thumbs = new Request.HTML({
			autoCancel: true,
			update: 'ajax_thumbs',
			onRequest: function() {
				var shade = new Element('div', {
					'id': 'shade',
					'html': 'Loading Images',
					'styles': {'opacity': 0.7}
				});
				shade.inject('ajax_thumbs');
			},
			onComplete: this.setControlEvents.bind(this)
		});
		this.ajax_copy = new Request.HTML({
			autoCancel: true,
			update: 'copy'
		});
	},
	
	getThumbs: function(page, group) {
		this.page = page;
		this.group = group;
		
		$('image').load('/gallery/ajax/image.php?g=' + group);
		this.ajax_thumbs.get('/gallery/ajax/thumbs.php?p=' + page + '&g=' + group);
		this.ajax_copy.get('/gallery/ajax/groupcopy.php?g=' + group);
	},
	
	setControlEvents: function(evt) {
		this.curPage = 1;
		
		this.sliderFx = new Fx.Tween('slider', {
			transition: 'sine:in:out',
			duration: 750,
			link: 'cancel',
			unit: 'px'
		});
		
		if ($('controls')) {
			$$('#controls span').addEvent('click', this.onControlClick.bind(this));
			$$('#controls span').addEvent('mouseover', function(evt) {evt.target.addClass('hover');});
			$$('#controls span').addEvent('mouseout', function(evt) {evt.target.removeClass('hover');});
		}
		
		$('slider').getElements('img').addEvent('mouseenter', function(evt) {
			$('image').load('/gallery/ajax/image.php?i=' + evt.target.get('src'));
		});
		
		$('slider').getElements('span').addEvent('click', this.deleteImage.bind(this));
	},
	
	deleteImage: function(evt) {
		if (confirm('Delete Image?'))
			this.ajax_thumbs.get('/gallery/ajax/thumbs.php?del=' + evt.target.get('id') + '&p=' + this.page + '&g=' + this.group);
	},
	
	onControlClick: function(evt) {
		if (evt.target.hasClass('dn'))
			this.switchPage('dn', evt);
		else if (evt.target.hasClass('up'))
			this.switchPage('up', evt);
		else
			this.switchPage(evt.target.get('html'), evt);
	},
	
	switchPage: function(p, evt) {
		switch (p) {
			case 'up' :
				if ($('slider').getElement('div.thumbs').getChildren().length > 20 * this.curPage)
					this.sliderFx.start('left', -375 * this.curPage++);
				break;
			case 'dn' :
				if (this.curPage > 1)
					this.sliderFx.start('left', -375 * (--this.curPage - 1));
				break;
			default :
				this.sliderFx.start('left', -375 * (p - 1));
				this.curPage = p;
				break;
		}
		this.resetControls();
	},
	
	resetControls: function() {
		$('controls').getChildren().each(function(el) {
			if (el.hasClass('active'))
				el.removeClass('active');
		});
		$('control' + this.curPage).addClass('active');
	}
});

var thm = new Thumbs();