(function($) {

Drupal.behaviors.init_theme = {};
Drupal.behaviors.init_theme.attach = function (context) {
  // Growl-style system messages
  $('#messages-and-help > div.messages:not(.processed)')
    .addClass('processed')
    .each(function() {
      // If a message meets these criteria, we don't autoclose
      // - contains a link
      // - is an error or warning
      // - contains a lenghthy amount of text
      if ($('a', this).size() || $(this).is('.error') || $(this).is('.warning') || $(this).text().length > 100) {
        $(this).prepend("<span class='close'>X</span>");
        $('span.close', this).click(function() {
          $(this).parent().slideUp('fast');
        });
      }
      else {
        // This essentially adds a 3 second pause before hiding the message.
        $(this).animate({opacity:1}, 5000, 'linear', function() {
          $(this).slideUp('fast');
        });
      }
    });

  if(!$('body').is('.front') && !$('body').is('.node-type-performance')){
    $('#main').jScrollPane({autoReinitialise:true, hijackInternalLinks:true});
  }
  
  $('#block-menu-block-2 ul.menu').listnav({cookieName:'test', attribute:'nom'});
};

Drupal.behaviors.init_timeline = {};
Drupal.behaviors.init_timeline.attach = function (context) {

  $.paScPlayer.defaults.onDomReady = null;
  $.paScPlayer.defaults.loadArtworks = 0;

  if($('html').is('.oldie'))
  {
    $('html').addClass('classic-nav');
  }
  else if($('body').is('.front') || $('body').is('.node-type-performance'))
  {
    var _$modalIntro = $('<div class="modal">').appendTo($('<div id="intro-wrapper"><div class="bg"></div></div>').appendTo('body')).verticalcenter(),
        _$timeline_loader, _$perfnode, _$filters, _$timeline, _$timeline_container,
        _datas = {},
        _dates = [], _dates_nids = [],
        _timeline,
        view_modes = ["dot", "titles", "thumbnails", "images"], current_view_mode,
        _filters = {}, _filters_str_tids = [], _filters_key = {}, _filters_correspondances = {}, _selected_filters = [],
        filterInputTimer, prevFilterInput = '',
        _layouts = {
          intro:"layout-intro",
          timeline:"layout-timeline",
          perfnode:"layout-perfnode"
        },
        _grid,
        _current_nid = false,
        _perf_jsp,
        _$next_perf, _$prev_perf,
        _intro_start,
        _$modal,
        _drupalBasePath = Drupal.settings.basePath+Drupal.settings.pathPrefix,
        _strings = Drupal.settings.perfarttimeline.strings;

    function init(){

      if(readCookie('advanced-nav') != 'yes' && readCookie('classic-nav') != 'yes'){
        
        $.getJSON(_drupalBasePath+'perfart/ajax/home', function(data){  
          console.log('data', data);
          _$modalIntro.prepend(data.front).verticalcenter();
          $('.nodetitle',_$modalIntro).hide();
        });
        var $btns = $('<div class="btns">').appendTo(_$modalIntro);
        $btns.append($('<span>'+_strings.advanced_nav+'</span>').bind('click', function(event) {
          createCookie('advanced-nav', 'yes');
          $btns.hide();
          initAdvancedNav();
        }));
        
        $btns.append($('<span>'+_strings.classical_nav+'</span>').bind('click', function(event) {
          createCookie('classic-nav', 'yes');
          initClassic();
        }));

      }else{
        if(readCookie('advanced-nav') == 'yes'){
          initAdvancedNav();
        }else{
          initClassic();
        }
      }
    };

    function initClassic(){
      // console.log('initClassic');
      removeIntroModal();
      $('html').addClass('classic-nav');
    };

    function initAdvancedNav(){
      // build dom layout //
      _$timeline_loader = $('<div id="timeline-loader">').appendTo(_$modalIntro).append('<div>'+_strings.loading_timeline+'</div>').append($('<div class="progress">'));
      _$perfnode = $('<div id="perfnode"><div class="loader"/><div class="close"/><div class="node-container"><div class="scroller"/></div></div>').appendTo('#center');
      _$filters = $('<div id="filters">').appendTo('#center');
      _$timeline = $('<div>').attr('id', 'timeline').appendTo('#center').append('<h3 class="title">Chronologie</h3>');
      _$timeline_container = $('<div>').attr('id', 'timeline-container').appendTo('#timeline');
      _$next_perf = $('<div class="next-perf">').appendTo(_$perfnode);
      _$prev_perf = $('<div class="prev-perf">').appendTo(_$perfnode);
      _$modal = $('<div class="timeline-modal">').appendTo('body');

      $('body').addClass('view-mode-'+view_modes[0]);

      // start //
      _timeline = new links.Timeline(document.getElementById('timeline-container'));


      var timeline_options = {
        "width":  "100%",
        "height": _$timeline_container.height()+"px",//"100%",
        "style": "dot",
        "editable": false,
        "axisOnTop":true,
        "min":new Date('1950'),
        "max":new Date('2020'),
        "start":new Date('1950'),
        "end":new Date('2020'),
        "showCurrentTime":false,
        "animate":true,
        "animateZoom":true,
        "intervalMin":1000*60*60*24*365, // a year
        "showNavigation":true,
        // "stackEvents":false,
        'eventMargin': 0,    // minimal margin between events 
        'eventMarginAxis': 4, // minimal margin beteen events and the axis

        // custom options
        "mousewheel":"move",
        "dblclick":"zoom",
        "language":Drupal.settings.perfarttimeline.language,
      };

      _timeline.draw([], timeline_options);
      
      _$next_perf.bind("click", onClickBtnNavPerf);
      _$prev_perf.bind("click", onClickBtnNavPerf);
      
      $('.close', _$perfnode).bind('click', function(event) {
        showTimeline();
      });
      

      $(".node-container",_$perfnode).height(_$perfnode.height());

      switchLayout('intro');
      
      initHistory();

      initKeyBoardNav();

      // Drupal.settings.perfart.effectuations_pages = 1;
      _intro_start = new Date();
      loadDates();      
    };

    function loadDates(page){
      page = page || 0;
      var url = _drupalBasePath + "perfart/ajax/dates/"+page,
          regexp;
      if(page == 0)
        $('.progress', _$timeline_loader).width('5%');
      
      $.getJSON(url, function(data){
        var date, start, end;
        // console.log('data', data);
  			$('.progress', _$timeline_loader).width((page+1)*(100/Drupal.settings.perfart.effectuations_pages)+'%');
        
        for(ind in data){
          if(data[ind].start === undefined)
            continue;
          
          date = data[ind];
          // console.log('date thumb',date.thumb);
          date.start = new Date(date.start.year, date.start.month, date.start.day);
        
          if(typeof date.end != "undefined")
            date.end = new Date(date.end.year, date.end.month, date.end.day);
            
          // filters
          for(filterstitle in date.filters){
          // console.log('date.filters', date.filters.length);
          // var filterstitle, tid;
          // for (var i = 0; i < date.filters.length; i++) {
          //   filterstitle = date.filters[i];
            if(_filters[filterstitle] === undefined){
              _filters[filterstitle] = [];
              _filters_str_tids[filterstitle] = "";
            }
            
            // console.log('date.filters = '+filterstitle, date.filters[filterstitle]);
            
            for(tid in date.filters[filterstitle]){
            // for (var j = 0; j < date.filters[filterstitle].length; j++) {
            //   tid = date.filters[filterstitle][j];

              if(_filters_key[tid] === undefined)
                _filters_key[tid] = filterstitle;

              if(date.tids === undefined)
                date.tids = [];
                
              date.tids.push(tid);
              
              regexp = new RegExp('tid'+tid+';');
              if(_filters_str_tids[filterstitle].search(regexp) != -1)
                continue;
                
              _filters_str_tids[filterstitle] += 'tid'+tid+";";

              date.filters[filterstitle][tid].visible = true;
              _filters[filterstitle].push(date.filters[filterstitle][tid]);
            }
            
          }
          
          
          for (var i = 0; i < date.tids.length; i++) {
            if(_filters_correspondances[date.tids[i]]=== undefined)
              _filters_correspondances[date.tids[i]] = [];
            for (var j = 0; j < date.tids.length; j++) {
              if(date.tids[j] != date.tids[i] && array_indexOf(_filters_correspondances[date.tids[i]], date.tids[j]) === -1)
                _filters_correspondances[date.tids[i]].push(date.tids[j]);
            }
          }

          _datas[date.nid] = date;
          _dates.push(date);
          _dates_nids.push(date.nid);
        }
        
        if(page+1 == Drupal.settings.perfart.effectuations_pages){
          $('.progress', _$timeline_loader).width('100%').addClass('complete');
          //console.log('_datas', _datas);
          // console.log('_filters', _filters);
          // console.log('_dates', _dates);
          onDatesLoaded();
        }else{
          loadDates(page+1);
        }

      })
      .error(function(jqXHR, textStatus, errorThrown) {
        console.log("error " + textStatus);
        console.log("incoming Text ", jqXHR); 
        console.log('ERROR on loading dates page '+page);

        $('.progress', _$timeline_loader).width((page+1)*(100/Drupal.settings.perfart.effectuations_pages)+'%');
        if(page+1 == Drupal.settings.perfart.effectuations_pages){
          $('.progress', _$timeline_loader).width('100%').addClass('complete');
          onDatesLoaded();
        }else{
          loadDates(page+1);
        }
      });
    };
    
    function onDatesLoaded(){
      initTimeline();
      if($('body').is('.front')){ launchTimeline();}
      else if( $('body').is('.node-type-performance') ){ launchPerf(); }
      setTimeout(removeIntroModal, 400);
    };

    function removeIntroModal(){
      _$modalIntro
        .css({'margin-top':'-'+(_$modalIntro.height()+100)+'px'})
        .siblings().hide();

      setTimeout(function(){
        _$modalIntro.parent().hide();
      }, 900);
    };
    
    function launchTimeline(){
      var end_loading = new Date(),
          pause = readCookie('timelinelaunched') == 'ok' ? 5000 : 10000,
          left_time = pause - (end_loading.getTime() - _intro_start.getTime());

      if(left_time < 0){
        showTimeline();
      }else{
        setTimeout(function(){
          createCookie('timelinelaunched', 'ok', 1);
          showTimeline();
        }, left_time);
      }  
    };

    function launchPerf(){
      var bodyclasses = $('body').attr('class'),
          matches = bodyclasses.match(/page-node-([0-9]+)/),
          nid = matches[1],
          date = _dates[array_indexOf(_dates_nids, nid)];

      loadPerformance(_datas[nid].ajax_link);
    };

    /**
    * keyboard navigation
    */
    function initKeyBoardNav(){
      $(window).bind('keydown', function(event){
        // console.log('keypressed', event);
        switch(event.keyCode){
          case 39://droite
            nextPerf();
          break;
          case 37://gauche
            prevPerf();
          break;
          case 38://haut
            if(_current_nid)
              //showPerformance();
          break;
          case 40://bas
            showTimeline();
          break;
        }
      });
    };

    /**
    * History
    */
    function initHistory(){
      var State = History.getState();
      
      // Log Initial State
      //History.log('initial:', State.data, State.title, State.url);    

      // Bind to State Change
      $(window).bind('statechange', function(){
        historyOnStateChange(History.getState());
      });
    };

    function historyOnStateChange(state){
      // History.log('statechange:', state.data, state.title, state.url);
      if (objectIsEmpty(state.data)){
        switchLayout('timeline');
        _current_nid = false;
        updateTranslationLink();
      }else if (_current_nid != state.data.json.nid) {
        updateTranslationLink(_datas[state.data.json.nid].node_translation);
        resetFilters();
        switchLayout('perfnode');
        showPerformance(state.data.json);
        // if(_current_nid){
        //   showPerformance(state.data.json);
        // }else{
        //   loadPerformance(state.data.ajaxpath);
        // }
        
      };
    };

    /**
    * time line 
    */
    function initTimeline(){
      
      setFilters();
      
      setupDatesLinks();
      
      updateTimeline();
      
      $('body').addClass('timeline');
      
      $('h3.title', _$timeline).bind('click', function(event) {
        showTimeline();
      });

      initSearch();
    };

    function showTimeline(){
      switchLayout('timeline');
      updateTranslationLink('');
      History.pushState({}, _strings.site_name, _drupalBasePath);
    };

    function setupDatesLinks(){
      $('div.date', _$timeline_container)
        .bind('click', onClickDate)
        .bind('mouseenter', onHoverDate)
        .bind('mouseleave', onOutDate);
    };
    
    function onClickDate(event){
      event.preventDefault();
      //console.log('onClickDate');
      
      loadPerformance($(this).attr('href'));
      
      return false;
    };

    function onHoverDate(event){
      var $date = $(event.currentTarget);
      _$modal
        .stop(true, true)
        .css({
          'top':event.clientY - _$modal.height() - 5,
          'left':event.clientX+5
        });
  
      // console.log('event',event);
      var visible = true;
      if($('body').is('.view-mode-dot')){
        _$modal.html($date.find('.text-content').html());  
      }else{
        // console.log('thumb = '+$date.attr('thumb'));
        if(typeof _datas[$date.attr('nid')].thumb != "undefined"){
          _$modal.html(_datas[$date.attr('nid')].thumb);  
        }else{
          _$modal.html("");
          visible = false;
        }
      }
      
      if(visible){
        $date.bind('mousemove', onDateMouseMove);
        _$modal.fadeIn();  
      }
    };

    function onDateMouseMove(event){
      _$modal
        .css({
          'top':event.clientY - _$modal.height() - 5,
          'left':event.clientX+5
        });    
    };

    function onOutDate(event){
      $(event.currentRarget).unbind('mousemove', onDateMouseMove);
      _$modal.stop(true, true).fadeOut();
    };

    function onBeforeStackEvents(){
      // console.log('onBeforeStackEvents | visibleItems', _timeline.visibleItems.length);
      
      if(_timeline.visibleItemsChanged){
        if(_timeline.visibleItems.length < 4){
          current_view_mode = 3;
        }else if(_timeline.visibleItems.length <= 10){
          current_view_mode = 2;        
        }else if(_timeline.visibleItems.length <= 120){
          current_view_mode = 1;        
        }else{
          current_view_mode = 0;
        }
    
        // 
        for (var i=0, max_len = view_modes.length; i < max_len; i++) {
          if(i == current_view_mode){
            $('body').addClass('view-mode-'+view_modes[i]);
          }else{
            $('body').removeClass('view-mode-'+view_modes[i]);          
          }
        };
        
        _timeline.itemsSizeChanged = true;
      }     
    };
    links.events.addListener(_timeline, 'on-before-stack-events', onBeforeStackEvents);

    function filterDates(){
      // console.log('filterDates');
      var date, tid, filter, active;
      _dates = [];
      _dates_nids = [];
      // console.log('_selected_filters', _selected_filters);
      for(nid in _datas){
        date = _datas[nid];
        active = true;
        
        if(_selected_filters.length){
          for (var i = _selected_filters.length - 1; i >= 0; i--){
            if(array_indexOf(date.tids, _selected_filters[i]) == -1){
               active = false;
               break;
            }
          };
        }
        
        if(active){
          _dates.push(date);
          _dates_nids.push(nid);
        }

      
      }

      updateTimeline();
    };

    function updateTimeline(){
      //console.log('updateTimeline | _dates');//, _dates);
      switchLayout('timeline');
      _timeline.draw(_dates);
      _timeline.setVisibleChartRangeAuto();
      setupDatesLinks();
    };
    
    function zoomToDate(nid){
      var index = array_indexOf(_dates_nids, nid),
          date = _dates[index];
      _timeline.setSelection([{row:index}]);
      _timeline.setVisibleChartRange(date.start, date.start);
    };

    /**
    * filters
    *
    */
    function setFilters(){
      var delta = 0;
      for(title in _filters){
        var $input = $('<input class="search" type="text" value="'+_strings.search+'" key="'+title+'">'),
            $filter = $('<div class="filter">')
                        .addClass(title).addClass('filter-'+delta)
                        .appendTo(_$filters)
                        .append('<div class="list"><ul></ul></div>')
                        .append('<h3 class="title">'+Drupal.settings.perfart.strings[title]+'</h3>')
                        // .append('<h3 class="title">'+title+'</h3>')
                        .append($input)
                        .wrapInner('<div class="filters-selection">')
                        .append('<div class="filters-selected">'),
            $list = $('.list ul', $filter);

        if(title == "peoples"){
          _filters[title].sort(sortFiltersByName);  
          // console.log('_filters[title]',_filters[title]);
        }else{
          _filters[title].sort(sortFilters);  
        }
        
        
        
        for(filter in _filters[title]){
          if(typeof _filters[title][filter]['tid'] !== "undefined"){
            $list.append($('<li class="'+_filters[title][filter]['tid']+'"></li>')
                          .append('<span class="'+_filters[title][filter]['tid']+'">'+_filters[title][filter]['name']+'</span>'));
          }
          
        }
        
        $input
          .bind('focus', clearInput)
          .bind('keydown', onInputKeypressed)
          .bind('valuechanged', filterFiltersList);
        
        $('li', $list)
          .bind('click', onClickAddFilter);
        
        delta++;
      };
      
      $('.list', "#filters").jScrollPane({autoReinitialise:true});      
    };
    
    function sortFiltersByName(a,b) {
      if(typeof a == 'object'){
        // var wordsa = a.name.toLowerCase().match(/^[^\s]+\s([^\s]+)/),
        //     na = wordsa === null ? a.name.toLowerCase() : wordsa[1],
        //     wordsb = b.name.toLowerCase().match(/^[^\s]+\s([^\s]+)/),
        //     nb = wordsb === null ? b.name.toLowerCase() : wordsb[1];

        var na = a.nom ? a.nom : a.name;
        var nb = b.nom ? b.nom : b.name;

        // na = na.toLowerCase();
        na = na.toLowerCase().latinise();
        // nb = nb.toLowerCase();
        nb = nb.toLowerCase().latinise();

        if (na < nb)
           return -1;
        if (na > nb)
          return 1;
      }
      return 0;
    };
    
    function sortFilters(a,b) {
      //console.log('a', a);
      if(typeof a == 'object'){
        var na = a.name.toLowerCase().latinise(),
            nb = b.name.toLowerCase().latinise();

        if (na < nb)
           return -1;
        if (na > nb)
          return 1;  
      }
      
      return 0;
    };

    function clearInput(event){
      var $input = $(this);
      if($input.attr('value') == _strings.search)
        $(this).attr('value', '');
    };
    
    function onInputKeypressed(event) {
      // this setTimeout just serve to retreive the juste added letter
      // without we always have a one char delay on the keypress event
      var $this = $(this);
      setTimeout(function(){ $this.trigger('valuechanged'); },1);
    };
    
    function filterFiltersList(event){
      console.log('filterFiltersList', event);

      var $input = $(this),
          value = $input.val(),
          filtersList = _filters[$input.attr('key')],
          $list = $input.siblings('.list'),
          regexpValue, filter;
      
      clearTimeout(filterInputTimer);
      // prevFilterInput
      if(value != ''){
        filterInputTimer = setTimeout(function(){
          console.log('value = '+value);
          regexpValue = new RegExp(value, 'i');
          for(key in filtersList){
            filter = filtersList[key];
            // console.log('filter', filter);
            if (filter.name.search(regexpValue) == -1){ 
              if(filter.visible){ 
                filter.visible = false;
                $('li.'+filter.tid, $list).height(0);//.slideUp(); 
              }
            }else if(!filter.visible){ 
              filter.visible = true;
              $('li.'+filter.tid, $list).height('auto');//.slideDown(); 
            }
          }
          // $list.jScrollPane();
        }, 500);
      }else{
        // $('li', $list).height('auto'); 
        for(key in filtersList){
          filter = filtersList[key];
          filter.visible = true;
          $('li.'+filter.tid, $list).height('auto');//.slideDown(); 
        }
      }
    };
    
    function onClickAddFilter(event){
      var $this = $(this);
      
      if(!$this.is('.selected')){
        var $clone = $('span', $this).clone(),
            tid = $clone.attr('class');
      
        $this
          .addClass('selected')
          .parents('.filter').find('.filters-selected')
            .append($clone);
        
        $clone.bind('click', onClickRemoveFilter );
        
        var click = jQuery.Event("click");
        click.dontfilterdate = true;
        $('.close-search','#search-block-form').trigger(click);

        _selected_filters.push(tid);
        filterOtherFilters();
        filterDates();
        checkFiltersHeight();
      }
    };
    
    function onClickRemoveFilter(event){
      if(!$('body').is('.layout-timeline'))
        return;

      console.log('onClickRemoveFilter', event);

      var $this = $(this),
          tid = $this.attr('class'),
          dontfilterdate = event.dontfilterdate || false;
          
      $this.parents('.filter').find('.filters-selection').find('li.'+tid).removeClass('selected');
      $this.remove();
      
      setTimeout(function(){
        array_remove(_selected_filters,tid);
        filterOtherFilters();
        checkFiltersHeight();
        if(!dontfilterdate)
          filterDates();
      },5);
    };
    
    function filterOtherFilters(){
      var active, classe;
      $('.filter .filters-selection li:not(.selected)').each(function(){
        active = true;
        classe = $(this).attr('class');
         
        if(_selected_filters.length){ // && array_indexOf(_selected_filters, classe) === -1
          for (var i = _selected_filters.length - 1; i >= 0; i--){
            if(array_indexOf(_filters_correspondances[_selected_filters[i]], classe) == -1){
               active = false;
               break;
            }
          };
        }

        if (!active) {
          $(this).height(0);
        }else{
          $(this).height('auto');
        }

      });
    }

    function checkFiltersHeight(){
      var h = 0;
      $('.filters-selected', '#filters').each(function(i, elmt){
        h = $(elmt).height() > h ? $(elmt).height() : h;
      });
      _$filters.css({marginBottom:(h+5)+'px'});
    };
    
    function resetFilters(fd){
      var click = jQuery.Event("click");
      click.dontfilterdate = true;
      console.log('resetFilters : click', click);
      $('#filters .filters-selected span').trigger(click);
    };

    /**
    * search
    */
    function initSearch(){
      $('#search-block-form').bind('submit', function(event) {
        // console.log('search submited', event);
        var $this = $(this);
        setTimeout(function(){
          var searched_keys = $this.find('input[name*="search_block_form"]').val()
          searchFormSubmit(searched_keys, $this);
        },10);
        return false;
      });
    };

    function searchFormSubmit(typed, $form){
      // console.log('searchFormSubmit | keys = '+keys);
      if(typed !== undefined && typed !== ''  && typed.length >= 2){
        typed = typed.replace('/', ' ');
        $form.addClass('loading');
        // $.getJSON(Drupal.settings.basePath+Drupal.settings.pathPrefix+'perfart/search/', 
        //   {keys:keys},
        //   function(json){
        //     $form.removeClass('loading');
        //     searchFiltreTimeline(json);
        // });
        $.getJSON(Drupal.settings.basePath+Drupal.settings.pathPrefix+'perfart/search_api/', 
          {typed:typed},
          function(json){
            $form.removeClass('loading');
            console.log('json', json);
            searchFiltreTimeline(json);
        });
      }
    };

    function searchFiltreTimeline(json){
      console.log('searchFiltreTimeline | json', json);
      var nid;
      _dates = [];
      _dates_nids = [];
      for(var nid in json['results']){
        // nid = json['results'][ind];
        if(typeof _datas[nid] != 'undefined'){
          _dates.push(_datas[nid]);
          _dates_nids.push(nid); 
        }
      }
      
      resetFilters(false);
      updateTimeline();

      if(!$('.container-inline .close-search', '#search-block-form').size()){
        $('.container-inline','#search-block-form').append($('<span class="close-search">').bind('click', resetSearch));
      }
    };

    function resetSearch(event){
      console.log('resetSearch')
      
      $(event.currentTarget).remove();

      var dontfilterdate = event.dontfilterdate || false;
      
      $('#search-block-form').find('input[name*="search_block_form"]').val('');

      if(dontfilterdate)
        return;

      _dates = [];
      _dates_nids = [];
      // console.log('_selected_filters', _selected_filters);
      for(nid in _datas){
        _dates.push(_datas[nid]);
        _dates_nids.push(nid);
      }
      updateTimeline();
    };

    /**
    * performance view
    */
    function loadPerformance(url){
      _$perfnode.addClass('loading').children('.node');
      $('.node-container .node', _$perfnode).hide();
      clearPerfNav();
      switchLayout('perfnode');
      
      
      // if(url.indexOf("/") === 0){
        url = url.replace(/^\//, '');
      // }

      url = _drupalBasePath + url;

      $.getJSON(url,
       function(json){
         // console.log('json', json);
         showPerformance(json);

         History.pushState({json:json, ajaxpath:url}, _datas[json.nid].perf_title+' | '+_strings.site_name, _drupalBasePath + _datas[json.nid].node_link);

         updateTranslationLink(_datas[json.nid].node_translation);
         
      });
    };
    
    function updateTranslationLink(p){
      if(!updateTranslationLink.homeTranslationLink){
        updateTranslationLink.homeTranslationLink = $('.language-switcher-locale-url li:not(.active) a').attr('href');
      }
      var href = p ? Drupal.settings.basePath + p : updateTranslationLink.homeTranslationLink;
      $('.language-switcher-locale-url li:not(.active) a').attr('href', href);
    }

    function showPerformance(data){
      // console.log('showPerformance', data);
      zoomToDate(data.nid);
      
      var $node_container = $('.node-container', _$perfnode);

      // $('>*', $node_container).remove();
      // $node_container.empty();

      _$perfnode.removeClass('loading');

      $node_container.find('.scroller').html(data.node_view)
        .children('.node').children().addClass('grid-block');
      
      _randomizeImageSizes($('.scroller>.node', $node_container));

      $('.node .node-title', $node_container).after($('.node figure.grid_large', $node_container));
      $('.node .field-type-textauthor', $node_container).children('.field-item').jScrollPane();

      _initPaScPlayer($node_container);

      $node_container.bind('grid_ready', onGridReady);

      _grid = new Grid($node_container, {
        cell_w:50,
        cell_h:50,
        // lines:Math.ceil($node_container.height())/100,
        // columns:Math.ceil($node_container.width())/100,
        padding:{t:0,r:0,b:0,l:0},
        gouttiere: 5,
        grille: false,
        decalage: false,
        latitude: 0,
        augmentable:true
      });
      
      protectImages($node_container);
      
      setPerfNav(data.nid);
      _current_nid = data.nid;
    };
    
    function _randomizeImageSizes($container){
      array_randomize($container.children('figure')).each(function(index) {
        _setImageSize(this, true, index);
      });
      array_randomize($container.children().find('figure')).each(function(index) {
        _setImageSize(this);
      });
    };

    function _setImageSize(figure, c, index){
      var children = c || false,
          style, $remain_img;
      
      $('img:not([path])', figure).each(function(){
        $(this).attr('path', $(this).attr('src'));
      });

      $('img', figure).attr('src', '');

      if(children){
        if(index == 0){       style = 'grid_large';
        }else if (index < 5){ style = 'grid_medium';
        }else{                style = 'grid_small'; }
      }else{
        style = 'grid_medium';
      }
      

      $remain_img = $('img.'+style, figure);
      $remain_img.attr('src', $remain_img.attr('path'));
      $(figure).css({
        'width':$remain_img.attr('width'),
        'height':$remain_img.attr('height')
        })
        .addClass(style);

      $('img:not(.blank,.'+style+')', figure).remove();
    };

    function protectImages($container){
      $('figure', $container)
        // .append('<img class="blank" src="/'+Drupal.settings.perfarttimeline.theme_path+'/images/blank.gif" />')
        .bind("contextmenu", function(e){ alert("Cette image est soumise au droit d'auteur."); return false; })
        .addClass('protected');
    };

    function onGridReady(event){
      //console.log('onGridReady', event);
      // var $node_container = $('.node-container', _$perfnode);
      //console.log('grid max width = '+event.grid.maxwidth+' | grid max height = '+event.grid.maxheight);

      
          // _perf_jsp.destroy();

      $('.node-container',_$perfnode).find('.scroller').height(event.grid.maxheight);

      if(!_perf_jsp){
        var pane = $('.node-container',_$perfnode).jScrollPane({
          verticalGutter:5, 
          autoReinitialise:true
        });
        _perf_jsp = pane.data('jsp');  
      }
    };

    function clearPerfNav(){
      _$prev_perf.attr('url', '');
      _$next_perf.attr('url', '');
    };
    
    function setPerfNav(nid){
      // console.log('nid = '+nid);
      var index = array_indexOf(_dates_nids, nid);
      
      if(typeof _dates_nids[index-1] != 'undefined'){
        _$prev_perf.attr('url', _datas[_dates_nids[index-1]].ajax_link).show();
      }else{
        _$prev_perf.hide();
      }

      if(typeof _dates_nids[index+1] != 'undefined'){
        _$next_perf.attr('url', _datas[_dates_nids[index+1]].ajax_link).show();  
      }else{
        _$next_perf.hide();
      }
    };
    
    function onClickBtnNavPerf(event){
      var url = $(this).attr('url');
      if(url != '')
        loadPerformance(url);
    };

    function nextPerf(){
      if(_current_nid){
        var index = array_indexOf(_dates_nids, _current_nid);
        // console.log('index = '+index);
        loadPerformance(_datas[_dates_nids[index+1]].ajax_link);
      }
    };

    function prevPerf(){
      if(_current_nid){
        var index = array_indexOf(_dates_nids,_current_nid);
        // console.log('index = '+index);
        loadPerformance(_datas[_dates_nids[index-1]].ajax_link);
      }
    };

    /**
    * layout
    */
    function switchLayout(mode){
      //console.log('switchLayout | mode '+mode);

      // if(mode != 'timeline'){
      //   // _timeline.deleteAllItems();
      // }else{
      //   // updateTimeline();
      // }
      
      for (key in _layouts)
        $('body').removeClass(_layouts[key]);
      
      $('body').addClass(_layouts[mode]);
    };
    
		/**
		* Grid()
		*/
		function Grid($f, settings){
			
			var _defaults = {
						padding:{t:20,r:25,b:20,l:25},
		        gouttiere: 20,
		        cell_w: 155,
		        cell_h: 50,
		        lines: 0,
		        columns: 0,
		        grille: false,
		        decalage: false,
		        latitude: 50,
            augmentable:false
	    		},
					$fiche = $f,
	        _cells = new Array(),
		      _positions = new Array(),
					_thisgrid = this,
					_prePlacedBlocks = 0,
					_placedBlocks = 0,
					_allBlocks = 0,
          _grilleInterval;
			
		
			this.fiche = $fiche;
			this.settings = $.extend({}, _defaults, settings);
	    
      this.settings.lines = Math.floor(($f.height() - this.settings.padding.t  - this.settings.padding.b) / (this.settings.cell_h + this.settings.gouttiere));
      this.settings.columns = Math.floor(($f.width() -  - this.settings.padding.r  - this.settings.padding.l) / (this.settings.cell_w + this.settings.gouttiere));

      this.maxheight = this.maxwidth = 0;

      // console.log('w = '+$f.width()+' | h = '+$f.height());
      // console.log('lines = '+this.settings.lines+' | columns = '+this.settings.columns);

			if (this.settings.grille) {
			  $fiche.append('<div class="grille"><div>');
			  $('.grille', $fiche).css({
		      'width': '100%',
		      'height': '100%',
		      'position': 'relative'
			  });
			}
			
      for (var l = 0; l < this.settings.lines; l++) {
	      _cells[l] = new Array();
	      for (var c = 0; c < this.settings.columns; c++) {
	        _cells[l][c] = new Cell(this, c, l);
	      };
      };
			
			_allBlocks = $('.grid-block', $fiche).length;
			if (this.settings.grille) {
				_grilleInterval = setInterval(function(){
					if(_prePlacedBlocks < _allBlocks){
						_placeBlock($('.grid-block', $fiche).eq(_prePlacedBlocks));
						_prePlacedBlocks ++;
					}else{
            clearInterval(_grilleInterval);
          }
				},1000);
			}else{
	      $('.grid-block', $fiche).each(function() {
					// _allBlocks++;		
					_placeBlock(this);
				});
			}
			
			
			function _block_placed(){
				// console.log('_block_placed _allBlocks = '+_allBlocks+' _placedBlocks = '+_placedBlocks)
				_placedBlocks++;
				if(_placedBlocks == _allBlocks){
          var event = jQuery.Event('grid_ready');
          event.grid = _thisgrid;
          $fiche.trigger(event);
        }
					
			}
			
			/**
			*
			*/
			function _placeBlock(_this){
        //console.log('_placeBlock', _this);
	
	      var $this = $(_this),
						this_cells_w = 0,
	      		this_cells_h = 0,
						free_cells = [];

        // if($this.hasClass('image')){
        //  var sizes     = [155, 330, 505],
        //      i         = sizes.length,
        //      $img      = $('img', $this),
        //      $legende  = $('.legende', $this);
        // 
        //  while(free_cells.length == 0 && i > 0){
        //    i--;
        //    $img.width(sizes[i]);
        //    $this.width(sizes[i]+$legende.outerWidth()+2);
        //    this_cells_w = Math.ceil($this.width() / (_thisgrid.settings.cell_w + _thisgrid.settings.gouttiere)),
        //    this_cells_h = Math.ceil($this.height() / (_thisgrid.settings.cell_h + _thisgrid.settings.gouttiere));
        //    free_cells = getFreeCells(this_cells_w, this_cells_h);
        //  }
        // }else{
					this_cells_w = Math.ceil($this.width() / (_thisgrid.settings.cell_w + _thisgrid.settings.gouttiere)),
		      this_cells_h = Math.ceil($this.height() / (_thisgrid.settings.cell_h + _thisgrid.settings.gouttiere));
					free_cells = getFreeCells(this_cells_w, this_cells_h);
        // }

				if(free_cells.length > 0){

	        // var cell_num = Math.round(Math.random() * (free_cells.length - 1));
	        // var cell_num = 0;
					var cell_num = Math.floor((free_cells.length-1)*0.5 + (-2+Math.random()*4));
					cell_num = cell_num > free_cells.length-1 ? free_cells.length-1 : ( cell_num < 0 ? 0 : cell_num );

					var cell = free_cells[cell_num],
							line_limit_loop = cell.getPos().l + (this_cells_h),
							column_limit_loop = cell.getPos().c + (this_cells_w);

	        for (var l = cell.getPos().l; l < line_limit_loop; l++) {
	            for (var c = cell.getPos().c; c < column_limit_loop; c++) {
	                var temp_cell = _cells[l][c];
	                temp_cell.setFull();
	            };
	        };

	        var top = cell.getPos().l * (_thisgrid.settings.cell_h + _thisgrid.settings.gouttiere),
							left = cell.getPos().c * (_thisgrid.settings.cell_w + _thisgrid.settings.gouttiere),
							latitude = _thisgrid.settings.latitude;

					top = !_thisgrid.settings.decalage ? top: top + Math.round(Math.random() * latitude - latitude / 2)
					left = !_thisgrid.settings.decalage ? left: left + Math.round(Math.random() * latitude - latitude / 2);

	        $this.css({
	            'top': top+_thisgrid.settings.padding.t,
	            'left': left+_thisgrid.settings.padding.l
	        });

          _thisgrid.maxheight = Math.max(top+_thisgrid.settings.padding.t+$this.height(), _thisgrid.maxheight);
          _thisgrid.maxwidth = Math.max(left+_thisgrid.settings.padding.l+$this.width(), _thisgrid.maxwidth);

          _block_placed();

        } else {
		       
          if(!_thisgrid.settings.augmentable){
            $this.css({
              'border': '2px solid red',
              'opacity': 0.2
            }).remove();
            _block_placed();
          }else{
            _augmenteGrid();
            //console.log('re placeblock');
            _placeBlock(_this);
          }

       	}

			}
			
      function _augmenteGrid(){

        // for (var l = 0; l < this.settings.lines; l++) {
          var l = _thisgrid.settings.lines ;
          _thisgrid.settings.lines ++;
          _cells[l] = new Array();
          for (var c = 0; c < _thisgrid.settings.columns; c++) {
            _cells[l][c] = new Cell(_thisgrid, c, l);
          };
        // };
        _refreshCells();

        // console.log('lines = '+_thisgrid.settings.lines+' | columns = '+_thisgrid.settings.columns);
      };
			
      function _refreshCells(){
        for (var l = _thisgrid.settings.lines-1; l >= 0 ; l--) {
          for (var c = _thisgrid.settings.columns-1; c >= 0 ; c--) {
            _cells[l][c].refresh();
          }
        }
      }

			/**
			* getFreeCells()
			*/
			function getFreeCells(this_cells_w, this_cells_h){
				var free_cells = new Array();
				for (var l = 0; l < _thisgrid.settings.lines; l++) {
					for (var c = 0; c < _thisgrid.settings.columns; c++) {
						var cell = _cells[l][c];
						if (cell.isFree() && (cell.getAround().right + 1) >= this_cells_w && (cell.getAround().bottom + 1) >= this_cells_h) {
							var good = true;
							for (var i = 1; i < this_cells_w; i++) {
								var temp_cell = _cells[l][c + i];
								if ((temp_cell.getAround().bottom + 1) < this_cells_h) {
									good = false;
									break;
								}
							};
							if (good) free_cells.push(cell);
						}
					};
				};
								
				return free_cells;
			}
			
			/**
			* Cell()
			*/
	  	function Cell(g, c, l) {
	      var _g = g,
						_column = c,
			      _line = l,
			      _free = true,
			      _free_cell_right = _g.settings.columns - 1 - c,
			      _free_cell_bottom = _g.settings.lines - 1 - l;

	      if (_g.settings.grille) {
	          var _table = '<table>';
	          _table += '<tr><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td></tr>';
	          // _table += '<tr><td>&nbsp;</td><td class="state">'+_free+'</td><td class="fr">'+_free_cell_right+'</td></tr>';
	          _table += '<tr><td>&nbsp;</td><td>&nbsp;</td><td class="fr">' + _free_cell_right + '</td></tr>';
	          _table += '<tr><td>&nbsp;</td><td class="fb">' + _free_cell_bottom + '</td><td>&nbsp;</td></tr>';
	          _table += '</table>';
	          _g.fiche.find('.grille').append('<div class="cell-' + l + '-' + c + '">' + _table + '<div>');
	          var _dom = $('.cell-' + l + '-' + c, _g.fiche.find('.grille'));
	          _dom.css({
	              'position': 'absolute',
	              'top': _line * (_g.settings.cell_h + _g.settings.gouttiere) + _g.settings.padding.t,
	              'left': _column * (_g.settings.cell_w + _g.settings.gouttiere) + _g.settings.padding.l,
	              'width': _g.settings.cell_w,
	              'height': _g.settings.cell_h,
	              'backgroundColor': '#00FF00',
	              'opacity': 0.6
	          }).find('table').css({
              width:'100%',
              height:'100%'
            }).find('td').css({width:"30%"});
	          // $('td', _dom).css({
	          //     'fontSize': '8px'
	          // });
	      }

	      this.isFree = function() {
	          return _free;
	      };

	      this.getPos = function() {
	          return {
	              c: _column,
	              l: _line
	          };
	      };

	      this.getAround = function() {
	          return {
	              right: _free_cell_right,
	              bottom: _free_cell_bottom
	          };
	      };

	      this.setFull = function() {

	          _free = false;
	          _free_cell_bottom = -1;
	          _free_cell_right = -1;

	          if (_g.settings.grille) {
	              _dom.css({
	                  'backgroundColor': '#0000FF'
	              });
	              $('.fb', _dom).html(_free_cell_bottom);
	              $('.fr', _dom).html(_free_cell_right);
	          }

	          _propageFreeCells();
	      };

	      this.setFreeCellsRight = function(right) {
	          if (_free) {
	              // console.log('_setFreeCellRigth | _free_cell_right = ' + _free_cell_right + ' | new right = ' + right);
	              _free_cell_right = right;
	              if (_g.settings.grille) $('.fr', _dom).html(_free_cell_right);
	              _propageFreeCellsLeft();
	          }
	      };

	      this.setFreeCellsBottom = function(bottom) {
	          if (_free) {
	              // console.log('_setFreeCellsBottom | _free_cell_bottom = ' + _free_cell_bottom + ' | new right = ' + bottom);
	              _free_cell_bottom = bottom;
	              if (_g.settings.grille) $('.fb', _dom).html(_free_cell_bottom);
	              _propageFreeCellsTop();
	          }
	      };

        this.refresh = function(){
          if(_free)
            _propageFreeCellsTop();
        };

	      function _propageFreeCells() {
	          // console.log('_propageFreeCells');
	          _propageFreeCellsLeft();
	          _propageFreeCellsTop();
	      };

	      function _propageFreeCellsLeft() {
	          // console.log('_propageFreeCellsLeft | _column = '+_column);
	          if (_column > 0) {
	              var left_cel = _cells[_line][_column - 1];
	              left_cel.setFreeCellsRight(_free_cell_right + 1);
	          }
	      };

	      function _propageFreeCellsTop() {
	          // console.log('_propageFreeCellsTop | _line = '+_line);
	          if (_line > 0) {
	              var top_cel = _cells[_line - 1][_column];
	              top_cel.setFreeCellsBottom(_free_cell_bottom + 1);
	          }
	      };

	      if (typeof Cell.initialized == "undefined") {
	          Cell.prototype.infos = function() {
	              //console.log('cell | column = ' + this.getPos().c + ', line = ' + this.getPos().l + ', free = ' + this.isFree() + ', free cell right = ' + this.getAround().right + ', free cell bottom = ' + this.getAround().bottom);
	          };

	          Cell.initialized = true;
	      }
	  	}; // cell()
			
			this.clear = function(){
				$('.grille', $fiche).fadeOut(200, function() {
					$(this).remove();
				});
				
			}
		}; // GRIB
		
		/**
    * on resize
    */
    // debulked onresize handler
    function on_resize(c,t){onresize=function(){clearTimeout(t);t=setTimeout(c,100)};return c};
    on_resize(function() { if(typeof _timeline != 'undefined') _timeline.redraw(); });
    
    /** 
  	* cookies 
  	*/
  	function createCookie(name,value,days) {
  		if (days) {
  			var date = new Date();
  			date.setTime(date.getTime()+(days*24*60*60*1000));
  			var expires = "; expires="+date.toGMTString();
  		}
  		else var expires = "";
  		document.cookie = name+"="+value+expires+"; path=/";
  	}

  	function readCookie(name) {
  		var nameEQ = name + "=";
  		var ca = document.cookie.split(';');
  		for(var i=0;i < ca.length;i++) {
  			var c = ca[i];
  			while (c.charAt(0)==' ') c = c.substring(1,c.length);
  			if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
  		}
  		return null;
  	}

  	function eraseCookie(name) {
  		createCookie(name,"",-1);
  	}

    /**
    * init
    */
    init();
  }

  function _initPaScPlayer($container, ap){
    var $container = $container || $('body');
    var ap = ap || false;
    // console.log('_initPaScPlayer');
    $.paScPlayer.stopAll();
    var $links = $('a[rel="soundcloud"]', $container);
    // console.log('$links', $links);
    if($links.size()){
      $links.parents('.field-item').find('span.ext').remove();
      $links.paScPlayer({autoplay:ap});
    }
  }

  _initPaScPlayer();
};

$.fn.verticalcenter = function(){
  return this.each(function(index) {
    $(this).css({
      "margin-top": ($(this).parent().height() - $(this).height()) / 2
    });
  });
};

$.fn.innerheight = function(){
  var h = 0;

  this.chlidren().each(function(index) {
    h = h + $(this).height() + parseInt($(this).css('margin-top')) + parseInt($(this).css('margin-bottom')) + parseInt($(this).css('padding-top')) + parseInt($(this).css('padding-bottom'))
  });

  return h;
};

})(jQuery);

/** HELPERS */

/**  
* returned value: (Array)
*/
array_remove= function(ar){
    var what, a= arguments, L= a.length, ax;
    while(L && ar.length){
        what= a[--L];
        while((ax= ar.indexOf(what))!= -1){
            ar.splice(ax, 1);
        }
    }
    return ar;
};

array_indexOf = function(ar, what, i){
    i= i || 0;
    var L= ar.length;
    while(i< L){
        if(ar[i]=== what) return i;
        ++i;
    }
    return -1;
};

array_randomize = function(arr) {
  for(var j, x, i = arr.length; i; j = parseInt(Math.random() * i), x = arr[--i], arr[i] = arr[j], arr[j] = x);
  return arr;
};

function objectIsEmpty(obj){
  for (var prop in obj) {
    if (obj.hasOwnProperty(prop))
      return false;
  };

  return true;
}

var Latinise={};Latinise.latin_map={"Á":"A","Ă":"A","Ắ":"A","Ặ":"A","Ằ":"A","Ẳ":"A","Ẵ":"A","Ǎ":"A","Â":"A","Ấ":"A","Ậ":"A","Ầ":"A","Ẩ":"A","Ẫ":"A","Ä":"A","Ǟ":"A","Ȧ":"A","Ǡ":"A","Ạ":"A","Ȁ":"A","À":"A","Ả":"A","Ȃ":"A","Ā":"A","Ą":"A","Å":"A","Ǻ":"A","Ḁ":"A","Ⱥ":"A","Ã":"A","Ꜳ":"AA","Æ":"AE","Ǽ":"AE","Ǣ":"AE","Ꜵ":"AO","Ꜷ":"AU","Ꜹ":"AV","Ꜻ":"AV","Ꜽ":"AY","Ḃ":"B","Ḅ":"B","Ɓ":"B","Ḇ":"B","Ƀ":"B","Ƃ":"B","Ć":"C","Č":"C","Ç":"C","Ḉ":"C","Ĉ":"C","Ċ":"C","Ƈ":"C","Ȼ":"C","Ď":"D","Ḑ":"D","Ḓ":"D","Ḋ":"D","Ḍ":"D","Ɗ":"D","Ḏ":"D","ǲ":"D","ǅ":"D","Đ":"D","Ƌ":"D","Ǳ":"DZ","Ǆ":"DZ","É":"E","Ĕ":"E","Ě":"E","Ȩ":"E","Ḝ":"E","Ê":"E","Ế":"E","Ệ":"E","Ề":"E","Ể":"E","Ễ":"E","Ḙ":"E","Ë":"E","Ė":"E","Ẹ":"E","Ȅ":"E","È":"E","Ẻ":"E","Ȇ":"E","Ē":"E","Ḗ":"E","Ḕ":"E","Ę":"E","Ɇ":"E","Ẽ":"E","Ḛ":"E","Ꝫ":"ET","Ḟ":"F","Ƒ":"F","Ǵ":"G","Ğ":"G","Ǧ":"G","Ģ":"G","Ĝ":"G","Ġ":"G","Ɠ":"G","Ḡ":"G","Ǥ":"G","Ḫ":"H","Ȟ":"H","Ḩ":"H","Ĥ":"H","Ⱨ":"H","Ḧ":"H","Ḣ":"H","Ḥ":"H","Ħ":"H","Í":"I","Ĭ":"I","Ǐ":"I","Î":"I","Ï":"I","Ḯ":"I","İ":"I","Ị":"I","Ȉ":"I","Ì":"I","Ỉ":"I","Ȋ":"I","Ī":"I","Į":"I","Ɨ":"I","Ĩ":"I","Ḭ":"I","Ꝺ":"D","Ꝼ":"F","Ᵹ":"G","Ꞃ":"R","Ꞅ":"S","Ꞇ":"T","Ꝭ":"IS","Ĵ":"J","Ɉ":"J","Ḱ":"K","Ǩ":"K","Ķ":"K","Ⱪ":"K","Ꝃ":"K","Ḳ":"K","Ƙ":"K","Ḵ":"K","Ꝁ":"K","Ꝅ":"K","Ĺ":"L","Ƚ":"L","Ľ":"L","Ļ":"L","Ḽ":"L","Ḷ":"L","Ḹ":"L","Ⱡ":"L","Ꝉ":"L","Ḻ":"L","Ŀ":"L","Ɫ":"L","ǈ":"L","Ł":"L","Ǉ":"LJ","Ḿ":"M","Ṁ":"M","Ṃ":"M","Ɱ":"M","Ń":"N","Ň":"N","Ņ":"N","Ṋ":"N","Ṅ":"N","Ṇ":"N","Ǹ":"N","Ɲ":"N","Ṉ":"N","Ƞ":"N","ǋ":"N","Ñ":"N","Ǌ":"NJ","Ó":"O","Ŏ":"O","Ǒ":"O","Ô":"O","Ố":"O","Ộ":"O","Ồ":"O","Ổ":"O","Ỗ":"O","Ö":"O","Ȫ":"O","Ȯ":"O","Ȱ":"O","Ọ":"O","Ő":"O","Ȍ":"O","Ò":"O","Ỏ":"O","Ơ":"O","Ớ":"O","Ợ":"O","Ờ":"O","Ở":"O","Ỡ":"O","Ȏ":"O","Ꝋ":"O","Ꝍ":"O","Ō":"O","Ṓ":"O","Ṑ":"O","Ɵ":"O","Ǫ":"O","Ǭ":"O","Ø":"O","Ǿ":"O","Õ":"O","Ṍ":"O","Ṏ":"O","Ȭ":"O","Ƣ":"OI","Ꝏ":"OO","Ɛ":"E","Ɔ":"O","Ȣ":"OU","Ṕ":"P","Ṗ":"P","Ꝓ":"P","Ƥ":"P","Ꝕ":"P","Ᵽ":"P","Ꝑ":"P","Ꝙ":"Q","Ꝗ":"Q","Ŕ":"R","Ř":"R","Ŗ":"R","Ṙ":"R","Ṛ":"R","Ṝ":"R","Ȑ":"R","Ȓ":"R","Ṟ":"R","Ɍ":"R","Ɽ":"R","Ꜿ":"C","Ǝ":"E","Ś":"S","Ṥ":"S","Š":"S","Ṧ":"S","Ş":"S","Ŝ":"S","Ș":"S","Ṡ":"S","Ṣ":"S","Ṩ":"S","Ť":"T","Ţ":"T","Ṱ":"T","Ț":"T","Ⱦ":"T","Ṫ":"T","Ṭ":"T","Ƭ":"T","Ṯ":"T","Ʈ":"T","Ŧ":"T","Ɐ":"A","Ꞁ":"L","Ɯ":"M","Ʌ":"V","Ꜩ":"TZ","Ú":"U","Ŭ":"U","Ǔ":"U","Û":"U","Ṷ":"U","Ü":"U","Ǘ":"U","Ǚ":"U","Ǜ":"U","Ǖ":"U","Ṳ":"U","Ụ":"U","Ű":"U","Ȕ":"U","Ù":"U","Ủ":"U","Ư":"U","Ứ":"U","Ự":"U","Ừ":"U","Ử":"U","Ữ":"U","Ȗ":"U","Ū":"U","Ṻ":"U","Ų":"U","Ů":"U","Ũ":"U","Ṹ":"U","Ṵ":"U","Ꝟ":"V","Ṿ":"V","Ʋ":"V","Ṽ":"V","Ꝡ":"VY","Ẃ":"W","Ŵ":"W","Ẅ":"W","Ẇ":"W","Ẉ":"W","Ẁ":"W","Ⱳ":"W","Ẍ":"X","Ẋ":"X","Ý":"Y","Ŷ":"Y","Ÿ":"Y","Ẏ":"Y","Ỵ":"Y","Ỳ":"Y","Ƴ":"Y","Ỷ":"Y","Ỿ":"Y","Ȳ":"Y","Ɏ":"Y","Ỹ":"Y","Ź":"Z","Ž":"Z","Ẑ":"Z","Ⱬ":"Z","Ż":"Z","Ẓ":"Z","Ȥ":"Z","Ẕ":"Z","Ƶ":"Z","Ĳ":"IJ","Œ":"OE","ᴀ":"A","ᴁ":"AE","ʙ":"B","ᴃ":"B","ᴄ":"C","ᴅ":"D","ᴇ":"E","ꜰ":"F","ɢ":"G","ʛ":"G","ʜ":"H","ɪ":"I","ʁ":"R","ᴊ":"J","ᴋ":"K","ʟ":"L","ᴌ":"L","ᴍ":"M","ɴ":"N","ᴏ":"O","ɶ":"OE","ᴐ":"O","ᴕ":"OU","ᴘ":"P","ʀ":"R","ᴎ":"N","ᴙ":"R","ꜱ":"S","ᴛ":"T","ⱻ":"E","ᴚ":"R","ᴜ":"U","ᴠ":"V","ᴡ":"W","ʏ":"Y","ᴢ":"Z","á":"a","ă":"a","ắ":"a","ặ":"a","ằ":"a","ẳ":"a","ẵ":"a","ǎ":"a","â":"a","ấ":"a","ậ":"a","ầ":"a","ẩ":"a","ẫ":"a","ä":"a","ǟ":"a","ȧ":"a","ǡ":"a","ạ":"a","ȁ":"a","à":"a","ả":"a","ȃ":"a","ā":"a","ą":"a","ᶏ":"a","ẚ":"a","å":"a","ǻ":"a","ḁ":"a","ⱥ":"a","ã":"a","ꜳ":"aa","æ":"ae","ǽ":"ae","ǣ":"ae","ꜵ":"ao","ꜷ":"au","ꜹ":"av","ꜻ":"av","ꜽ":"ay","ḃ":"b","ḅ":"b","ɓ":"b","ḇ":"b","ᵬ":"b","ᶀ":"b","ƀ":"b","ƃ":"b","ɵ":"o","ć":"c","č":"c","ç":"c","ḉ":"c","ĉ":"c","ɕ":"c","ċ":"c","ƈ":"c","ȼ":"c","ď":"d","ḑ":"d","ḓ":"d","ȡ":"d","ḋ":"d","ḍ":"d","ɗ":"d","ᶑ":"d","ḏ":"d","ᵭ":"d","ᶁ":"d","đ":"d","ɖ":"d","ƌ":"d","ı":"i","ȷ":"j","ɟ":"j","ʄ":"j","ǳ":"dz","ǆ":"dz","é":"e","ĕ":"e","ě":"e","ȩ":"e","ḝ":"e","ê":"e","ế":"e","ệ":"e","ề":"e","ể":"e","ễ":"e","ḙ":"e","ë":"e","ė":"e","ẹ":"e","ȅ":"e","è":"e","ẻ":"e","ȇ":"e","ē":"e","ḗ":"e","ḕ":"e","ⱸ":"e","ę":"e","ᶒ":"e","ɇ":"e","ẽ":"e","ḛ":"e","ꝫ":"et","ḟ":"f","ƒ":"f","ᵮ":"f","ᶂ":"f","ǵ":"g","ğ":"g","ǧ":"g","ģ":"g","ĝ":"g","ġ":"g","ɠ":"g","ḡ":"g","ᶃ":"g","ǥ":"g","ḫ":"h","ȟ":"h","ḩ":"h","ĥ":"h","ⱨ":"h","ḧ":"h","ḣ":"h","ḥ":"h","ɦ":"h","ẖ":"h","ħ":"h","ƕ":"hv","í":"i","ĭ":"i","ǐ":"i","î":"i","ï":"i","ḯ":"i","ị":"i","ȉ":"i","ì":"i","ỉ":"i","ȋ":"i","ī":"i","į":"i","ᶖ":"i","ɨ":"i","ĩ":"i","ḭ":"i","ꝺ":"d","ꝼ":"f","ᵹ":"g","ꞃ":"r","ꞅ":"s","ꞇ":"t","ꝭ":"is","ǰ":"j","ĵ":"j","ʝ":"j","ɉ":"j","ḱ":"k","ǩ":"k","ķ":"k","ⱪ":"k","ꝃ":"k","ḳ":"k","ƙ":"k","ḵ":"k","ᶄ":"k","ꝁ":"k","ꝅ":"k","ĺ":"l","ƚ":"l","ɬ":"l","ľ":"l","ļ":"l","ḽ":"l","ȴ":"l","ḷ":"l","ḹ":"l","ⱡ":"l","ꝉ":"l","ḻ":"l","ŀ":"l","ɫ":"l","ᶅ":"l","ɭ":"l","ł":"l","ǉ":"lj","ſ":"s","ẜ":"s","ẛ":"s","ẝ":"s","ḿ":"m","ṁ":"m","ṃ":"m","ɱ":"m","ᵯ":"m","ᶆ":"m","ń":"n","ň":"n","ņ":"n","ṋ":"n","ȵ":"n","ṅ":"n","ṇ":"n","ǹ":"n","ɲ":"n","ṉ":"n","ƞ":"n","ᵰ":"n","ᶇ":"n","ɳ":"n","ñ":"n","ǌ":"nj","ó":"o","ŏ":"o","ǒ":"o","ô":"o","ố":"o","ộ":"o","ồ":"o","ổ":"o","ỗ":"o","ö":"o","ȫ":"o","ȯ":"o","ȱ":"o","ọ":"o","ő":"o","ȍ":"o","ò":"o","ỏ":"o","ơ":"o","ớ":"o","ợ":"o","ờ":"o","ở":"o","ỡ":"o","ȏ":"o","ꝋ":"o","ꝍ":"o","ⱺ":"o","ō":"o","ṓ":"o","ṑ":"o","ǫ":"o","ǭ":"o","ø":"o","ǿ":"o","õ":"o","ṍ":"o","ṏ":"o","ȭ":"o","ƣ":"oi","ꝏ":"oo","ɛ":"e","ᶓ":"e","ɔ":"o","ᶗ":"o","ȣ":"ou","ṕ":"p","ṗ":"p","ꝓ":"p","ƥ":"p","ᵱ":"p","ᶈ":"p","ꝕ":"p","ᵽ":"p","ꝑ":"p","ꝙ":"q","ʠ":"q","ɋ":"q","ꝗ":"q","ŕ":"r","ř":"r","ŗ":"r","ṙ":"r","ṛ":"r","ṝ":"r","ȑ":"r","ɾ":"r","ᵳ":"r","ȓ":"r","ṟ":"r","ɼ":"r","ᵲ":"r","ᶉ":"r","ɍ":"r","ɽ":"r","ↄ":"c","ꜿ":"c","ɘ":"e","ɿ":"r","ś":"s","ṥ":"s","š":"s","ṧ":"s","ş":"s","ŝ":"s","ș":"s","ṡ":"s","ṣ":"s","ṩ":"s","ʂ":"s","ᵴ":"s","ᶊ":"s","ȿ":"s","ɡ":"g","ᴑ":"o","ᴓ":"o","ᴝ":"u","ť":"t","ţ":"t","ṱ":"t","ț":"t","ȶ":"t","ẗ":"t","ⱦ":"t","ṫ":"t","ṭ":"t","ƭ":"t","ṯ":"t","ᵵ":"t","ƫ":"t","ʈ":"t","ŧ":"t","ᵺ":"th","ɐ":"a","ᴂ":"ae","ǝ":"e","ᵷ":"g","ɥ":"h","ʮ":"h","ʯ":"h","ᴉ":"i","ʞ":"k","ꞁ":"l","ɯ":"m","ɰ":"m","ᴔ":"oe","ɹ":"r","ɻ":"r","ɺ":"r","ⱹ":"r","ʇ":"t","ʌ":"v","ʍ":"w","ʎ":"y","ꜩ":"tz","ú":"u","ŭ":"u","ǔ":"u","û":"u","ṷ":"u","ü":"u","ǘ":"u","ǚ":"u","ǜ":"u","ǖ":"u","ṳ":"u","ụ":"u","ű":"u","ȕ":"u","ù":"u","ủ":"u","ư":"u","ứ":"u","ự":"u","ừ":"u","ử":"u","ữ":"u","ȗ":"u","ū":"u","ṻ":"u","ų":"u","ᶙ":"u","ů":"u","ũ":"u","ṹ":"u","ṵ":"u","ᵫ":"ue","ꝸ":"um","ⱴ":"v","ꝟ":"v","ṿ":"v","ʋ":"v","ᶌ":"v","ⱱ":"v","ṽ":"v","ꝡ":"vy","ẃ":"w","ŵ":"w","ẅ":"w","ẇ":"w","ẉ":"w","ẁ":"w","ⱳ":"w","ẘ":"w","ẍ":"x","ẋ":"x","ᶍ":"x","ý":"y","ŷ":"y","ÿ":"y","ẏ":"y","ỵ":"y","ỳ":"y","ƴ":"y","ỷ":"y","ỿ":"y","ȳ":"y","ẙ":"y","ɏ":"y","ỹ":"y","ź":"z","ž":"z","ẑ":"z","ʑ":"z","ⱬ":"z","ż":"z","ẓ":"z","ȥ":"z","ẕ":"z","ᵶ":"z","ᶎ":"z","ʐ":"z","ƶ":"z","ɀ":"z","ﬀ":"ff","ﬃ":"ffi","ﬄ":"ffl","ﬁ":"fi","ﬂ":"fl","ĳ":"ij","œ":"oe","ﬆ":"st","ₐ":"a","ₑ":"e","ᵢ":"i","ⱼ":"j","ₒ":"o","ᵣ":"r","ᵤ":"u","ᵥ":"v","ₓ":"x"};
String.prototype.latinise=function(){return this.replace(/[^A-Za-z0-9\[\] ]/g,function(a){return Latinise.latin_map[a]||a})};
String.prototype.latinize=String.prototype.latinise;
String.prototype.isLatin=function(){return this==this.latinise()}
