var Carrousel = Class.create(
{
	categories      : [],
	blinds          : [],
	selectedCategory: 0,
	selectedSlide   : 0,
	url             : null,
	timer           : null,
	options         : {
		blindsNb  : 6,
		container : 'carrousel',
		panel     : null,
		nav       : null,
		btnPrev   : null,
		btnNext   : null,
		width     : 600,
		height    : 230,
		slideshow : false,
		delay     : 6,
		fps       : 25,
		transition: Effect.Transitions.linear
	},

	utils: {
		getPosFromId: function(id){

			var pos = parseInt(id.substring(id.lastIndexOf('-')+1, id.length))

			return pos;
		}
	},

	initialize: function(options)
	{
		var opts = this.options;

		opts = Object.extend(opts, options || {});

		opts.container = $(opts.container).show();
		opts.panel     = $(opts.container.id + '-panel');

		this.onTabClickedAction   = this.onTabClicked.bindAsEventListener(this);
		this.onSlideClickedAction = this.onSlideClicked.bindAsEventListener(this);
		this.onPrevClickedAction  = this.onPrevClicked.bindAsEventListener(this);
		this.onNextClickedAction  = this.onNextClicked.bindAsEventListener(this);
		this.onPanelClickedAction = this.onPanelClicked.bindAsEventListener(this);
		this.slideShowAction      = this.selectNextSlide.bindAsEventListener(this);

		this.initContainer();
		this.initCategories();
		this.initTabs();
		this.initBlinds();
		this.initNav();

		this.selectCategory(0);
		this.updateNav(0);
		this.selectSlide(0, 0, true);

		this.restartSlideshow(this.options.delay);
	},

	onPanelClicked: function(event)
	{
		event.stop();

		if(this.uri)
		{
            if(this.newWindow)
            {
                window.open(this.uri);
            }
            else
            {
                window.location.href = this.uri;
            }
		}
	},

	onPrevClicked: function(event)
	{
		event.stop();

		Effect.Queues.get('carrousel').invoke('cancel');

		this.stopSlideshow();

		var min      = 0;
		var max      = this.options.nav.select('ul li a').length - 1;
		var selected = this.selectedSlide;
		var pos      = 0;

		if(selected>min)
		{
			pos = selected - 1;
		}
		else
		{
			pos  = max;
		}

		this.selectSlide(null, pos);
	},

	onNextClicked: function(event)
	{
		event.stop();

		Effect.Queues.get('carrousel').invoke('cancel');

		this.stopSlideshow();

		var min      = 0;
		var max      = this.options.nav.select('ul li a').length - 1;
		var selected = this.selectedSlide;
		var pos      = 0;

		if(selected<max)
		{
			pos = selected + 1;
		}
		else
		{
			pos  = 0;
		}

		this.selectSlide(null, pos);
	},

	onSlideClicked: function(event)
	{
		event.stop();

		var pos = this.utils.getPosFromId(event.element().id) || 0;

		if(pos !== this.selectedSlide)
		{
			Effect.Queues.get('carrousel').invoke('cancel');

			this.selectSlide(null, pos);
		}
	},

	onTabClicked: function(event)
	{
		event.stop();

		var pos = this.utils.getPosFromId(event.element().id) || 0;

		if(pos !== this.selectedCategory)
		{
			Effect.Queues.get('carrousel').invoke('cancel');

			this.selectCategory(pos);
			this.updateNav(pos);
			this.selectSlide(pos, 0);

			this.restartSlideshow();
		}
	},

    startScrollBg: function(delay)
    {
        var blinds = this.blinds;
		var slides = this.categories[this.selectedCategory].slides;
        var blinds = $$('.carrousel-blind');
        var panel  = $(this.options.container.id + '-panel');

        this.stopSlideshow();

        panel.addClassName('top10');

        Effect.Queues.get('carrousel').invoke('cancel');

        blinds.invoke('hide');

        if($('top10img'))
        {
            $('top10img').remove();
        }

        panel.insert({top: new Element('IMG', {id: 'top10img', src: slides[0].src, style: 'margin:29px 0 0 600px;'})});

        new Effect.Move(
            $('top10img'),
            {
                x: -$('top10img').width-600,
                y: 0,
                fps: 30,
                mode: 'relative',
                duration: 70,
                transition: Effect.Transitions.linear,
                queue: { scope: 'carrousel', limit: 1 },
                afterFinish: function(){

                    $('top10img').remove();
                    panel.removeClassName('top10');
                    blinds.invoke('setStyle', {backgroundImage: ''});
                    blinds.invoke('show');

                    var pos = (this.selectedCategory+1)%this.categories.length;
                    this.selectCategory(pos);
        			this.updateNav(pos);
        			this.selectSlide(pos, 0, true);
                    this.restartSlideshow();

                }.bind(this)
            }
        );
    },

    stopScrollBg: function()
    {
        window.clearInterval(this.timer);

		this.timer = null;
    },

	startSlideshow: function(delay)
	{
		this.timer = window.setInterval(this.slideShowAction, (delay + 3) * 1000);
	},

	stopSlideshow: function()
	{
		this.timer = window.clearInterval(this.timer);
	},

	restartSlideshow: function()
	{
        var opts  = this.options;
        var delay = opts.delay;

        this.stopSlideshow();

        if(this.categories[this.selectedCategory].slides.length > 1)
        {
            opts.navContainer.show();
        }
        else
        {
            opts.navContainer.hide();
        }

        if(2 == this.selectedCategory)
        {
            this.startScrollBg(1);
        }
        else if(opts.slideshow)
		{
			this.startSlideshow(delay);
		}
	},

	startRendering: function()
	{

	},

	stopRendering: function()
	{

	},

	selectNextSlide: function()
	{
        if((this.selectedSlide + 1) == this.categories[this.selectedCategory].slides.length)
        {
            var pos = (this.selectedCategory + 1)%(this.categories.length);

            Effect.Queues.get('carrousel').invoke('cancel');

			this.selectCategory(pos);
			this.updateNav(pos);
			this.selectSlide(pos, 0);

			this.restartSlideshow();
        }
        else
        {
            this.selectSlide(null, this.selectedSlide + 1);
        }
//		this.selectSlide(null, (this.selectedSlide + 1)%(this.categories[this.selectedCategory].slides.length));
	},

	moveNav: function(step)
	{
		new Effect.Move(this.options.nav.select('ul')[0], {duration: 0.35, x: step, y: 0, mode: 'relative'});
	},

	updateNav: function(selectedCategory)
	{
		var nav           = this.options.nav;
		var slides        = null;
		var html          = '';
		var slideTemplate = new Template('<li>' +
			'<a href="#{src}" id="' + this.options.container.id + '-slide-#{nb}" title="Slide #{name}">#{name}</a>' +
		'</li>');

		if(!selectedCategory)
		{
			selectedCategory = this.selectedCategory;
		}

		if(this.categories[selectedCategory].slides.length<2)
		{
			nav.hide();
		}
		else
		{
			this.categories[selectedCategory].slides.each(function(slide, pos){
				html += slideTemplate.evaluate({ src: slide.src, nb: pos, name: pos + 1});
			});

			nav.update('<ul>' + html + '</ul>');

			slides = nav.select('ul li a');

			slides.each(function(slide){
				slide.observe('click', this.onSlideClickedAction);
			}.bind(this));

			nav.show();
		}
	},

	selectCategory: function(newCategory)
	{
		var categories = this.categories;
		var selected   = this.selectedCategory;

		categories[selected].tab.removeClassName('selected');
		categories[newCategory].tab.addClassName('selected');

        this.updateNav(newCategory);

		this.selectedCategory = newCategory;
	},

	selectSlide: function(selectedCategory, pos, preventAnimation)
	{
		if(!selectedCategory)
		{
			selectedCategory = this.selectedCategory;
		}

		var blinds     = this.blinds;
		var slides     = this.categories[selectedCategory].slides;
		var navItems   = this.options.nav.select('ul li a');
		var selected   = this.selectedSlide;
        var parent     = $(slides[pos].parentNode);
		var length     = slides.length;
		var step       = 0;
		var opts       = this.options;
		var fps        = opts.fps;
		var transition = opts.transition;

		Effect.Queues.get('navitems').invoke('cancel');

        if(navItems[selected])
        {
    		navItems[selected].setStyle({opacity: 1});
    /*
    		new Effect.Morph(navItems[pos], {
    			style   : 'background:#3C0000;',
    			duration: opts.delay + 6, // pour effet visible sur la fin
    			queue   : {scope: 'navitems', limit: 1}
    		});
    */
        }

		new Effect.Morph(navItems[pos], {
			style   : 'color:#A06482;',
			duration: opts.delay + 6, // pour effet visible sur la fin
			queue   : {scope: 'navitems', limit: 1}
		});
/*
		new Effect.Fade(navItems[pos], {
				from    : 1,
				to      : 0.1,
				duration: opts.delay + 3,
				queue   : {scope: 'navitems', limit: 1}
			});
*/
//		this.


		if(!preventAnimation)
		{
			new Effect.multiple(blinds, Effect.Fade, {
				delay      : 0,
				duration   : 1.0,
				from       : .75,
				to         : 0.15,
				fps        : fps,
				queue      : {scope: 'carrousel', limit: opts.blindsNb*2},
				transition : transition,
				beforeStart: function(){
				    if(navItems[selected])
                    {
					   navItems[selected].setStyle({color: '#ffffff'});
                    }
//					Effect.Queues.get('navitems').invoke('cancel');
//					alert(this.options.nav.select('ul li a')[this.selectedSlide]);
//					navItems[selected].opacity(1);
				}.bind(this),
				afterFinish: function(effect){

					var el = $(effect.element);

					el.setStyle({backgroundImage: 'url(' + slides[pos].src + ')'});

					new Effect.Appear(el, {
						duration  : 1.0,
						from      : 0.15,
						to        : 1,
						fps       : fps,
						transition: transition,
						queue     : {scope: 'carrousel', limit: opts.blindsNb*2}
					});
				}
			});
		}
		else
		{
			blinds.each(function(blind){
				blind.setStyle({backgroundImage: 'url(' + slides[pos].src + ')'});
			});
		}

        if(navItems)
        {
    		navItems.invoke('removeClassName', 'selected');
    		navItems[pos].addClassName('selected');


    		if(slides.length>5)
    		{
    			if(selected == 0 && pos == length - 1)
    			{
    				step = -1 * Math.floor(length/5) * 105;
    			}
    			else if(selected == length - 1 && pos == 0)
    			{
    				step = Math.floor(length/5) * 105;
    			}
    			else if(pos>0)
    			{
    				if(Math.floor(selected/5)>Math.floor(pos/5))
    				{
    					step = 105;
    				}
    				else if(Math.floor(pos/5)>Math.floor(selected/5))
    				{
    					step = -105;
    				}
    			}
    		}

    		this.moveNav(step);
        }

		if(parent.nodeName.toUpperCase()=='A')
		{

			this.uri = parent.href;
            this.newWindow = parent.hasClassName('new-page');

			this.options.panel.observe('click', this.onPanelClickedAction);

			this.options.panel.setStyle({
				cursor: 'pointer'
			});
		}
		else
		{
			this.uri       = null;
            this.newWindow = false;

			this.options.panel.stopObserving('click', this.onPanelClickedAction);

			this.options.panel.setStyle({
				cursor: 'default'
			});
		}

		this.selectedSlide = pos;
	},

	initContainer: function()
	{
		this.options.container.insert({bottom: '<div class="clearer"></div>'});
	},

	initNav: function()
	{
		var opts        = this.options;
		var containerId = opts.container.id;
		var navTemplate = new Template('<div id="#{containerId}-nav">' +
			'<div id="#{containerId}-nav-prev-container">' +
				'<a id="#{containerId}-nav-prev-btn" href="#" title="Précédent">&lt;</a>' +
			'</div>' +
			'<div id="#{containerId}-nav-slides-container"></div>' +
			'<div id="#{containerId}-nav-next-container">' +
				'<a id="#{containerId}-nav-next-btn" href="#" title="Suivant">&gt;</a>' +
			'</div>'   +
		'</div>');

		opts.panel.insert({
			top: navTemplate.evaluate({
					containerId: containerId
				})
		});

		opts.navContainer = $(containerId + '-nav');

        opts.navContainer.setStyle({
			position: 'absolute',
			top     : '0px',
			right   : '0px',
			zIndex  : 110
		});

		opts.nav = $(containerId + '-nav-slides-container');
		var prev = opts.btnPrev = $(containerId + '-nav-prev-btn');
		var next = opts.btnNext = $(containerId + '-nav-next-btn');

		prev.observe('click', this.onPrevClickedAction);
		next.observe('click', this.onNextClickedAction);
	},

	initBlinds: function()
	{
		var blindTemplate = new Template('<div ' +
			'id="#{containerId}-blind-#{nb}" ' +
            'class="#{containerId}-blind" ' +
			'style="' +
				'position           : absolute;'     +
				'top                : 0px;'          +
				'left               : #{left}px;'    +
				'background-repeat  : no-repeat;'    +
				'background-position: #{pos}px 50%;' +
				'background-image   : url(#{url});'  +
				'background-color   : #{bg};'        +
				'width              : #{w}px;'       +
				'height             : #{h}px;"'      +
			'></div>');

		var opts = this.options;
		var n = opts.blindsNb;
		var W = opts.width;
		var w = Math.round(W / n);
		var h = opts.height;
		var p = opts.panel;

		p.absolutize();
		p.setStyle({
			width   : W  + 'px',
			height  : h + 'px',
			overflow: 'hidden',
			zIndex  : 100
		});

		for(var i=0, len = n; i<len; i++)
		{
			p.insert({
				bottom: blindTemplate.evaluate({
							containerId: opts.container.id,
							nb  : i,
							left: i*w,
							pos : -i*w,
							w   : w,
							h   : h,
							url : this.categories[this.selectedCategory].slides[0].src,
							bg  : 'transparent'
						})
				});
		}

		this.blinds = p.childElements();
	},

	initTabs: function()
	{
		this.categories.each(function(cat, pos){

			cat.tab.observe('click', this.onTabClickedAction);

		}.bind(this));
	},

	initCategories: function()
	{
		var categories = this.options.container.select('li.carrousel-category');

		categories.each(function(cat){

			var elements = cat.childElements();

			if(elements.length>1)
			{
				var category = {
					tab   : elements[0],
					slides: elements[1].select('img').invoke('hide')
				};

				this.categories.push(category);

				elements[1].hide();
			}
			else if(elements.length==1)
			{
				elements[0].addClassName('disabled');
				elements[0].href = 'javascript:void(0);';
			}

		}.bind(this));
	}
});

document.observe('dom:loaded', function(){

	new Carrousel({
		slideshow: true,
		delay    : 7.0
	});

	new UI.SlidePanel({
        container: 'slider',
        pageItems: 3
	});

});
