window.addEvent('domready', function() {
	$$('.pg-gl').each(function(wrapper) {
		if(!wrapper.hasClass('pg-init')) new pgGridLightbox(wrapper);
		wrapper.addClass('pg-init');
	});
});

var pgGridLightbox = new Class({
																 
	Implements: [Options],
 
	options: {
		initial: 0
	},
												
	initialize: function(el, options) {
		//options
		this.setOptions(options);
		
		//main element reference
		this.wrapper = $(el);
		
		//last item to be clicked
		this.last = {
			clicked: false,
			index: 0
		};
		
		//-----
		
		//thumbs
		this.thumbs = {
			images: this.wrapper.getElements('.thumbs img'),
			imagesSrc: []
		};
		
		this.thumbs.images.each(function(thumb) {																		 
			//store thumbnail info
			var parts = thumb.get('title').split('##');
			thumb.set('title', '');
			thumb.store('index', parts[0]);
			thumb.store('title', parts[1].length > 0 ? parts[1] + ':' : '&nbsp;');
			thumb.store('tip:title', parts[1].length > 0 ? parts[1] : '&nbsp;');
			thumb.store('description', parts[2].length > 0 ? parts[2] : '&nbsp;');
			thumb.store('tip:text', parts[2].length > 0 ? parts[2] : '&nbsp;');
		}.bind(this));
		
		
		//preload
		this.preload();
		
		//-----
		
		//tooltips
		this.tips = new Tips(this.thumbs.images, {
			className: 'pg-gl-tip',
			offset: {'x': -125, 'y': 20}
		});
	},
	
	//preload all images, adjust margins, trigger initial click
	preload: function() {
		this.thumbs.images.each(function(thumb) {
			this.thumbs.imagesSrc.push(thumb.getParent().get('href'));
		}.bind(this));
		
		new Asset.images(this.thumbs.imagesSrc);
		
		return this;
	}
	
});
