var blocks_ok = false, path, disable_xxl = false, hidden_box = [], inside_target;

// l'alias de la page
function getPageAlias(isAjax) {
  if ($('.page:visible').length) {
    var aliases = $('.page:visible').data('pageInfo').alias;
    return aliases[aliases.length-1];
  }
  return 'home';
}
function search(form) {
  $(window).history('add', '#/search.html?' + $(form).serialize());
  return false;
}

$(document).ready(function(){

    // initialisation des infos de page
    $(".page:visible").data('pageInfo', pageInfo);
    jQuery.datepicker.setDefaults(jQuery.datepicker.regional[language]);

    // background
    if (!isTablet) {
      $.backstretch();
      $("#navimages .recharge").live('click', function(e){
        $("#box_infos").toggleClass('ouvert');
        $.each(hidden_box, function(id, box){
          $(box).show();
          $("#menu_home").append(box).masonry( 'appended', box );
        });
        $('#menu_home').masonry( 'reload' );
      });
    }
    
    // slider xxl
    startSlider = function() {
      jQuery(".menu_xxl:visible ul.slider").anythingSlider({
        easing: "easeInOutExpo",
        autoPlay: true,
        delay: 5000,
        startStopped: false,
        hashTags: true,
        buildNavigation: false,
        pauseOnHover: true,
        startText: "",             // Start text
        stopText: ""
      });
    }
    startSlider();

    
    // block home
    // positionner si visible
    function init_blocks() {
      if (isTablet) {
        blocks_ok = true;
        return;        
      }
      if (!blocks_ok && $(".nav-box:visible").length) {
        $(".nav-box:visible").draggable({
           containment:'document',
           handle: '.title_box',
           start: function() {
               disable_xxl = true;
           },
           stop: function() {
               setTimeout('disable_xxl = false', 200);
           }
        });
        $('#menu_home').masonry({
          itemSelector: '.nav-box',
          columnWidth: 100,
          isAnimated: true
        });
        blocks_ok = true;
      }
    }
    // affichage block home
    function show_blocks() {
      $("#menu_home").fadeIn(800, function(e){
         init_blocks();
      });
      toplevel_oid = 'home';
      if (!isTablet)
        $.backstretch('reload');
    }
    init_blocks();

    // hauteur bloc_info home
    $("#box_infos").css('min-height', $("#box_infos .bloc_infos").height());
    // bloc plus d'infos home
    $(".plus_infos, .ooo", "#box_infos").click(function(e){
      $("#box_infos").toggleClass('ouvert', 200, function(e){
        $('#menu_home').masonry( 'reload' );
      });
      return false;
    });
    // bloc plus d'infos home
    $("#left_menu .ooo").click(function(e){
      $("#box_infos_menu").toggleClass('ouvert');
      return false;
    });
    
    $("#menu_home .close").click(function(e){
      e.stopPropagation();
      var nav_box = $(this).parents(".nav-box");
      nav_box.effect('explode', {pieces:16}, 800, function(){
        hidden_box.push(nav_box.detach());
        $('#menu_home').masonry( 'reload' );
      });
    });
    
    
    function show_xxl(e, id){
      $("#overlay").fadeIn(500);
      toggle_xxl(id);
      $("#xxl").show();
      $.scrollTo("#main", 500, {axis: 'y'});
      startSlider();
      e.stopPropagation();
    }
    function hide_xxl(){
      $("#xxl").slideUp(500, function(e){
        $("#overlay").fadeOut(500);
      });
    }
    $("#xxl .close").click(function(e){
      if (window.location.hash.length)
        history.go(-1);
      else
        hide_xxl();
    });
    // menu xxl
    function toggle_xxl(id) {
      var target = $("#menu_xxl_"+id);
      $(".menu_xxl").not(target).removeClass('current');
      target.addClass('current');
    };
    function show_main() {
      if ($("#menu_home").is(":visible"))
        $("#menu_home").fadeOut(500);
      if ($("#overlay").is(":visible"))
        $("#overlay").fadeOut(500);
      if ($("#main").is(":hidden"))
        $("#main").fadeIn(300);
      toplevel_oid = 'pages';
      if(!isTablet)
        $.backstretch('reload');
    }
    
    $("#xxl .close").click(function(e){
      hide_xxl();
    });

    $(".nav_xxl a").click(function(e){
      e.stopPropagation();
      $("html").unbind('click');
      path = $(this).attr('id').split('_');
      path.shift();
      var href = $(this).attr('href');
      $("#xxl").slideUp(500, function(e){
        show_main();
        $("#anav_"+path.join('_')).click();
      });
    });

    // accordeon level2/3
    nav23 = function(a) {
      var path = a.attr('id').split('_');
      $(".navlist li, .ullevel1 li", "#left_menu").removeClass('active');
      a.parents('li').addClass('active');
      $("#anav_"+path[1]).parents('li').addClass('active');
      
    }
    $("#left_menu .navlist a").click(function(e){
      nav23($(this));
    });

    // close main content
    $(".nav-box_page .fermer").live('click', function(e){
      $(".page").fadeOut(800);
    });
    //back home
    $("#logo a").live('click', function(e){
      $("#main").slideUp(500, function(e){
        show_blocks();
        $(window).history('add', '');
      });
    });
    
    // scroll top
    $(".top a").live('click', function(e){
      $.scrollTo("#content", 500, {axis: 'y'});
      return false;
    });
    
    // intercepte le a click
    aClick = function(e) {
      e.stopPropagation();
      // direct links
      if ($(this).is('.noajax'))
        return true;
      var href = $(this).attr('href') || '#';
      // lien dans la page
      if ($(this).is('.inside') && href.substring(0,1) == '#' && href.length > 1) {
        $.scrollTo(href, 500, {axis: 'y'});
        return false;
      }
      // close, nyromodal et addthis
      if (href.substring(0,1) == '#' || $(this).is(".close") || /^(nyro|addthis)/.test($(this).attr('class')))
        return false;
      // ignorer les liens externes
      href = href.replace(location.protocol+'//'+location.host, '');
      if (this.target.length
        || href.substring(0,6) == 'mailto'
        || href.substring(0,10) == 'javascript'
        || /pdf$/.test(href))
        return true;
      if (/http:/g.test(href)) {
        this.target = "_blank";
        return true;
      }
      // peremption (20mn)
      if ((new Date().getTime() - pageDate.getTime()) > 20*60*1000) {
        document.location = href;
        return true;
      }
      // cache
      if (window.nocache != undefined) {
        if (href.indexOf('?') == -1)
          href += '?nocache=1';
        else
          href += '&nocache=1';
        document.location = href;
        return true;
      }
      // si présent dans main menu, click dans le main menu pour accordeon
      if (!$(this).parents("#left_menu").length && $("#left_menu a[href$='"+href+"']").length) {
        nav23($("#left_menu a[href$='"+href+"']"));
      }
      e.preventDefault();
      if ($(this).data('target') != undefined)
        inside_target = $(this).data('target');
      else
        delete inside_target;
      // réafficher la page courante fermé
      var here = top.location.hash.substring(1);
      if (here == href) {
        var pageId = href.substring(1).replace('.html', '').replace(/[\/\?=&\.:]/g, '_');
        $("#"+pageId).show();
      } else
        $(window).history('add', '#' + href);
    }
    $("a").live('click', aClick);

    contentLoaded = function() {
      $('.nyroModal').nyroModal();
      // tooltip
      $(".with-tooltip").simpletooltip();
      // widget agenda
      agenda();
    };
    $(window).bind('loadcontent', contentLoaded);
    contentLoaded();

    // chargement de contenu sur changement location
    $(window).bind('hashchange', function(e, ui) {
      var dest = top.location.hash.substring(1),
          pageId = dest.substring(1).replace('.html', '').replace(/[\/\?=&\.:%]/g, '_'),
          url = top.location.hash.substring(1),
          a = $("a:[href='"+url+"']", "#left_menu").not("#page_title"),
          page = $("#"+pageId);
      // Suppression de la page si le paramètre always_reload est spécifié
      var current_page = $(".page:visible");
      if (current_page.length && current_page.data('pageInfo').always_reload == 1) {
        current_page.remove();
      }
      // toplevel
      if (a.is(".toplevel")) {
        var id = a.attr('id').split('_')[1];
        show_xxl(e, id);
        return false;
      } else
        hide_xxl();
      // current page
      if (dest == '' || page.is(":visible")) {
        return false;
      }
      if ($("#main").is(":hidden")) {
        show_main();
      }
      $("#overlay,#xxl").fadeOut(300);
      // page exist
      if (page && page.length) {
        $(".page:visible").fadeOut(300);
        page.fadeIn(300, function(){
          if (inside_target != undefined)
            $.scrollTo("#"+inside_target, 500, {axis: 'y'});
          else
            $.scrollTo("#main", 500, {axis: 'y'});
        });
        $("#page_title")
        .html($("#"+pageId).data('pageInfo').breadcrumb[0])
        .attr('href',  '/'+$("#"+pageId).data('pageInfo').aliases[0]+'.html');
      } else {
        $(".page:visible").fadeOut(300);
        $("#waiting").fadeIn(1000);
        var params = {ajax:1};
        $.get(url, params)
        .complete(function(jqXHR){
          var data = jQuery.parseJSON( jqXHR.responseText )
          $("#waiting").hide();
          $("#end_pages").before('<div class="page" id="'+pageId+'">'+data.html+'</div>');
          if ($("#main:hidden").length)
            show_main();

          // svg des infos de page
          $("#"+pageId).data('pageInfo', data.pageInfo);
          // si présent dans main menu, et pas actif, click dans le main menu pour accordeon (reload)
          if (data.pageInfo.id != undefined) {
            if (!$("#anav_"+data.pageInfo.id.join('_')).parent().is('.active'))
              nav23($("#anav_"+data.pageInfo.id.join('_')));//.trigger('click');
          }
          else if ($("#left_menu #box_infos_menu a[href~='"+data.pageInfo.alias+"']").length) { // menu ooo
            $(".navlist li").removeClass('active');
            $("#box_infos_menu").addClass('ouvert');
            $("#"+pageId).fadeIn(300);
          }
          if (data.pageInfo.breadcrumb[0].length)
            $("#page_title")
            .html(data.pageInfo.breadcrumb[0])
            .attr('href', '/'+$("#"+pageId).data('pageInfo').aliases[0]+'.html');
          $(window).trigger('loadcontent');
          if (inside_target != undefined)
            $.scrollTo("#"+inside_target, 500, {axis: 'y'});
          else
            $.scrollTo("#main", 500, {axis: 'y'});
        });
      }
    });


    // Charge la page demandé dans l'ancre si renseignée
    var href = window.location.hash.length ? window.location.hash.substring(1) : '';
    if (href.length) {
      if (!/(^\/index.php|\.html$)/.test(href))
        href = '/'+href+'.html';
      $(window).trigger('hashchange');
    }

    // widget agenda
    function agenda() {
      $(".proch_dates a").click(function(e){
        var id = $(this).data('id');
        var contenu = $(this).parents(".contenu");
        $(".proch_dates a").removeClass('current');
        $(this).addClass('current');

        $(".a_venir", contenu).hide();
        $(".content_event_"+id, contenu).show();
        return false;
      });
    }
});



