/*
---

script: ThumbnailGrid.js

name: ThumbnailGrid

description: Turns a bunch of thumbnails into an active grid that (for example) can be used for a slideshow

license: MIT-style license

authors: Rolf Langenhuijzen

requires: [Core, More/Element.Delegation]

provides: [ThumbnailGrid]

...
*/

var ThumbnailGrid = new Class({

	Implements: [Events, Options],

	options: {
		/*
		onEnabled: function(){},
		onDisabled: function(){},
    onClick: function(){},
    onSetCurrent: function(){},
		*/
	  thumbnailContainerSelector: 'li',
	  initialThumbnailIndex: 0,
		currentClass: 'current'
	},

  collection: [],

  initialize: function(grid, options){
		this.setOptions(options);
		this.element = document.id(grid);
    this.current = this.options.initialThumbnailIndex;

		this.bound = {
      click: this.click.bind(this)
		};

    this.setup(this.current).enable();
	},

	toElement: function(){
		return this.element;
	},

  setup: function(current){
    this.makeCollection().setCurrent(current);
    return this;
  },

  makeCollection: function(){
    this.collection = this.element.getElements(this.options.thumbnailContainerSelector);
    return this;
  },

  enable: function(){
    this.attach();
    this.fireEvent('enabled');
    return this;
  },

  disable: function(){
    this.detach();
    this.fireEvent('disabled');
    return this;
  },

  attach: function(attach){
		attach = attach != null ? attach : true;
		var method = attach ? 'addEvents' : 'removeEvents';
    var events = {};
    events['click:relay('+this.options.thumbnailContainerSelector+')'] = this.bound.click;
    this.element[method](events);
  },

  detach: function(){
    this.attach(false);
  },

  click: function(event, clicked){
    event.preventDefault();
    var index = this.collection.indexOf(clicked);
		if (this.current === index) return this;
    this.setCurrent(index);
		this.fireEvent('click', [event, index, clicked]);
		return this;
  },

  setCurrent: function(index) {
		//console.log('setCurrent collection: ', this.collection);
		//console.log('setCurrent index: ', index);
		//console.log('setCurrent this.current: ', this.current);
		if (this.options.currentClass != ''){
			this.collection[this.current].removeClass(this.options.currentClass);
			this.collection[index].addClass(this.options.currentClass);
		}
		this.current = index;
		this.fireEvent('setCurrent', [index, this.collection[index]]);
		return this;
  }

});

