﻿var SlideShow = new Class({
    Implements: [Options],
    options: {
		url: '',
		relativePath: '',
		delay: 4000,
		width: 135,
		height: 135,
		images: [],
		startDelay: 2000
    },
   initialize: function(element, options) {
		this.element = $(element);
		this.setOptions(options);
		this.build();
		if ( this.options.images.length == 0 && this.options.url != '' )
			this.getImages(this.options.url);
		else
			this.start();
    },
    build: function() {
		var img = new Element('img', {'id':'img0','styles':{'border':'solid 1px #000','position':'absolute','top':0,'left':0,'display':'none'}});
		this.element.grab(img);
		var img2 = img.clone();
		img2.set('id','img1');
		this.element.grab(img2);
    },
    getImages: function (url) {
		this.request = new Request.JSON({
			'url': url,
			'link': 'cancel'
		}).addEvent('onComplete', function(response) {this.options.images = response;this.start();}.bind(this));
		this.request.send();
    },
    start: function () {
		if ( this.options.images == null || this.options.images.length == 0 ) return;
		if ( !this.Playing ) this.element.getElements('img').each(this.extendImages.bind(this));
    },
    extendImages: function (img, idx, arr) {
		img.setStyles({'width':this.options.width,'height':this.options.height});
		img.addEvent('load', function () {
			arr[idx>0?0:1].fade(0);
			arr[idx].setStyle('display','');
			arr[idx].fade(1);
			window.setTimeout( function () {if (this.options.images!=null) arr[idx>0?0:1].set('src', this.options.relativePath+this.options.images.getRandom()) }.bind(this), this.options.delay+(this.FirstImage?this.options.startDelay:0));
			this.FirstImage = false;
		}.bind(this));
		if(idx==0) img.set('src',this.options.relativePath+this.options.images.getRandom()).setStyle('display','');
		this.Playing = true;
		return img;
    },
    Playing: false,
    FirstImage: true
});
