var SouvenirSlider = new Class({
	Implements: [Events, Options],
	
	slider: null,
	pushLinks: null,
	data: null,
	currentCategory: null,
	
	initialize: function(jsonFileURL, pushLinks, slider){
		this.pushLinks = $(pushLinks);
		this.slider = $(slider);
		new Request.JSON({
			method: 'get',
			url: jsonFileURL,
			onSuccess: function(response, responseText){
				this.data = response;
				this.loadCategory();
			}.bind(this)
		}).send();
		pushLinks.addEvent('click:relay(a)', function(el){
			this.loadCategory(el.target.firstChild.data);
			el.target.getParent().getChildren().removeClass('selected');
			el.target.addClass('selected');
		}.bind(this));
		this.slider.addEvent('click:relay(a)', this.displayInfo.bind(this));
	},
	
	loadCategory: function(category){
		$$('.bubble').destroy();
		if(category == null){
			category = this.data['categories'].getRandom();
			this.pushLinks.getElements('a').each(function(element){
				if(element.firstChild.data == category)
					element.addClass('selected');
			});
		}
		this.currentCategory = category;
		if(this.slider.getChildren().length>0){
			this.slider.empty();
		}
		this.buildSlider(this.data[this.currentCategory]);
	},
	
	buildSlider: function(souvenirs){
		souvenirs.each(function(el, index){
			var link = new Element('a', {href: '#', rel: this.currentCategory + ',' + index, title: el.title, style: 'background-image: url("'+el.image+'"); width: 172px; height: 172px; float: left; margin-left: 20px; margin-top: 15px'});
			var image = new Element('img', {src: '/images/home/mask-thumb.png', rel: this.currentCategory + ',' + index});
			link.adopt(image).inject(this.slider);
		}, this);
	},
	
	displayInfo: function(event){
		$$('.bubble').destroy();
		var info = event.target.getParent().getProperty('rel').split(',');
		var souvenir = this.data[info[0]][parseInt(info[1])];
		var html = new Element('div',{
			'class': 'bubble',
			html: '<div class="top">&nbsp;</div><div class="content"><a href="#" class="close">&nbsp;</a><h2>' + souvenir.title + '</h2><div class="bubble-subtitle"><p>Mémoire :</p><a href="' + souvenir.urlMemory + '">' + souvenir.memory +'</a></div><cite>« ' + souvenir.description +' (...) »</cite><a href="' + souvenir.url + '" class="visit-souvenir">Voir le souvenir</a></div><div class="bottom left">&nbsp;</div>'
		});
		var position = event.target.getPosition();
		//Si le cadre est le dernier on change sa classe et la position en X
		if(info[1] == "4"){
			html.getElement('.bottom').removeClass('left').addClass('right');
			position.x -= 205;
		} else {
			position.x += 50;
		}
		position.y -= 125;
		html.setPosition(position);
		html.getElement('.close').addEvent('click', function(){
			this.getParent().getParent().destroy();
		});
		$('content').adopt(html);
	}
});
var s;
window.addEvent('domready', function(){
	s = new SouvenirSlider('/home/souvenir-slider.json', $('push-links'), $('souvenir-slider'));
});