var blocks_ok = false, path, disable_xxl = false, 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';
}


$(document).ready(function(){
    // Désactivation du clic droit
    $(document).bind("contextmenu",function(e){
      e.preventDefault();
    });

    // tooltip
    $(".with-tooltip").simpletooltip();
    
    // background
    $.backstretch();
    $("#navimages .recharge").live('click', function(e){
      $(".nav-box").each(function(i,elt){
        var position = $(this).data('originalPosition');
        $(this).css({left:position.left, top:position.top}).show();
      });
    });

    // block home
    function init_blocks() {
      if (!blocks_ok) {
        // block home
        if ($(".nav-box:visible").length) {
          var menu_homeOffset = $('#menu_home').offset();
          $($(".nav-box:visible").get().reverse()).each(function(i,elt){
            var offset = $(this).offset();
            var position = {left:offset.left-menu_homeOffset.left, top:offset.top-menu_homeOffset.top};
            $(this)
            .css({position:'absolute', left:position.left, top:position.top})
            .data('originalPosition', position);
          }).draggable({
            containment:'document',
            handle: '.txt_box,.title',
            start: function() {
                disable_xxl = true;
            },
            stop: function() {
                setTimeout('disable_xxl = false', 200);
            }
          });
          blocks_ok = true;
        }
        // station menu home
        $("#home_menu").draggable({
              containment:'document',
              handle: '.txt_box'
        });
      }
    }
    function show_blocks() {
      $("#menu_home").fadeIn(800, function(e){
        init_blocks();
      });
    }
    init_blocks();
    $("#main").draggable({containment:'document', handle: '#chemin'});
    $("#menu_home .ouvre_xxl").click(function(e){
      if (disable_xxl)
        return false;
      var id = $(this).attr('id').split('_')[1];
      show_xxl(e, id);
    });
    $("#menu_home .close").click(function(e){
      e.stopPropagation();
      $(this).parents(".nav-box").effect('explode', {}, 600);
    });
    // station menu home
    $("#home_menu .close").click(function(e){
      $("#home_menu .img_box-menu").slideToggle();
    });
    // recalcul la position du menu xxl /*et de l'overlay*/ / main
    function adjust_position(){
      var main = $("#main"),
          position = main.offset();
      if (main.is(':visible')) {
        $("#xxl").css({top:position.top, left:position.left});
      }
    }
    function page_size(){
      bottom_xxl = $("#bottom_xxl").offset();
      $("#page").css({'min-height': Math.max(600, bottom_xxl ? bottom_xxl.top : 0)});
    }
    page_size();
    function show_xxl(e, id){
      adjust_position();
      $("#xxl").show();
      if ($("#main:visible").length)
        $("#overlay").show();
      $("#menu_home").hide();
      toggle_xxl(id);
      $("html").one('click', function(e){
        hide_xxl();
        e.stopPropagation();
      });
      $.scrollTo("#xxl", 500, {axis: 'y'});
      e.stopPropagation();
      page_size();
    }
    function hide_xxl(){
      $("#xxl").slideUp(500, function(e){
        if ($("#main:visible").length)
          $("#overlay").fadeOut(500);
        else
          show_blocks();
        page_size();
      });
    }

    // intercepte le a click
    aClick = function(e) {
      // direct links
      if ($(this).is('.noajax'))
        return true;
      var href = $(this).attr('href') || '#';
      // ne pas traiter
      if ($(this).is(".ouvre_xxl, .toplevel, .switchSaison, .ajouter-selection")
        || href.substring(0,1) == '#')
        return false;
      // nyromodal et addthis
      if (/nyro/.test($(this).attr('class')))
        return true;
      if (/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'
        || (/^http:/.test(href))
        || (/^\/tzr/.test(href))
        || href.substring(0,10) == 'javascript')
        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;
      }
      // enregistrer la cible dans la page
      if ($(this).data('target') != undefined)
        inside_target = $(this).data('target');
      else
        delete inside_target;

      e.preventDefault();
      var anchor = getAnchor(href);
      anchors[anchor] = href;
      $(window).history('add', '#' + anchor);
    }
    $("a").live('click', aClick);

    contentLoaded = function() {
      CCVU.onContentLoaded();
      // telechargement brochure
      jQuery('a.nyroFlash').nyroModal({
        type:'swf',
        height:700,
        width:1000
      });
    };
    $(window).bind('loadcontent', contentLoaded);
    contentLoaded();

    var pageXHR = null;
    // chargement de contenu sur changement location
    $(window).bind('hashchange', function(e, ui) {
      // recherche du toplevel oid pour les images de fonds
      var dest = top.location.hash.substring(1),
          pageId = dest.replace(/\//g, '_') || $("#col970 > .page").attr('id'),
          url = anchors[dest] || '/error404.html',
          a = $("a:[href='"+url+"']"),
          toplevel = a.parents(".navlist>li").find(".toplevel"),
          next_oid = toplevel.data('oid') /*|| a.data('oid')*/;
      // current page
      if (dest == '' || $("#"+pageId+":visible").length) {
        return false;
      }
      if ($("#main").is(":hidden")) {
        $("#menu_home").fadeOut(300, function(e){
          $("#main").fadeIn(300);
        });
      }
      // Suppression de la page si le paramètre always_reload est spécifié
      if ($("#"+pageId).length && $("#"+pageId).data('pageInfo').always_reload == 1) {
        $("#"+pageId).remove();
      }
      $("#overlay,#xxl").fadeOut(300);
      // page exist
      if ($("#"+pageId+":hidden").length) {
        $(".page").hide();
	$("#"+pageId).fadeIn(300, function(){
	  if (inside_target != undefined)
	    $.scrollTo("#"+inside_target, 500, {axis: 'y'});
	  else
	    $.scrollTo("#main", 500, {axis: 'y'});
	});
	if (next_oid != undefined && next_oid != toplevel_oid) {
	  $.backstretch('reload');
	}
	breadcrumb(pageId);
	CCVU.onContentDisplayed();
      } else {
        $(".page").hide();
        $("#waiting").fadeIn(300);
        var params = {ajax:1};
        // top level oid pour image bg
        if (next_oid != undefined && next_oid != toplevel_oid && bgImgs[next_oid] == undefined) {
          toplevel_oid = next_oid;
          $.extend(params, {toplevel_oid: toplevel_oid});
        }
        // Annule la précédente requête AJAX pour éviter d'avoir 2 pages ouvertes en même temps
        if (pageXHR != null) pageXHR.abort();
        pageXHR = $.get(url, params, function(data){
          $("#waiting").hide();
          $("#col970").prepend('<div class="page '+site.saison+'" id="'+pageId+'">'+data.html+'</div>');
          if ($("#main:hidden").length)
            $("#main").fadeIn(500);
          if (data.bgImgs && toplevel_oid != undefined) {
            bgImgs[toplevel_oid] = data.bgImgs;
            $.backstretch('reload');
          }
          // svg des infos de page
          $('#'+pageId).data('pageInfo', data.pageInfo);
          breadcrumb(pageId);
          // si présent dans main menu, et pas actif, ouverture
          if (data.pageInfo.id != undefined) {
            if (!$("#anav_"+data.pageInfo.id.join('_')).parent().is('.active'))
              nav23($("#anav_"+data.pageInfo.id.join('_')));
          }
          else { // menu bas
            $(".ullevel2").hide();
            $(".navlist li").removeClass('active');
          }
          $(window).trigger('loadcontent');
          if (inside_target != undefined)
            $.scrollTo("#"+inside_target, 500, {axis: 'y'});
          else
            $.scrollTo("#main", 500, {axis: 'y'});
        }, 'json');
      }
    });

    // actualise le breadcrumb
    breadcrumb = function(pageId) {
      var breadcrumb = '',
          last = $('#'+pageId).data('pageInfo').breadcrumb.length -1;
      $.each($('#'+pageId).data('pageInfo').breadcrumb, function(i, crumb){
        if (i==last)
          breadcrumb += '<li>'+crumb+'</li>';
        else {
          breadcrumb += '<li><a href="';
          $.each($('#'+pageId).data('pageInfo').alias, function(j, alias){
            if (j <= i)
              breadcrumb += '/'+alias;
          });
          breadcrumb += '.html">'+crumb+'</a></li>';
        }
      });
      $("#chemin ul").html(breadcrumb);
    }

    // menu xxl
    $("#xxl .toplevel").click(function(e){
      e.stopPropagation();
      var id = $(this).attr('id').split('_')[1];
      toggle_xxl(id);
    });
    function toggle_xxl(id) {
      $("#xxl_top>.title1").removeClass('current');
      $("#xxl_content>ul").hide();
      $("#xxl .toplevel").parent().removeClass('active');

      $("#xxltitle_"+id).addClass('current');
      $("#ulxxl_"+id).show();
      $("#axxl_"+id).parent().addClass('active');
      page_size();
    };

    $("#xxl .close").click(function(e){
      hide_xxl();
    });

    $("#xxl_content 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){
        if ($("#overlay").is(":visible"))
          $("#overlay").fadeOut(500);
        if ($("#main").is(":hidden"))
          $("#main").fadeIn(300);
        // le menu en avant
        $(".rib,.level3").hide();
        $(".rib:not(#rib_"+path[0]+")").show();
        $("#anav_"+path.join('_')).click();
      });
    });

    // left menu
    // toplevel show xxl
    $("#left_menu .toplevel, #home_menu .toplevel").click(function(e){
      var id = $(this).attr('id').split('_')[1];
      $(".ullevel2").hide();
      show_xxl(e, id);
    });

    // accordeon level2/3
    nav23 = function(a) {
      var path = a.attr('id').split('_');
      var level2 = $("#ullevel2_"+path[1]);
      var level3 = $("#ullevel3_"+path[1]+'_'+path[2]);
      $(".ullevel2").not("#ullevel2_"+path[1]).hide(300);
      $(".ullevel3").not("#ullevel3_"+path[1]+'_'+path[2]).hide(300);
      if (level2.is(':hidden'))
        level2.show(300);
      if (level3.is(':hidden'))
        level3.show(300);
      $("#left_menu li").removeClass('active');
      a.parents('li').addClass('active');
    }
    $("#left_menu a:not(.toplevel)").click(function(e){
      nav23($(this));
    });

    // close main content
    $("#main .close").click(function(e){
      $("#main").slideUp(500, function(e){
        $("#menu_home").fadeIn(800, function(e){
          show_blocks();
        });
        $(".ullevel2").hide();
        $(window).history('add', '');
      });
    });
    $(window).resize(function(e){
      adjust_position();
    });

    // slider vignette bas de page
    // regler la hauteur
    var sliderInterval = new Array();
    $.each(['eve', 'actus'], function(i, sel){
      if ($("#"+sel+" .vignette").length < 2)
        return;
      $("#"+sel+" .slider").height($("#"+sel+" .vignette").length * 71);
      slide = function (elt) {
        $(elt).animate({top: '-71px'}, 800, function() {
            vtop = $(this).find(".vignette:first").detach();
            $(this).css('top', 0);
            vtop.appendTo(this);
        });
      }
      // lancer le slider
      sliderInterval[sel] = setInterval(function(){
        slide("#"+sel+" .slider");
      }, 3000 + Math.floor(Math.random()*6000));
      // au click stop slider auto et bind slider au click
      $("#"+sel+" .slider").click(function(e){
        clearInterval(sliderInterval[sel]);
        $(this).click(slide("#"+sel+" .slider"));
      });
      // le bouton
      $("#"+sel+" .bt a").click(function(e){
        clearInterval(sliderInterval[sel]);
        // if exist close
        if ($("#"+sel+"full").length) {
          $("#"+sel+"full").remove();
          return false;
        }
        $("#"+sel+" .slider")
        .clone()
        .removeClass('slider')
        .css({top: '', left: $("#"+sel).position().left-5})
        .attr('id', sel+'full')
        .addClass(sel+' full')
        .insertBefore("#"+sel+" .slider");
        contentLoaded();
        $("body").one('click', function(e){
          $("#"+sel+"full").remove();
        });
        return false;
      });

    });

    $(".switchSaison").live('click', function(e){
        $(this).parents(".page").toggleClass('ete').toggleClass('hiver');
    });
    // selection
    $(".ajouter-selection").live('click', function(e){
      if ($(this).is(".delete")) {
        var _function = 'delfromselection';
        // si dans la selection, suppression fiche
        if ($(this).parents('#selection').length) {
          var divliste = $(this).parents('.liste');
          $(this).parents('.fiche').remove();
          // et suppression du groupe vide
          if (!divliste.find('.fiche').length) {
            divliste.remove();
          }
        }
      }
      else
        var _function = 'addtoselection';
      $.get('/index.php', {
        'function': _function,
        oid: $(this).data('oid'),
        type:$(this).data('type')
      },
      function(data){
        $(".selection .nb").html(data.count);
        $(".selection:not(#main_selection)").toggle(data.count != 0);
        $(".ajouter-selection[data-oid='"+data.oid+"']").toggleClass('hidden');
      },
      'json');
      return false;
    });

    // Récupère le lien de page contenu dans l'ancre
    getAnchor = function(href) {
      if (/^\/?([^\.]*).html/.test(href))
        return (/^\/?([^\.]*).html/).exec(href)[1];
      else {
        return (/^\/index.php\?(.*)/).exec(href)[1].replace(/[^a-zA-Z0-9_-]/g, '');
      }
    };

    // 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';
      anchors[getAnchor(href)] = href;
      $("#menu_home").hide();
      $(window).trigger('hashchange');
    }
    
    
});


