/**
 * @author micromongo
 */

var ImageBox = Class.create();
ImageBox.prototype = {
	initialize: function(id) {
    	this.id = id;
		this.images = new Array();
		this.imagesrc = new Array();
		this.current = 0;
		this.setup();

	},
	
	
	setup: function() {
    	
		images = this.images;
		imagesrc = this.imagesrc;
		$(this.id).childElements().each(function(e){
			if (e.tagName == "IMG") {
				images[images.size()] = e;
				imagesrc[images.size()] = new Image();
				imagesrc[images.size()] = e.src;
			}
		});
		
		this.current = 0;
		this.display(0);
	},
	
	display: function(image_id) {
		$(this.id).innerHTML = "";
		$(this.id).insert(this.images[image_id]);
		this.current = image_id;
	}
};

var ImageBoxControl = Class.create();
ImageBoxControl.prototype = {
	initialize: function(config) {
		this.buttons = new Array();
		this.config = config;
		this.setup();
		
		if (config.mode.type == "slideshow") {
			setInterval("" + config.htmlname + ".next();", config.mode.duration);
		}
	},
	
	setup: function() {
		config = this.config;
		id = config.htmlid;
		name = config.htmlname;
		prefix = config.prefix;
		templ = new Template(config.item_pattern);
		buttons = this.buttons;
		
		if (!this.config.visible) {
			$(id).writeAttribute({
				style: "display: none;"
			});
		}
		
		this.config.imagebox_obj.images.each(function(e,index) {
			random = Math.random() * 100;
			if(config.next_on_click){
				next = index + 1;
				if (next == (config.imagebox_obj.images.size())) {
					next = 0;
				}
				e.writeAttribute({
					onclick: name + '.display(' + next + ')',
					style: "cursor:pointer;"
				});
				//e.observe('click', function(event){
				//	obj.display(Event.element(event).innerHTML -1);
				//});	
			}
			vars = {link: name + ".display(" + index + ");" , htmlclass: '', htmlid: prefix + random , title: index + 1};
			tmp = templ.evaluate(vars);
			
			if (config.reverse) {
				$(id).insert({
					top: tmp
				});
			}
			else {
				$(id).insert(tmp, {
					position: 'after'
				});
			}
			
			buttons[buttons.size()] = $(prefix + random );
			buttons[0].addClassName(this.config.active_flag);
		});
	},
		
	display: function(id) {
		this.buttons[this.config.imagebox_obj.current].removeClassName(this.config.active_flag);
		this.buttons[id].addClassName(this.config.active_flag);
		this.buttons[id].update(id + 1);
		this.config.imagebox_obj.display(id);
		this.buttons[id];
	},
	
	next: function() {
		next = this.config.imagebox_obj.current + 1
		if (next == (this.config.imagebox_obj.images.size())) {
			next = 0;
		}
		this.display(next);
	}
	
		
};

