CaptainDash

//--------------------------------------------------------------------------
//  APPLICATION
//--------------------------------------------------------------------------

// begin:script-wrapper
(function($) {
  // begin:startup
  $(document).bind('ready', function() {

    //-------------------------------------
    //  DOM ELEMENTS
    //-------------------------------------

    var $window = $(window),
      $html = $('html'),
      $body = $('body');

    //-------------------------------------
    //  SETTINGS
    //-------------------------------------

    var settings = {
      page_home: {
        fullscreenLimit: 800
      },
      page_solve: {
        fullscreenLimit: 800
      },
      page_tryus: {
        fullscreenLimit: 860
      },
      page_404: {
        fullscreenLimit: 500
      }
    };

    //-------------------------------------
    //  #NAV
    //-------------------------------------

    // duplique les labels de la nav pour le rollover
    $('#nav a .label').each(function(i, e) {
      var out = $(this).wrap('<span></span>').parent();
      out.clone().addClass('over').insertBefore(out.addClass('out'));
    });

    //-------------------------------------
    //  WINDOW RESIZE
    //-------------------------------------

    $window
    // debouncer
    .resize(function(e) {
      var w = $window.width(),
        h = $window.height();
      if (w != window.__previousWidth || h != window.__previousHeight || window.__sizeInvalidated) {
        window.__previousWidth = w;
        window.__previousHeight = h;
        window.__sizeInvalidated = false;
        return;
      }
      e.stopImmediatePropagation();
    }).resize(function(e) {
      updateBehavior($html);
    })
    // déclanche l'évènement manuellement pour l'initialisation
    .resize();

    function updateBehavior($wrap) {
      // hauteur de la fenêtre
      var windowHeight = $window.height();

      if ($wrap.hasClass('home')) {
        $wrap.toggleClass('fullscreen', windowHeight > settings.page_home.fullscreenLimit);
      } else if ($wrap.hasClass('what-we-solve')) {
        if ($window.height() > settings.page_solve.fullscreenLimit) {
          $wrap.toggleClass('fullscreen', true);
          $wrap.find('#main .content .section').css('height', windowHeight - 290);
        } else {
          $wrap.toggleClass('fullscreen', false);
          $wrap.find('#main .content .section').css('height', '');
        }
      }
      // pour les sections du site
      else if ($wrap.hasClass('site-section')) {
        // page d'accueil des sections
        if ($wrap.hasClass('front')) {
          // le fullscreen si on dépasse la hauteur de la nav
          $wrap.toggleClass('fullscreen', $window.height() > $wrap.find('#subnav ul').height() + 295 + 100);
        }
        // page intérieures
        else if ($wrap.hasClass('inner')) {
          // le fullscreen si on dépasse la hauteur de la nav ou du contenu
          $wrap.find('#subnav').toggleClass('fullheight', $wrap.find('#subnav ul').height() + 195 < $wrap.find('#content').height());
        }
      }
      // pour la page...
      else if ($wrap.hasClass('try-us')) {
        $wrap.toggleClass('fullscreen', $window.height() > settings.page_tryus.fullscreenLimit);
      }
      // pour la page 404
      else if ($wrap.hasClass('not-found')) {
        $wrap.toggleClass('fullscreen', $window.height() > settings.page_404.fullscreenLimit);
      }
    }

    //-------------------------------------
    //  WHAT WE SOLVE
    //-------------------------------------

    // rollover sur le logo
    $('.what-we-solve #logo').live('mouseenter', function(e) {
      $(this).parent().addClass('over');
    });
    $('.what-we-solve #logo').live('mouseleave', function(e) {
      $(this).parent().removeClass('over');
    });

    // scroll manuel au clic sur les flèches
    $('html.what-we-solve #main .bar .prev').live('click', function(e) {
      $('html,body').animate({
        scrollTop: solve_getPrevSection()
      }, 650, 'easeInOutQuad');
    });
    $('html.what-we-solve #main .bar .next').live('click', function(e) {
      $('html,body').animate({
        scrollTop: solve_getNextSection()
      }, 650, 'easeInOutQuad');
    });

    function solve_getNextSection() {
      var $sections = $('html.what-we-solve #main .content .section')
      sectionCount = $sections.length,
        sectionHeight = $sections.height(),
        scrollTop = $window.scrollTop(),
        currentSection = Math.round(scrollTop / sectionHeight),
        targetSection = currentSection + 1;
      return (targetSection >= sectionCount ? currentSection : targetSection) * sectionHeight;
    }

    function solve_getPrevSection() {
      var $sections = $('html.what-we-solve #main .content .section')
      sectionCount = $sections.length,
        sectionHeight = $sections.height(),
        scrollTop = $window.scrollTop(),
        currentSection = Math.round(scrollTop / sectionHeight),
        targetSection = currentSection - 1;
      return targetSection < 0 ? 0 : targetSection * sectionHeight;
    }

    //-------------------------------------
    //  FORM TRY-US
    //-------------------------------------

    $('form#try-us').live('submit', function(e) {
      var $form = $(this),
        $email = $form.find('#email')
        // suppression des classes
        .removeClass('email-error').removeClass('send-error').removeClass('sended');

      // affichage du chargement
      $body.addClass('loading-content');

      // envoi du formulaire en ajax
      $form.ajaxSubmit({
        data: {
          mode: 'ajax'
        },
        success: function(response, status, xhr, form) {
          // fin du chargement
          $body.removeClass('loading-content');
          // traitement du résultat
          if (response == 'email-sent') {
            $email.addClass('email-sent').attr('value', $email.attr('data-email-sent'));
          } else if (response == 'email-error') {
            $email.addClass('email-error');
          } else {
            $email.addClass('send-error').attr('value', $email.attr('data-send-error'));
          }
        }
      });
      e.preventDefault();
      return false;
    });

    //-------------------------------------
    //  FORM CONTACT
    //-------------------------------------

    $('form#contact').live('submit', function(e) {
      var $form = $(this),
        $email = $form.find('#email')
        // suppression des classes
        .removeClass('email-error').removeClass('send-error').removeClass('sended'),
        $message = $form.find('#message')
        // suppression des classes
        .removeClass('message-error').removeClass('send-error').removeClass('sended');

      // affichage du chargement
      $body.addClass('loading-content');

      // envoi du formulaire en ajax
      $form.ajaxSubmit({
        data: {
          mode: 'ajax'
        },
        success: function(response, status, xhr, form) {
          // fin du chargement
          $body.removeClass('loading-content');

          // traitement du résultat
          if (response == 'email-sent') {
            $email.addClass('email-sent').attr('value', $email.attr('data-email-sent'));

            $message.addClass('email-sent').attr('value', '');
          } else if (response == 'email-error') {
            $email.addClass('email-error');
          } else if (response == 'message-error') {
            $message.addClass('message-error');
          } else {
            $email.addClass('send-error').attr('value', $email.attr('data-send-error'));

            $message.addClass('send-error');
          }
        }
      });
      e.preventDefault();
      return false;
    });

    //-------------------------------------
    //  FORM FIELD#MESSAGE
    //-------------------------------------

    $('form #message').live('focus', function(e) {
      var $this = $(this)
      // suppression de la classe du status
      .removeClass('message-error').removeClass('send-error').removeClass('email-sent');
      // quand le champ est vide on remet la valeur par défaut
      if (this.value == '') {
        this.value = $(this).attr('data-default');
      }
    }).live('blur', function(e) {
      // quand le champ est vide on remet la valeur par défaut
      if (this.value == '') {
        this.value = $(this).attr('data-default');
      }
    });

    //-------------------------------------
    //  FORM FIELD#EMAIL
    //-------------------------------------

    $('form #email').live('focus', function(e) {
      var $this = $(this)
      // suppression de la classe du status
      .removeClass('email-error').removeClass('send-error').removeClass('email-sent'),
        // récupération de la valeur actuelle
        value = this.value,
        // récupération des valeurs par défaut
        value_default = $this.attr('data-default'),
        value_emailSent = $this.attr('data-email-sent'),
        value_sendError = $this.attr('data-send-error');
      // on vide le champ s'il s'agit d'un des valeurs
      if (value == value_default || value == value_emailSent || value == value_sendError) {
        this.value = '';
      }
    }).live('blur', function(e) {
      // quand le champ est vide on remet la valeur par défaut
      if (this.value == '') {
        this.value = $(this).attr('data-default');
      }
    });

    var currentPath = new Array('home'),
      currentPathString = '',
      currentIndex = 0,
      preventDynamicNavigation = false;

    //-------------------------------------
    //  UTIL
    //-------------------------------------

    function getPathFromUrl(url) {
      var base = $body.attr('data-root'),
        reg1 = new RegExp('^' + base + '/?([^#]*)'),
        path = url.match(reg1)[1],
        pathElements = [],
        pathLevel = 1;
      if (path != '') {
        var reg2 = new RegExp('([^/]+)', 'g'),
          pathElements = path.match(reg2),
          pathLevel = pathElements.length,
          path = pathElements.join('/');
      }
      return path;
    }

    //-------------------------------------
    //  NAVIGATION OVERRIDE
    //-------------------------------------

    if (!$html.hasClass('not-found')) $('#nav a,#logo a,#subnav a').live('click', function(e) {
      // si on est déjà en train de charger une page
      if (preventDynamicNavigation) {
        e.preventDefault();
        return false;
      }

      // récupération du path
      var path = getPathFromUrl($(this).attr('href'));

      function setHash() {
        // définition de l'url
        window.location.hash = path;
        // google analytics
        _gaq.push(['_trackPageview', '/' + path]);
      }

      var scrollTop = $window.scrollTop();
      if (scrollTop > 0) {
        $('body,html').stop().animate({
          scrollTop: 0
        }, 100 + scrollTop * 0.8, 'easeInOutExpo', setHash);
      } else {
        setHash();
      }

      // empèche l'action par défaut (click)
      e.preventDefault();
      return false;
    });

    //-------------------------------------
    //  WINDOW :: HASH CHANGE
    //-------------------------------------

    // écoute le changement du hash de la page
    $(window).bind('hashchange', windowHashChange);

    function windowHashChange(e) {
      // si on est déjà en train de charger une page
      if (preventDynamicNavigation) {
        if (e) e.preventDefault();
        return;
      }

      // traitement des informations
      var base = $body.attr('data-root'),
        hash = window.location.hash.replace('#', ''),
        path = hash.split('/'),
        pathLevel = path.length;

      // sélection/déselection des items
      $html.find('#nav li.current-item):has(a[href!="' + base + path[0] + '"])').removeClass('current-item');
      $html.find('#nav li:not(.current-item):has(a[href="' + base + path[0] + '"])').addClass('current-item');
      $html.find('#subnav li.current-item):has(a[href!="' + base + hash + '"])').removeClass('current-item');
      $html.find('#subnav li:not(.current-item):has(a[href="' + base + hash + '"])').addClass('current-item');

      // pour l'accueil
      if (hash == '') {
        loadRootContent(base, 'home');
      }
      // pour les pages de niveau 1
      else if (pathLevel == 1) {
        if (currentPath.length == 2 && currentPath[0] == path[0]) {
          loadSubContent(base + hash, path[0]);
        } else {
          loadRootContent(base + hash, path[0]);
        }
      }
      // pour les page de niveau 2
      else if (pathLevel == 2) {
        if (currentPath[0] != path[0]) {
          loadRootContent(base + hash, path[0]);
        } else {
          loadSubContent(base + hash, path[0]);
        }
      }

      // définition du current path
      currentPath = path;

      // empèche le scroll vers #hash
      if (e) e.preventDefault();
      return false;
    }

    //-------------------------------------
    //  LOAD ROOT CONTENT
    //-------------------------------------

    function loadSubContent(url, nextPageClass) {
      // pour éviter de charger deux pages en même temps
      preventDynamicNavigation = true;
      // affiche le chargement
      $body.addClass('loading-content');

      var $oldContent = $html.find('#content'),
        $newWrap = $('<div/>').hide().load(url + ' #content,#hidden-title', function(r, t, x) {
          // en cas d'erreur
          if (t == 'error') {
            currentPath = new Array('not-found');
            currentPathString = 'not-found';
            loadRootContent($('body').attr('data-root') + 404, currentPathString);
            return;
          }

          // fin du chargement
          $body.removeClass('loading-content');

          // titre de la page
          window.document.title = $(this).find('#hidden-title').remove().text();

          var $newContent = $newWrap.find('#content').hide();
          $oldContent.fadeOut(150, 'easeInOutExpo', function() {
            $html.removeClass('fullscreen').removeClass('inner').removeClass('front');

            // définition des autres classes
            if ($html.find('#subnav li.current-item').length > 0) {
              $html.addClass('inner');
            } else {
              $html.addClass('front');
            }

            $oldContent.replaceWith($newWrap.find('#content').fadeIn());

            updateBehavior($html);

            // pour éviter de charger deux pages en même temps
            preventDynamicNavigation = false;
          });
        });
    }

    //-------------------------------------
    //  LOAD ROOT CONTENT
    //-------------------------------------

    function loadRootContent(url, nextPageClass) {
      // pour éviter de charger deux pages en même temps
      preventDynamicNavigation = true;
      // affiche le chargement
      $body.addClass('loading-content');

      // direction de l'animation
      var direction = 'rtl',
        nextIndex = 0;
      $('#nav a').each(function(i, e) {
        if ($(this).attr('href') == url) nextIndex = i + 1;
      });
      if (nextIndex < currentIndex) direction = 'ltr';

      // création de l'élément temporaire pour le chargement
      var $newWrap = $('<div/>').hide().load(url + ' #main,#footer,#hidden-title', function(r, t, x) {
        // en cas d'erreur
        if (t == 'error') {
          currentPath = new Array('not-found');
          currentPathString = 'not-found';
          loadRootContent($('body').attr('data-root') + 404, currentPathString);
          return;
        }

        // titre de la page
        window.document.title = $(this).find('#hidden-title').remove().text();

        $body.removeClass('loading-content').css({
          'overflow-x': 'hidden'
        });

        currentIndex = nextIndex;

        /////////////////////////////////////////////////////////////
        // OLD WRAP
        /////////////////////////////////////////////////////////////

        var $oldWrap = $('<div/>');

        $oldWrap.insertBefore('#main').addClass($html.attr('class')).css({
          'width': $body.width() + 'px',
          'height': $window.height() + 'px',
          'position': 'absolute',
          'top': $oldWrap.hasClass('fullscreen') ? '0' : '100px',
          'left': '0',
          'overflow': 'hidden'
        }).append($html.find('#main,#footer'));

        /////////////////////////////////////////////////////////////

        $html.removeClass();

        /////////////////////////////////////////////////////////////
        // NEW WRAP
        /////////////////////////////////////////////////////////////

        // ajout de la classe de la page
        $newWrap.insertAfter($oldWrap).addClass(nextPageClass);
        // définition des autres classes
        if ($newWrap.find('#subnav').length > 0) {
          $newWrap.addClass('site-section');
          if ($newWrap.find('#subnav li.current-item').length > 0) {
            $newWrap.addClass('inner');
          } else {
            $newWrap.addClass('front');
          }
        }

        // configuration des styles
        $newWrap.css({
          'width': $body.width() + 'px',
          'position': 'absolute',
          'top': '100px',
          'left': '0',
          'overflow': 'hidden',
          'margin-left': direction == 'rtl' ? '100%' : '-100%'
        }).show();

        // mise à jour du comportement
        updateBehavior($newWrap);

        // si il a la classe fullscreen ou fullheight
        if ($newWrap.hasClass('fullscreen')) {
          $newWrap.css({
            'top': '0',
            //'width':$body.width()+'px',
            'height': $window.height() + 'px',
          });
        }

        /////////////////////////////////////////////////////////////
        // SUPER WRAP
        /////////////////////////////////////////////////////////////

        var $superWrap = $('<div/>');
        $superWrap.css({
          'width': '100%',
          'height': $window.height() + 'px',
          'position': 'absolute',
          'top': '0',
          'left': '0',
          'overflow': 'hidden'
        }).insertBefore($oldWrap).append($oldWrap).append($newWrap);

        /////////////////////////////////////////////////////////////
        // ANIMATION
        /////////////////////////////////////////////////////////////

        // ancien contenu
        $oldWrap.animate({
          'margin-left': direction == 'rtl' ? '-100%' : '100%'
        }, 650, 'easeInOutQuad', function() {
          $oldWrap.remove();
        });

        // nouveau contenu
        $newWrap.animate({
          'margin-left': '0%'
        }, 650, 'easeInOutQuad', function() {
          $html.addClass($newWrap.attr('class'));
          $newWrap.unwrap();
          $superWrap.remove();
          $newWrap.find('#main,#footer').unwrap();
          $newWrap.remove();
          // fin du chargement
          $body.css({
            'overflow-x': '',
          });
          window.__sizeInvalidated = true;
          $window.resize();

          preventDynamicNavigation = false;
        });

      });
    }

    //-------------------------------------
    //  REDIRECTION
    //-------------------------------------

    var hash = window.location.hash,
      href = window.location.href,
      root = $body.attr('data-root');
    if ($html.hasClass('not-found')) {
      // do nothing
    } else if (href.replace(hash, '') != root) {
      window.location.href = $body.attr('data-root') + "#" + getPathFromUrl(href);
    } else if (hash != '') {
      windowHashChange();
    }

  }); // end:startup
})(jQuery); // end:script-wrapper


$(document).ready(function() {
  $("div.content > .readmoreLink").live('click', function() {
    if ($(this).next("div.more:visible").length != 0) {
      $(this).next("div.more").slideUp("normal", function() {
        $(this).parent().removeClass("open")
      });
    } else {
      $("div.more").slideUp("normal", function() {
        $(this).parent().removeClass("open")
      });
      $(this).next("div.more").slideDown("normal", function() {
        $(this).parent().addClass("open")
      });
    }
    return false;
  });
});
//--------------------------------------------------------------------------
//  APPLICATION
//--------------------------------------------------------------------------

// begin:script-wrapper
(function($){
// begin:startup
$(document).bind('ready',function(){
	
	//-------------------------------------
	//  DOM ELEMENTS
	//-------------------------------------
	
	var $window = $(window),
		$html = $('html'),
		$body = $('body');
	
	//-------------------------------------
	//  SETTINGS
	//-------------------------------------
	
	var settings = {
		page_home : {
			fullscreenLimit : 800
		},
		page_solve : {
			fullscreenLimit : 800
		},
		page_tryus : {
			fullscreenLimit : 860
		},
		page_404 : {
			fullscreenLimit : 500
		}
	};
	
	//-------------------------------------
	//  #NAV
	//-------------------------------------
	
	// duplique les labels de la nav pour le rollover
	$('#nav a .label').each(function(i,e){
		var out = $(this).wrap('<span></span>').parent();
		out.clone().addClass('over').insertBefore(out.addClass('out'));
	});
	
	//-------------------------------------
	//  WINDOW RESIZE
	//-------------------------------------
	
	$window
	// debouncer
	.resize(function(e)
	{
		var w = $window.width(),
			h = $window.height();
		if (w != window.__previousWidth
		 || h != window.__previousHeight
		 || window.__sizeInvalidated) {
			window.__previousWidth = w;
			window.__previousHeight = h;
			window.__sizeInvalidated = false;
			return;
		}
		e.stopImmediatePropagation();
	})
	.resize(function(e)
	{
		updateBehavior($html);
	})
	// déclanche l'évènement manuellement pour l'initialisation
	.resize();
	
	function updateBehavior($wrap)
	{
		// hauteur de la fenêtre
		var windowHeight = $window.height();
		
		if ($wrap.hasClass('home')) {
			$wrap.toggleClass('fullscreen', windowHeight > settings.page_home.fullscreenLimit);
		}
		else
		if ($wrap.hasClass('what-we-solve')) {
			if ($window.height() > settings.page_solve.fullscreenLimit) {
				$wrap.toggleClass('fullscreen', true);
				$wrap.find('#main .content .section').css('height', windowHeight - 290);
			} else {
				$wrap.toggleClass('fullscreen', false);
				$wrap.find('#main .content .section').css('height', '');
			}
		}
		// pour les sections du site
		else if ($wrap.hasClass('site-section'))
		{
			// page d'accueil des sections
			if ($wrap.hasClass('front')) {
				// le fullscreen si on dépasse la hauteur de la nav
				$wrap.toggleClass('fullscreen', $window.height() > $wrap.find('#subnav ul').height() + 295 + 100);
			}
			// page intérieures
			else if ($wrap.hasClass('inner')) {
				// le fullscreen si on dépasse la hauteur de la nav ou du contenu
				$wrap.find('#subnav').toggleClass('fullheight', $wrap.find('#subnav ul').height() + 195 < $wrap.find('#content').height());
			}
		}
		// pour la page...
		else if ($wrap.hasClass('try-us'))
		{
			$wrap.toggleClass('fullscreen', $window.height() > settings.page_tryus.fullscreenLimit);
		}
		// pour la page 404
		else if ($wrap.hasClass('not-found'))
		{
			$wrap.toggleClass('fullscreen', $window.height() > settings.page_404.fullscreenLimit);
		}
	}
	
	//-------------------------------------
	//  WHAT WE SOLVE
	//-------------------------------------
	
	// rollover sur le logo
	$('.what-we-solve #logo').live('mouseenter',function(e){
		$(this).parent().addClass('over');
	});
	$('.what-we-solve #logo').live('mouseleave',function(e){
		$(this).parent().removeClass('over');
	});
	
	// scroll manuel au clic sur les flèches
	$('html.what-we-solve #main .bar .prev').live('click',function(e){
		$('html,body').animate({scrollTop:solve_getPrevSection()},650,'easeInOutQuad');
	});
	$('html.what-we-solve #main .bar .next').live('click',function(e){
		$('html,body').animate({scrollTop:solve_getNextSection()},650,'easeInOutQuad');
	});
		
	function solve_getNextSection(){
		var $sections = $('html.what-we-solve #main .content .section')
			sectionCount = $sections.length,
			sectionHeight = $sections.height(),
			scrollTop = $window.scrollTop(),
			currentSection = Math.round(scrollTop / sectionHeight),
			targetSection = currentSection + 1;
		return (targetSection >= sectionCount ? currentSection : targetSection) * sectionHeight;
	}
	function solve_getPrevSection(){
		var $sections = $('html.what-we-solve #main .content .section')
			sectionCount = $sections.length,
			sectionHeight = $sections.height(),
			scrollTop = $window.scrollTop(),
			currentSection = Math.round(scrollTop / sectionHeight),
			targetSection = currentSection - 1;
		return targetSection < 0 ? 0 : targetSection * sectionHeight;
	}
	
	//-------------------------------------
	//  FORM TRY-US
	//-------------------------------------
	
	$('form#try-us').live('submit',function(e)
	{
		var $form = $(this),
			$email = $form.find('#email')
				// suppression des classes
				.removeClass('email-error')
				.removeClass('send-error')
				.removeClass('sended');
		
		// affichage du chargement
		$body.addClass('loading-content');
		
		// envoi du formulaire en ajax
		$form.ajaxSubmit({
			data : { mode:'ajax' },
			success : function(response,status,xhr,form)
			{
				// fin du chargement
				$body.removeClass('loading-content');
				// traitement du résultat
				if (response == 'email-sent')
				{
					$email
					.addClass('email-sent')
					.attr('value',$email.attr('data-email-sent'));
				}
				else if (response == 'email-error') {
					$email
					.addClass('email-error');
				}
				else {
					$email
					.addClass('send-error')
					.attr('value',$email.attr('data-send-error'));
				}
			}
		});
		e.preventDefault();
		return false; 
	});
	
	//-------------------------------------
	//  FORM CONTACT
	//-------------------------------------
	
	$('form#contact').live('submit',function(e)
	{
		var $form = $(this),
			$email = $form.find('#email')
				// suppression des classes
				.removeClass('email-error')
				.removeClass('send-error')
				.removeClass('sended'),
			$message = $form.find('#message')
				// suppression des classes
				.removeClass('message-error')
				.removeClass('send-error')
				.removeClass('sended');
		
		// affichage du chargement
		$body.addClass('loading-content');
		
		// envoi du formulaire en ajax
		$form.ajaxSubmit({
			data : { mode:'ajax' },
			success : function(response,status,xhr,form)
			{
				// fin du chargement
				$body.removeClass('loading-content');
				
				// traitement du résultat
				if (response == 'email-sent')
				{
					$email
					.addClass('email-sent')
					.attr('value',$email.attr('data-email-sent'));
					
					$message
					.addClass('email-sent')
					.attr('value','');
				}
				else if (response == 'email-error') {
					$email
					.addClass('email-error');
				}
				else if (response == 'message-error') {
					$message
					.addClass('message-error');
				}
				else {
					$email
					.addClass('send-error')
					.attr('value',$email.attr('data-send-error'));
					
					$message
					.addClass('send-error');
				}
			}
		});
		e.preventDefault();
		return false; 
	});
	
	//-------------------------------------
	//  FORM FIELD#MESSAGE
	//-------------------------------------
	
	$('form #message')
	.live('focus',function(e)
	{
		var $this = $(this)
			// suppression de la classe du status
			.removeClass('message-error')
			.removeClass('send-error')
			.removeClass('email-sent');
		// quand le champ est vide on remet la valeur par défaut
		if (this.value == '') {
			this.value = $(this).attr('data-default');
		}
	})
	.live('blur',function(e)
	{
		// quand le champ est vide on remet la valeur par défaut
		if (this.value == '') {
			this.value = $(this).attr('data-default');
		}
	});
	
	//-------------------------------------
	//  FORM FIELD#EMAIL
	//-------------------------------------
	
	$('form #email')
	.live('focus',function(e)
	{
		var $this = $(this)
			// suppression de la classe du status
			.removeClass('email-error')
			.removeClass('send-error')
			.removeClass('email-sent'),
			// récupération de la valeur actuelle
			value = this.value,
			// récupération des valeurs par défaut
			value_default = $this.attr('data-default'),
			value_emailSent = $this.attr('data-email-sent'),
			value_sendError = $this.attr('data-send-error');
		// on vide le champ s'il s'agit d'un des valeurs
		if (value == value_default
		 || value == value_emailSent
		 || value == value_sendError) {
			this.value = '';
		}
	})
	.live('blur',function(e)
	{
		// quand le champ est vide on remet la valeur par défaut
		if (this.value == '') {
			this.value = $(this).attr('data-default');
		}
	});
	
	var currentPath = new Array('home'),
		currentPathString = '',
		currentIndex = 0,
		preventDynamicNavigation = false;
	
	//-------------------------------------
	//  UTIL
	//-------------------------------------
	
	function getPathFromUrl(url)
	{
		var base = $body.attr('data-root'),
			reg1 = new RegExp('^'+base+'/?([^#]*)'),
			path = url.match(reg1)[1],
			pathElements = [],
			pathLevel = 1;
		if (path != '') {
			var reg2 = new RegExp('([^/]+)','g'),
				pathElements = path.match(reg2),
				pathLevel = pathElements.length,
				path = pathElements.join('/');
		}
		return path;
	}
	
	//-------------------------------------
	//  NAVIGATION OVERRIDE
	//-------------------------------------
	
	if (!$html.hasClass('not-found'))
	$('#nav a,#logo a,#subnav a').live('click',function(e)
	{
		// si on est déjà en train de charger une page
		if (preventDynamicNavigation) {
			e.preventDefault();
			return false;
		}
		
		// récupération du path
		var path = getPathFromUrl($(this).attr('href'));
		
		function setHash()
		{
			// définition de l'url
			window.location.hash = path;
			// google analytics
			_gaq.push(['_trackPageview', '/'+path]);
		}
		
		var scrollTop = $window.scrollTop();
		if (scrollTop > 0) {
			$('body,html').stop().animate(
				{scrollTop:0},
				100 + scrollTop * 0.8,
				'easeInOutExpo',
				setHash
			);
		} else {
			setHash();
		}
		
		// empèche l'action par défaut (click)
		e.preventDefault();
		return false;
	});
	
	//-------------------------------------
	//  WINDOW :: HASH CHANGE
	//-------------------------------------
	
	// écoute le changement du hash de la page
	$(window).bind('hashchange', windowHashChange);
	function windowHashChange(e)
	{
		// si on est déjà en train de charger une page
		if (preventDynamicNavigation) {
			if (e) e.preventDefault();
			return;
		}
		
		// traitement des informations
		var base = $body.attr('data-root'),
			hash = window.location.hash.replace('#',''),
			path = hash.split('/'),
			pathLevel = path.length;
		
		// sélection/déselection des items
		$html.find('#nav li.current-item):has(a[href!="'+base+path[0]+'"])').removeClass('current-item');
		$html.find('#nav li:not(.current-item):has(a[href="'+base+path[0]+'"])').addClass('current-item');
		$html.find('#subnav li.current-item):has(a[href!="'+base+hash+'"])').removeClass('current-item');
		$html.find('#subnav li:not(.current-item):has(a[href="'+base+hash+'"])').addClass('current-item');
		
		// pour l'accueil
		if (hash == '') {
			loadRootContent(base, 'home');
		}
		// pour les pages de niveau 1
		else if (pathLevel == 1) {
			if (currentPath.length == 2 &&
				currentPath[0] == path[0]) {
				loadSubContent(base + hash, path[0]);
			} else {
				loadRootContent(base + hash, path[0]);
			}
		} 
		// pour les page de niveau 2
		else if (pathLevel == 2) {
			if (currentPath[0] != path[0]) {
				loadRootContent(base + hash, path[0]);
			} else {
				loadSubContent(base + hash, path[0]);
			}
		}
		
		// définition du current path
		currentPath = path;
		
		// empèche le scroll vers #hash
		if (e) e.preventDefault();
		return false;
	}
	
	//-------------------------------------
	//  LOAD ROOT CONTENT
	//-------------------------------------
	
	function loadSubContent(url, nextPageClass)
	{
		// pour éviter de charger deux pages en même temps
		preventDynamicNavigation = true;
		// affiche le chargement
		$body.addClass('loading-content');
		
		var $oldContent = $html.find('#content'),
			$newWrap = $('<div/>').hide()
			.load(url+' #content,#hidden-title',function(r,t,x)
			{
				// en cas d'erreur
				if (t == 'error') {
					currentPath = new Array('not-found');
					currentPathString = 'not-found';
					loadRootContent($('body').attr('data-root')+404,currentPathString);
					return;
				}
				
				// fin du chargement
				$body.removeClass('loading-content');
				
				// titre de la page
				window.document.title = $(this).find('#hidden-title').remove().text();
				
				var $newContent = $newWrap.find('#content').hide();
				$oldContent.fadeOut(150,'easeInOutExpo',function(){
					$html
					.removeClass('fullscreen')
					.removeClass('inner')
					.removeClass('front');
					
					// définition des autres classes
					if ($html.find('#subnav li.current-item').length > 0) {
						$html.addClass('inner');
					} else {
						$html.addClass('front');
					}
					
					$oldContent.replaceWith($newWrap.find('#content').fadeIn());
					
					updateBehavior($html);
					
					// pour éviter de charger deux pages en même temps
					preventDynamicNavigation = false;
				});
			});
	}
	
	//-------------------------------------
	//  LOAD ROOT CONTENT
	//-------------------------------------
	
	function loadRootContent(url, nextPageClass)
	{
		// pour éviter de charger deux pages en même temps
		preventDynamicNavigation = true;
		// affiche le chargement
		$body.addClass('loading-content');
		
		// direction de l'animation
		var direction = 'rtl',
			nextIndex = 0;
		$('#nav a').each(function(i,e){
			if ($(this).attr('href') == url) nextIndex = i+1;
		});
		if (nextIndex < currentIndex) direction = 'ltr';
		
		// création de l'élément temporaire pour le chargement
		var $newWrap = $('<div/>').hide()
		.load(url+' #main,#footer,#hidden-title',function(r,t,x)
		{
			// en cas d'erreur
			if (t == 'error') {
				currentPath = new Array('not-found');
				currentPathString = 'not-found';
				loadRootContent($('body').attr('data-root')+404,currentPathString);
				return;
			}
			
			// titre de la page
			window.document.title = $(this).find('#hidden-title').remove().text();
				
			$body
			.removeClass('loading-content')
			.css({
				'overflow-x':'hidden'
			});
			
			currentIndex = nextIndex;
			
			/////////////////////////////////////////////////////////////
			// OLD WRAP
			/////////////////////////////////////////////////////////////
			
			var $oldWrap = $('<div/>');
			
			$oldWrap
			.insertBefore('#main')
			.addClass($html.attr('class'))
			.css({
				'width':$body.width()+'px',
				'height':$window.height()+'px',
				'position':'absolute',
				'top':$oldWrap.hasClass('fullscreen') ? '0' : '100px',
				'left':'0',
				'overflow':'hidden'
			})
			.append($html.find('#main,#footer'));
			
			/////////////////////////////////////////////////////////////
			
			$html.removeClass();
			
			/////////////////////////////////////////////////////////////
			// NEW WRAP
			/////////////////////////////////////////////////////////////
			
			// ajout de la classe de la page
			$newWrap
			.insertAfter($oldWrap)
			.addClass(nextPageClass);
			// définition des autres classes
			if ($newWrap.find('#subnav').length > 0) {
				$newWrap.addClass('site-section');
				if ($newWrap.find('#subnav li.current-item').length > 0) {
					$newWrap.addClass('inner');
				} else {
					$newWrap.addClass('front');
				}
			}
			
			// configuration des styles
			$newWrap.css({
				'width':$body.width()+'px',
				'position':'absolute',
				'top':'100px',
				'left':'0',
				'overflow':'hidden',
				'margin-left':direction == 'rtl' ? '100%' : '-100%'
			}).show();
			
			// mise à jour du comportement
			updateBehavior($newWrap);
			
			// si il a la classe fullscreen ou fullheight
			if ($newWrap.hasClass('fullscreen')) {
				$newWrap.css({
					'top':'0',
					//'width':$body.width()+'px',
					'height':$window.height()+'px',
				});
			}
				
			/////////////////////////////////////////////////////////////
			// SUPER WRAP
			/////////////////////////////////////////////////////////////
			
			var $superWrap = $('<div/>');
			$superWrap
			.css({
				'width':'100%',
				'height':$window.height()+'px',
				'position':'absolute',
				'top':'0',
				'left':'0',
				'overflow':'hidden'
			})
			.insertBefore($oldWrap)
			.append($oldWrap)
			.append($newWrap);
			
			/////////////////////////////////////////////////////////////
			// ANIMATION
			/////////////////////////////////////////////////////////////
			
			// ancien contenu
			$oldWrap.animate({
				'margin-left':direction == 'rtl' ? '-100%' : '100%'
			},650,'easeInOutQuad',function()
			{
				$oldWrap.remove();
			});
			
			// nouveau contenu
			$newWrap.animate({
				'margin-left':'0%'
			},650,'easeInOutQuad',function()
			{
				$html.addClass($newWrap.attr('class'));
				$newWrap.unwrap();
				$superWrap.remove();
				$newWrap.find('#main,#footer').unwrap();
				$newWrap.remove();
				// fin du chargement
				$body.css({
					'overflow-x':'',
				});
				window.__sizeInvalidated = true;
				$window.resize();
				
				preventDynamicNavigation = false;
			});
			
		});
	}
	
	//-------------------------------------
	//  REDIRECTION
	//-------------------------------------
	
	var hash = window.location.hash,
		href = window.location.href,
		root = $body.attr('data-root');
	if ($html.hasClass('not-found')) {
		// do nothing
	} else if (href.replace(hash,'') != root) {
		window.location.href = $body.attr('data-root') + "#" + getPathFromUrl(href);
	} else if (hash != '') {
		windowHashChange();
	}
	
}); // end:startup
})(jQuery); // end:script-wrapper


$(document).ready( function () {
	$("div.content > .readmoreLink").live('click', function () {
		if ($(this).next("div.more:visible").length != 0) {
			$(this).next("div.more").slideUp("normal", function () { $(this).parent().removeClass("open") } );
		}
		else {
			$("div.more").slideUp("normal", function () { $(this).parent().removeClass("open") } );
			$(this).next("div.more").slideDown("normal", function () { $(this).parent().addClass("open") } );
		}
		return false;
	});
} ) ;