/* ---------------------------------- */

/*
 *  TABLE DES MATIERES
 *  
 *  @Initialisation
 *  @Evenement
 *  @Initialisation auto
 *	@Shell
 *  @Scroll
 *  @Planche
 *  @MainNav
 *  @Counter
 *  @SiteScroll
 *  @Clavier
 *  @Methods
 *
 */
 
/* ---------------------------------- */


/* Initialisation */
jQuery(
  function ($) {
    $.Body = $('body');
    $.Window = $(window);
    $.Scroll = ($.browser.mozilla || $.browser.msie) ? $('html') : $.Body;
    $.Mobile = ($.Body.hasClass('webkit-mobile') || (navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i)) || (navigator.userAgent.match(/iPad/i))),
    $.Unsupported = $.Body.hasClass('unsupported-browser');
    $.Body.Keyboard();
    $('[data-controller]').Instantiate();

    if ($.browser.msie){
      //$(window).bind('load',function(){$('[data-canvasline]').Line();});
	}
    else{
      0;
	}
  } 
);
/* ---------------------------------- */


/* Evenements */
(function($) {
  $.Events = {
     SECTION_ENTER: 'sectionEnter',
     SCROLL_TO: 'scrollTo',
     SCROLL: 'windowScroll',
     SCROLL_ENTER: 'windowScrollEnter',
     SCROLL_LEAVE: 'windwScrollLeave',
     KEY_UP: 'keyUp',
     KEY_DOWN: 'keyDown',
     KEY_LEFT: 'keyLeft',
     KEY_RIGHT: 'keyRight',
     KEY_ESC: 'keyEsc',
     KEY_SPACE: 'keySpace'
  } // Events  
  $.Views = {} // Views 
})(jQuery);
/* ---------------------------------- */


/* Initialisation auto*/
(function($) {
  $.fn.Instantiate = function(settings) { 
    var config = {};
    if (settings) {$.extend(config, settings);}
      this.each(function() { 
          var $self = $(this),
              $controller = $self.attr('data-controller');             
          if ($self[$controller]){
            $self[$controller]();
		  }
              
      });  
  }
})(jQuery);
/* ---------------------------------- */



/* Shell */
(function($) {
  $.fn.SHELL = function(settings) {
    var config = {};
    if (settings) {$.extend(config, settings);}
      this.each(function() {});    
      return this;
  }
})(jQuery); 
/* ---------------------------------- */


/* Scroll */
(function($) {
  $.fn.Scrollable = function(settings) {
     var config = { threshold: -100, offset_scroll: 6, offset_intertia: .15 };
     if (settings) $.extend(config, settings);
     this.each(function() { 
        var $self = $(this),
        $id = $self.attr('id');
        config.threshold = 0
        
        if ($.Mobile || $.Unsupported) {  
          $self.css({backgroundAttachment:'scroll'});
        }
		else
			{
			$.Window
			  .bind('scroll',
				function(e){
				  if ( $.inview($self,{threshold:config.threshold}) ) {
					if (!$self.hasClass('_active')){
					  $self.addClass('_active');
					  if (settings.is_nav){
						$.Body.triggerHandler($.Events.SECTION_ENTER,$id);
					  }
					  $self.triggerHandler($.Events.SCROLL_ENTER);
					}
					_scroll_background();  
					$self.triggerHandler($.Events.SCROLL,$.distancefromfold($self,{threshold:config.threshold}) - config.threshold);
				}
				else
					{
					if ($self.hasClass('_active')){				
					  $self.removeClass('_active');
					  $self.triggerHandler($.Events.SCROLL_LEAVE);
					}
				  }
				});
			}
        
        function _scroll_background()
			{
          	var _x = '50% '
            var bpos = _x + (-($.distancefromfold($self,{threshold:config.threshold}) - config.threshold) * config.offset_intertia) + 'px';// ALGORYTHME BOuGE BACKGROUND
		  	$self.css({'backgroundPosition':bpos});
		}
              
     });
     
    return this;
     
  } //Planche
  

  $.fn.PlancheFixe = function() {
     this.each(function() { 
        var $self = $(this),
            $id = $self.attr('id'),
            _threshold = -200;
        $self
          .Scrollable({threshold: _threshold,is_nav:true});
            
     });
    return this;
  } //BG fixe
  
  $.fn.PlancheMove = function() {
     this.each(function() { 
        var $self = $(this),
            $header = $self.find('header'),
            $bg = $self.find('.bg'),
            $h1 = $self.find('h1'),
            $h2 = $self.find('h2'),
            $id = $self.attr('id'),
            $img = $self.find('img'),
            _threshold = -200;
        
        $self
          .Scrollable({threshold: _threshold,is_nav:true})
          .bind($.Events.SCROLL,on_scroll)
          .bind($.Events.SCROLL_ENTER,on_scroll_enter)
          .bind($.Events.SCROLL_LEAVE,on_scroll_leave);
          
        function on_scroll(e,distance)
			{
			var bpos = '50% ' + ($.Window.height()/2.5-distance/3) + 'px';
        	$bg.css({'backgroundPosition':bpos});
        }
        
        function on_scroll_enter(e) {}
        
        function on_scroll_leave(e) {}     
     });
     
    return this;
  } //BG Move
})(jQuery);


/* ---------------------------------- */

/* MainNav */

(function($) {
   $.fn.MainNav = function() {
     this.each(function() { 
        var $self = $(this).children('div#contientMenu'),
        $ul = $('<ul/>').appendTo($self),
        $sections = $('[data-nav]'),
        _sections = new Array(),
        $navs = new Array(),
        _active = 0;
            
       if (!$.Mobile && !$.Unsupported) { 
        $sections.each(
          function(i){
            _sections.push($(this))
            $('<li/>').appendTo($ul).DotNav({id:$(this).attr('id'),name:$(this).attr('data-nav')});
          })
		 $('<li/>').appendTo($ul).DotNav({id:'story-footer',name:'Contact'});
        }
        
        $.Body
          .bind($.Events.SECTION_ENTER,
            function(e,id)
				{
              	$sections.each(
                function(i){
                  if ($(this).attr('id')==id){
                    _active = i;
				  }
              	})
            })
          .bind($.Events.KEY_RIGHT,
            function(e){
              _active++;
              if (_active>$sections.length-1){
                _active=$sections.length-1;
			  }
              _seek();
          })
          .bind($.Events.KEY_LEFT,
            function(e){
              _active--;
              if (_active<0){
                _active=0;
			  }
              _seek()  
          })
          
          function _seek() {
            $.Body.triggerHandler($.Events.SCROLL_TO,_sections[_active].attr('id'));
          } 
     });
     
	$('<b></b>').prependTo('div#contientMenu ul'); //on place notre petit rollover texte
	$('div#contientMenu ul li:eq(1), div#contientMenu ul li:eq(2), div#contientMenu ul li:eq(3)').hide(); //on cache les 3 menu generer 
    return this;
     
  } // Main Nav
  
  $.fn.DotNav = function(settings) {
    var config = {};
    if (settings) $.extend(config, settings); 
     this.each(function()
		{ 
        var $self = $(this),
        $a = $('<a/>'),
        $h1 = $('<h1/>').appendTo($self),
        $span = $('<span/>').html(config.name).appendTo($h1),
        $id = config.id;
		$title =settings.name;
			
		$a
			.attr('href',"#/"+config.name.split(' ').join('_'))
			.attr('rel',$title)
            .html($id)
            .appendTo($self)
            .bind('click',
                function(e){
                  $.Body.triggerHandler($.Events.SCROLL_TO,$id)
                  e.preventDefault();
                })
            
            $self.attr('data-id',$id);
			      
        $a
			.html('<img src="img/'+$id+'.gif" />')
          	.mouseenter(
            	function(e) {
					$('div#contientMenu ul b').html($(this).attr('rel'));
            	})
          	.bind('mouseleave',
            	function(e) {
              		$('div#contientMenu ul b').html('');
            	});
        
          
        $.Body
          .bind($.Events.SECTION_ENTER,
            function(e,id){
              if (id==$id)
                $self.addClass('active')
              else
                $self.removeClass('active')
            });
     });
     
    return this;
     
  } // DotNav 
})(jQuery);
/* ---------------------------------- */

/* SiteScroll */
(function($) {

  
   $.fn.SiteScroll = function() {
   
     this.each(function() { 
      
        var $self = $(this);
            
        $.Body
          .bind($.Events.SCROLL_TO,
            function(e,id){
            
              var $element = $('#'+id),
                  $header = $element.find('header'),
                  _align = $element.attr('data-align'),
                  _offset = $element.attr('data-scrolloffset') ? parseInt($element.attr('data-scrolloffset')) : 50,
                  _top = $element.offset().top;
              if ($header.length>0 && _align!="top") { 
                  _top = $header.offset().top  + $header.height()/2 - $.Window.height()/2;
                  if (_top > $header.offset().top){
                    _top = $header.offset().top - 50;
				  }
              }
              
              if (_align=="center" && $element.height()>$.Window.height()) {
                _top = $element.offset().top + ($element.height()-$.Window.height())/2;
              
              }
              
              $.Scroll
                .stop()
                .animate(
                  { 'scrollTop': _top },
                  800,
                  'easeInOutQuart'
                )
            });    
     });
     
    return this; 
  }  
})(jQuery);


/* ---------------------------------- */

/* Clavier */

(function($) {


   $.fn.Keyboard = function(settings) {
     
    var config = {};
 
    if (settings) $.extend(config, settings);
  
      this.each(function() { 
      
        var $self = $(this);
      
        $(document)
        .bind('keydown',on_keydown);
        
        function on_keydown(e) {
			
			if ($('li.active').attr('data-id')!='story-footer'){
          
    		  var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;
    		  
          switch(key) {

             
             case 27: //escape

              $.Body.triggerHandler($.Events.KEY_ESC);
                        
             break;
             
             case 32: //space

              $.Body.triggerHandler($.Events.KEY_SPACE);
                        
             break;
             
             case 38: //top
              
              $.Body.triggerHandler($.Events.KEY_LEFT);
                        
             break;
           
             case 39: //right

              $.Body.triggerHandler($.Events.KEY_RIGHT);
              e.preventDefault();
              
             break;
             
             case 40: ///bottom
            
              $.Body.triggerHandler($.Events.KEY_RIGHT);
                        
             break;
              
             case 37: //left
             
              $.Body.triggerHandler($.Events.KEY_LEFT);
                        
             break;
             
             
          }//switch
	  } //if
        }//keydown
  
      }); 
      
      return this;
    
  } 
  

})(jQuery);


/* ---------------------------------- */

/* Methods */

(function($) {


    $.distancefromfold = function($element, settings) {
        if (settings.container === undefined || settings.container === window) {
            var fold = $(window).height() + $(window).scrollTop();
        } else {
            var fold = $(settings.container).offset().top + $(settings.container).height();
        }
        return (fold + settings.threshold) - $element.offset().top ;
    };
    
    $.belowthefold = function($element, settings) {
        if (settings.container === undefined || settings.container === window) {
            var fold = $(window).height() + $(window).scrollTop();
        } else {
            var fold = $(settings.container).offset().top + $(settings.container).height();
        }
        return fold <= $element.offset().top - settings.threshold;
    };
    
    $.rightoffold = function($element, settings) {
        if (settings.container === undefined || settings.container === window) {
            var fold = $(window).width() + $(window).scrollLeft();
        } else {
            var fold = $(settings.container).offset().left + $(settings.container).width();
        }
        return fold <= $element.offset().left - settings.threshold;
    };
        
    $.abovethetop = function($element, settings) {
        if (settings.container === undefined || settings.container === window) {
            var fold = $(window).scrollTop();
        } else {
            var fold = $(settings.container).offset().top;
        }
        return fold >= $element.offset().top + settings.threshold  + $element.height();
    };
    
    $.leftofbegin = function($element, settings) {
        if (settings.container === undefined || settings.container === window) {
            var fold = $(window).scrollLeft();
        } else {
            var fold = $(settings.container).offset().left;
        }
        return fold >= $element.offset().left + settings.threshold + $element.width();
    };
    
    $.inview = function($element, settings) {
        return ($.abovethetop($element,settings)!=true && $.belowthefold($element,settings)!=true);
    };


    $.extend($.expr[':'], {
        "below-the-fold" : "$.belowthefold(a, {threshold : 0, container: window})",
        "above-the-fold" : "!$.belowthefold(a, {threshold : 0, container: window})",
        "right-of-fold"  : "$.rightoffold(a, {threshold : 0, container: window})",
        "left-of-fold"   : "!$.rightoffold(a, {threshold : 0, container: window})"
    });
    
})(jQuery);    









 
function limit_carac_max_ligne(f,texte)
{
	var tableau_result=new Array();
	var nl="\r\n";
	var max_carac=85; //nombre de caractère maximum par ligne
	var max_ligne=3;//nombre de ligne maximum
	var nb_ligne=0;
	var chntmp="";
	var Maxchn="";
	var result="";
	var chaine="";
	//chaque ligne du tableau represente une ligne délimité par un \r\n
	var tableau=texte.split(nl);
	var tableau_test=new Array();
 
	//pour chaque ligne 
	for(var i=0;i<tableau.length;i++)
	{
		//on recupère la ligne
		chntmp=tableau[i];
		//si une ligne utilise X lignes du textarea
		while (chntmp.length>max_carac)
		{
			//on recupère les max premiers caractères
			Maxchn=chntmp.substring(0,max_carac);
			//on récupère le reste de la chaine
			chntmp=chntmp.substring(max_carac,chntmp.length);
			tableau_result.push(Maxchn);
		}
		tableau_result.push(chntmp);
	}
//////////////////////////////////////////////////////////////////////////////////////////////////////////	
	//on parcourt tableau_result pour réafficher le tableau 
	//Problème d'ajout des retour à la ligne pour le réaffichage
	//Il n'y a saut à la ligne que si pour tableau_result[i], il existe un tableau_result[i+1]
	//on connait la taille de tableau_result : tableau_result.length
	for (var i=0;i<=tableau_result.length-1;i++)
	{
		// si on est à la fin du tableau on ne rajoute pas de \n
		if (i<tableau_result.length-1)
		{
			result+=tableau_result[i]+"\r\n";
		}
		else
		{
			result+=tableau_result[i];
		}
	}
	//////////////////////////////////////////////////////////////////////////////////////////////////////////
 
	//////////////////////////////////////////////////////////////////////////////////////////////////////////	
	//Limitation du nombre de ligne
	nbligne=compte_ligne(result);
	tableau=result.split(nl);
	if (nbligne>max_ligne-1)
	{
		for(var i=0;i<max_ligne;i++)
		{
			if (i<max_ligne-1)
			{
				chaine+=tableau[i]+'\r\n';
			}
			else
			{
				chaine+=tableau[i];
			}
		}
		f.value=chaine;
	}
	else
	{
	        tableau_test=result.split(nl);
	        f.value=result;
	}
}
