/* 

 * A workaround for IE issues in mootools 1.2.1

 * - Recreates FX.Scroll() but utilises 1.2.0's getPosition/getOffset routines.

 */

var SimpleSlideshow = new Class({
  options: {
    showControls: false,
    showDuration: 10000,
    showTOC: false,
    tocWidth: 20,
    tocClass: 'toc',
    tocActiveClass: 'toc-active'
  },
  Implements: [Options,Events],
  initialize: function(container,elements,options) {
    //settings
    this.container = $(container);
    this.elements = $$(elements);
    this.currentIndex = 0;
    this.interval = '';
    if(this.options.showTOC) this.toc = [];
    
    //assign
    this.elements.each(function(el,i){
      if(this.options.showTOC) {
        this.toc.push(new Element('a',{
          text: i+1,
          href: '#',
          'class': this.options.tocClass + '' + (i == 0 ? ' ' + this.options.tocActiveClass : ''),
          events: {
            click: function(e) {
              if(e) e.stop();
              this.stop();
              this.show(i);
            }.bind(this)
          },
          styles: {
            left: ((i + 1) * (this.options.tocWidth + 10))
          }
        }).inject(this.container));
      }
      if(i > 0) el.set('opacity',0);
    },this);
    
    //next,previous links
    if(this.options.showControls) {
      this.createControls();
      
    }
    //events
    this.container.addEvents({
      mouseenter: function() { this.stop(); }.bind(this),
      mouseleave: function() { this.start(); }.bind(this)
    });

  },
  show: function(to) {
    this.elements[this.currentIndex].fade('out');
    if(this.options.showTOC) this.toc[this.currentIndex].removeClass(this.options.tocActiveClass);
    this.elements[this.currentIndex = ($defined(to) ? to : (this.currentIndex < this.elements.length - 1 ? this.currentIndex+1 : 0))].fade('in');
    if(this.options.showTOC) this.toc[this.currentIndex].addClass(this.options.tocActiveClass);
  },
  start: function() {
    this.interval = this.show.bind(this).periodical(this.options.showDuration);
  },
  stop: function() {
    $clear(this.interval);
  },
  //"private"
  createControls: function() {
    var next = new Element('a',{
      href: '#',
      id: 'next',
      text: '>>',
      events: {
        click: function(e) {
          if(e) e.stop();
          this.stop(); 
          this.show();
        }.bind(this)
      }
    }).inject(this.container);
    var previous = new Element('a',{
      href: '#',
      id: 'previous',
      text: '<<',
      events: {
        click: function(e) {
          if(e) e.stop();
          this.stop(); 
          this.show(this.currentIndex != 0 ? this.currentIndex -1 : this.elements.length-1);
        }.bind(this)
      }
    }).inject(this.container);
  }
});

Fx.Scroll2 = new Class({

 

    'Extends': Fx.Scroll,

    'styleString': Element.getComputedStyle,

    'styleNumber': function(element, style) {

        return this.styleString(element, style).toInt() || 0;

    },

    'borderBox': function(element) {

        return this.styleString(element, '-moz-box-sizing') == 'border-box';

    },

    'topBorder': function(element) {

        return this.styleNumber(element, 'border-top-width');

    },

    'leftBorder': function(element) {

        return this.styleNumber(element, 'border-left-width');

    },

    'isBody': function(element) {

        return (/^(?:body|html)$/i).test(element.tagName);

    }, 

    'toElement': function(el) {

        var offset   = {x: 0, y: 0};

        var element  = $(el);

       

        if (this.isBody(element)) {

            return offset;

        }

        var scroll = element.getScrolls();

        while (element && !this.isBody(element)){

            offset.x += element.offsetLeft;

            offset.y += element.offsetTop;

           

            if (Browser.Engine.gecko){

                if (!this.borderBox(element)){

                    offset.x += this.leftBorder(element);

                    offset.y += this.topBorder(element);

                }

                var parent = element.parentNode;

                if (parent && this.styleString(parent, 'overflow') != 'visible'){

                    offset.x += this.leftBorder(parent);

                    offset.y += this.topBorder(parent);

                }

            } else if (Browser.Engine.trident || Browser.Engine.webkit){

                offset.x += this.leftBorder(element);

                offset.y += this.topBorder(element);

			}



            element = element.offsetParent;

            if (Browser.Engine.trident) {

                while (element && !element.currentStyle.hasLayout) {

                    element = element.offsetParent;

                }

            }

        }

        if (Browser.Engine.gecko && !this.borderBox(element)){

            offset.x -= this.leftBorder(element);

            offset.y -= this.topBorder(element);

        }

       

        var relative = this.element;

        var relativePosition = (relative && (relative = $(relative))) ? relative.getPosition() : {x: 0, y: 0};

        var position = {x: offset.x - scroll.x, y: offset.y - scroll.y};

       

        return this.start(position.x - relativePosition.x, position.y - relativePosition.y);

    }

});



var fmcScrollTo = new Class({

	Implements: Options,

	options: {

		container: document.body,

		slides: [],

		startIndex: 0,

		wrap: true,

		duration:1500,

		onShow: Class.empty //Mootools 1.2: $empty

	},

	initialize: function(options){

		//this.options = 

		this.setOptions(options);

		this.startIndex = this.options.startIndex;

		this.scroll = new Fx.Scroll2(this.options.container, {

			wait: false,

			duration: this.options.duration,

			offset: {'x': 0, 'y': 0}

			//transition: Fx.Transitions.Expo.easeOut

		});

	},

	scrollToEl: function(itemToScrollTo)

	{

		this.startIndex = itemToScrollTo;

		this.scroll.toElement(this.options.slides[itemToScrollTo]);

	}

});



var fadeImages = {

	actual:0,

	prev:false,

	on:false,

	init:function(options)

	{

		this.on=true;

		this.options = options;

		this.elms = options.elements;

		this.container = options.container;

		this.elms.each(function(el, index)

		{

			el.setStyles({'position':'absolute', opacity:0});

		});

		this.newImage = this.elms[this.actual]; 

		this.oldImage = this.elms[this.prev];

		this.fadeInOut();

		this.timer = this.fadeInOut.periodical(7000, this);

	}

	, fadeInOut:function()

	{

		this.newImage.set('tween', {duration: 'long'});

		this.newImage.tween('opacity', 1);

		if(this.oldImage)

		{

			this.oldImage.set('tween', {duration: 'long'});

			this.oldImage.fade(0);

		}

		this.prev = this.actual;

		this.actual++;

		if(this.actual ==this.elms.length)

		{

			this.actual = 0;

		}

		this.newImage = this.elms[this.actual];

		this.oldImage = this.elms[this.prev];

	}

};



var actus = {

	actus: [],

	active:null,

	listA:[],

	containerFx:null,

	singleFx:null,

	menuTween:null,

	container:null,

	single:new Element('div', {'class':'actu-single-c'}),

	closeBtn:new Element('a', {'href':'#','class':'closeActus', events:

	{

		'click':function(e)

		{

			if(e) e.stop();

			actus.close();

		}

	}}),

	shown:false,

	myHTMLRequest: null,

	actusSize:0,

	locked:false,

	init:function()

	{

		var that = this;

		this.actus=$$('.actu');

		this.container = $('actuSingle');

		this.contentContainer = $('actuSingleC');

		this.container.setStyle('left',-660);

		this.single.inject(this.contentContainer);

		this.containerFx = new Fx.Tween(this.container);

		this.singleFx = new Fx.Tween(this.single);

		this.menuTween = new Fx.Tween($('menu'));

		this.singleStylesFx = new Fx.Morph(this.single);

		this.listA = $$('.actu a');

		this.listA.each(function(el,index)

		{

			el.addEvent('click', function(e)

			{

				if(e) e.stop();

				if(that.locked == false)

				{

					that.locked = true;

					if(that.active == null) {

						that.active = index;

						that.showItem(this.href);

						that.actus[index].addClass('actu-active');

					}else if(that.active != index) {

						that.actus[index].addClass('actu-active');

						that.actus[that.active].removeClass('actu-active');

						that.showItem(this.href);

						that.active = index;

					}else if(that.active == index) {

						that.close();

					}

				}

			});

		});

		this.nav();

	},

	showItem:function(url)

	{

		//alert(this.shown);

		var that = this;

		//si une actu est déja montrée

		if(this.shown)

		{

			this.singleFx.start('opacity',0).chain(function()

			{

				that.req(url);

			});

		}else{

			this.shown = true;

			this.closeBtn.inject(this.container);

			//this.menuTween.start('top', 10-($('menu').getSize().y))

			this.singleFx.set('opacity',0);

			this.actusSize = $('site').getSize().y- $('actus').getSize().y - $('menu').getSize().y;

			this.containerFx.start('left',0);

			this.container.setStyles({'top': ($('menu').getSize().y), 'height':this.actusSize, 'display':'block'});

			this.req(url);

		}

	},

	req:function(url)

	{

		var that = this;

		myHTMLRequest = new Request({

			onRequest:function(){

				that.container.addClass('waiting');

				that.locked = true;

				//this.actus

			},

			onSuccess:function(responseText, responseXML)

			{

				that.single.set('html', responseText);

				//that.singleFx.set('margin-left',that.actus[that.active].getPosition().x);

				that.singleFx.set('opacity',1);

				that.singleFx.set('height',0);

				that.singleFx.set('overflow','hidden');

				that.singleFx.start('height',that.actusSize).chain(function()

				{

					that.locked = false;

					$$('#actuSingle .actu-content').each(function(el, index)

					{

						el.setStyle('height',that.actusSize - 150); 

						this.scr = new MakeScrollbar({content:el,ignoreMouse:false,id:'scrollbar0'+index, top:100});

						this.scr.changeSteps();

						that.showImagesOnTheLeft(el);

						Mediabox.scanPage();

						if(imgsC = that.container.getElements('.news-single-img')[0])

						{

							imgsC.setStyle('height', that.single.getSize().y - imgsC.getPosition().y + 80);

						}

					});

				});

				//that.singleFx.start('height', that.single

				that.container.removeClass('waiting');

				//that.singleStylesFx.start('margin-left', that.actus[that.active].getPosition().x +'px');

			}

		});

		myHTMLRequest.get(url);

	},

	close:function()

	{

		var that = this;

		this.closeBtn = this.closeBtn.dispose();

		this.actus[this.active].removeClass('actu-active');

		this.shown = false;

		this.locked = false;

		this.active = null;

		//this.menuTween.start('top', 0);

		this.singleFx.set('opacity',0);

		this.actusSize = $('site').getSize().y- $('actus').getSize().y - $('menu').getSize().y;

		this.containerFx.start('left',-660).chain(function(){

			that.container.setStyle('display','none');

		});

	},

	showImagesOnTheLeft:function(el)

	{

		var showPicsLinks = el.getElements('a.download');

		var original = null;

		var image = null;

		if(image = this.container.getElements('.actuPhotosLeft img')[0])

		{

			original = image.get('src');

		}

		showPicsLinks.each(function(link, id)

		{

			link.addEvents({

				'click':function(e)

				{

					e.stop();

				},

				'mouseenter':function(e)

				{

					if(original)

					{

						image.src= this.href;

					}else{

						image = new Element('img', {'src':this.href}).inject(el.getParent().getElement('.actuPhotosLeft'));

					}

				},

				'mouseleave':function(e)

				{

					if(original)

					{

						image.src= original;

					}else{

						image.dispose();

					}

				}

			});

		});

	},

	nav:function()

	{

		var that = this;

		$$('.actus-list').each(function(el, index)

		{

			var els = el.getElements('.actu');

			var len = els.length;

			if(len>0)

			{

				//largeur = len * 170 * 2;

				//$('actusWrapper').setStyle('width',largeur);

				var stepLength = Math.ceil(el.getElements('.actusListC')[0].getSize().x / els[0].getSize().x);

				//alert(stepLength);

				var scroller = new fmcScrollTo({

					slides: els,

					container: el.getElements('.actusListC')[0],

					duration:700

				});

				var steps = Math.ceil(len/stepLength); 

				var theStep = 0;

				var scrollable = false;

				var stepsArray = new Array();

				scrollable = true;

				that.checkBTNS(scroller.startIndex, steps, stepLength, el);

				el.getElements('.archives_nav_prev')[0].addEvent('click',function(e)

				{

					e.stop();

					if(scroller.startIndex != 0 && (scroller.startIndex-stepLength)>=0)

					{

						scroller.scrollToEl(scroller.startIndex-stepLength);

					}else{

						scroller.scrollToEl(0);

					}

					that.checkBTNS(scroller.startIndex, steps, stepLength, el);

				});

				el.getElements('.archives_nav_suiv')[0].addEvent('click',function(e)

				{

					e.stop();

					if(scroller.startIndex < len-1 && Math.ceil(scroller.startIndex + stepLength / stepLength) - 1 <= steps)

					{

						scroller.scrollToEl(scroller.startIndex+stepLength);

					}else{

						//alert('Last : '+ scroller.startIndex +' - '+ (stepLength*steps-stepLength));

						scroller.scrollToEl(stepLength*steps-stepLength);

					}

					that.checkBTNS(scroller.startIndex, steps, stepLength, el);

				});

			}else{

				el.getElements('.archives_nav_suiv')[0].setStyle('display','none');

				el.getElements('.archives_nav_prev')[0].setStyle('display','none');

			}

		});

	},

	checkBTNS:function (startIndex, steps, stepsLength, el)

	{

		var minus = false;

		var plus = false;

		//alert(Math.ceil((startIndex+stepsLength) / stepsLength));

		if(Math.ceil((startIndex+stepsLength) / stepsLength) == steps)

		{

			plus = false;

			el.getElements('.archives_nav_suiv')[0].addClass('disabled');

		}else{

			plus = true;

			el.getElements('.archives_nav_suiv')[0].removeClass('disabled');

		}

		if(startIndex == 0)

		{

			el.getElements('.archives_nav_prev')[0].addClass('disabled');

		}else{

			el.getElements('.archives_nav_prev')[0].removeClass('disabled');

		}

	}



};

var biographieHandler = {

	

	bio:null,

	iItems:null,

	iLinks:null,

	scrollbar:null,

	init:function(options)

	{

		var that = this;

		this.bio = options.bio;

		this.iItems = options.interviewsItems;

		this.iLinks = options.interviewsLinks;

		this.scrollbar = new MakeScrollbar({content:this.bio,ignoreMouse:false,id:'scrollbarBio', top:10,offsetX:-80});

		this.iLinks.each(function(el, index)

		{

			el.slide = new Fx.Slide(that.iItems[index]);

			el.slide.hide();

			el.addEvent('click', function(e)

			{

				if(e) e.stop();

				this.slide.toggle().chain(function()

				{

					that.scrollbar.changeSteps();

				});

			});

		});

		that.scrollbar.changeSteps() ;

	}

};



var MakeScrollbar = new Class({

	Implements: Options,

	content:null,

	ignoreMouse:false,

	id:'',

	top:100,

	scrollbar:null,

	handle:null,

	horizontal:false,

	slider:null,

	offsetX:0,

	initialize:function(options){

		if(options.content) { this.content = options.content; } else { return false; }

		if(options.ignoreMouse) this.ignoreMouse = options.ignoreMouse;

		(options.id) ? this.id = options.id : this.id = 'scrollbar_' + (100 * random());

		if(options.top) this.top = options.top;

		if(options.offsetX) this.offsetX = options.offsetX;

		var that = this;

		this.scrollbar = new Element('div',{id:this.id, 'class':'scrollbar-vert'}).inject(this.content, 'after');

		this.content.setStyles({ overflow:'hidden'});//width:(content.getSize().x-15),

		this.scrollbar.setStyles(

		{

			top:this.top,

			left:this.content.getPosition().x+ this.content.getSize().x+this.offsetX,

			height:this.content.getSize().y,

			position:'absolute'

		});

		this.handle = new Element('div',{'class':'handle-vert'}).inject(this.scrollbar);

		this.steps = this.countSteps();

		this.slider = new Slider(this.scrollbar, this.handle, {	

			steps: this.steps,

			mode: (this.horizontal?'horizontal':'vertical'),

			onChange: function(step){

				// Scrolls the content element in x or y direction.

				var x = (that.horizontal?step:0);

				var y = (that.horizontal?0:step);

				that.content.scrollTo(x,y);

			}

		}).set(0);

		if( !(this.ignoreMouse) ){

			// Scroll the content element when the mousewheel is used within the 

			// content or the scrollbar element.

			$$(this.content, this.scrollbar).addEvent('mousewheel', function(e){

				e = new Event(e).stop();

				var step = that.slider.step - e.wheel * 30;

				that.slider.set(step);

			});

		}

		// Stops the handle dragging process when the mouse leaves the document body.

		//$(document.body).addEvent('mouseleave',function(){that.slider.drag.stop()});

	},

	countSteps:function()

	{

		var nb = (this.horizontal?(this.content.getScrollSize().x - this.content.getSize().x):(this.content.getScrollSize().y - this.content.getSize().y))

		return nb;

	},

	changeSteps:function()

	{

		this.slider.steps = this.countSteps();

		if(this.countSteps() <= 0)

		{

			this.scrollbar.setStyle('visibility','hidden');

		}else{

			this.scrollbar.setStyle('visibility','visible');

		}

	}

});





var videos = {

	init:function()

	{

		this.c = $('videoC');

	},

	params: { 

		id: 'videoMc',

		width:600, 

		height: 490, 

		params: { wmode:'transparent' ,allowScriptAccess:'always' }, 

		vars: { width:600, height:490 }

	},

	showVideo:function(url)

	{

		this.init();

		if(this.c && url[0])

		{

			if(url[1]!= 'local')

			{

				var video= new Swiff(url[0], this.params);

				video.inject(this.c, top);

			}else{

				this.params.vars.movieUrl = url[0];

				var video= new Swiff(mainPath+"flash/v_player.swf", this.params);

				video.inject(this.c, top);

			}

			this.c.setStyle('display','block');

		}

	},

	hideVideo:function()

	{

		this.init();

		this.c.set('html','');

		this.c.setStyle('display','none');

	}

}



var encouragement = {

	init:function()

	{

		var that = this;

		this.c = $('encouragementForm');

		//this.log = new Element('div', {'class':'log'}).inject(this.c,'after');

		this.page = 'index.php?id=38';

		that.req (that.page, 'load');

	},

	req:function(url, type)

	{

		var that = this;

		switch(type)

		{

			case 'form' :

				break;

			case 'load' :

				var myRequest = new Request(

				{

					method: 'get', url:this.page, encoding:'iso-8859-1',

					onSuccess:function(responseText, responseXML)

					{

						that.c.set('html', responseText);

						that.setFormOn();

					},

					onFailure : function(t)

					{

						that.c.set('html', '<h3>Impossible de charger le formulaire !');

					}

				});

				myRequest.send();

				break;

		}

	},

	setFormOn: function()

	{

		var that = this;

		Mediabox.scanPage();

		that.form = that.c.getElements('form')[0];

		that.form.addEvent('submit', function(e) {

			e.stop();

			this.get('send').encoding ='iso-8859-1' ;

			this.set('send', {

				method:'post',

				onComplete: function(response) { 

					that.c.removeClass('ajax-loading');

					that.c.set('html', response);

					that.setFormOn();

				},

				encoding:'iso-8859-1',

				onRequest:function()

				{

					that.c.empty().addClass('ajax-loading');

				}

			});

			this.send();

			

		});

	},

	setFile:function()

	{

		

	}

}





var Autoslider = new Class ({

	Implements: Options,

	options:{

		wrap:null,

		c:null,

		itemsClass:'.partenaire',

		transitionTime:5000

	},

	initialize: function(options)

	{

		this.setOptions(options);

		this.wrap = this.options.wrap;

		this.c = this.options.c;

		this.slides = this.c.getElements(this.options.itemsClass);

		this.len = this.slides.length;

		this.autoPlay = null;

		//actus-wrapper

		if(this.len>0){

			this.wrap.setStyle('width', this.slides[0].getSize().x * this.len + 5);



			this.slideshow = new fmcScrollTo({container:this.c, slides:this.slides});

			this.stepLength = Math.ceil(this.c.getSize().x / this.slides[0].getSize().x);

			this.steps = Math.ceil(this.len / this.stepLength); 

			

			this.autoPlay = this.change.periodical(this.options.transitionTime, this);

		}

	}

	, change: function()

	{

		//alert('change' + ' - ' + this);

		if(this.slideshow.startIndex < this.len-1 && Math.ceil((this.slideshow.startIndex + this.stepLength) / this.stepLength) < this.steps)

		{

			this.slideshow.scrollToEl(this.slideshow.startIndex + this.stepLength);

		}else{

			this.slideshow.scrollToEl(0);

		}

	}

});






