
Drupal.behaviors.init_theme = 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');
        });
      }
    });
};

jQuery(document).ready(function($) {
  console.log('Hello Jee');

  var $header = $("#header"),
        $chapitres = $('.node-chapitre', '#main'),
        chapitres_len = $chapitres.length,
        $container = $('#main'),
        centerX = $container.width()/2,
        centerY = $container.height()/2,
        // radius = Math.min($container.width(), $container.height())/2.5,
        // angle = Math.random() * 360,

        // is_dragging = false,
        nav_pos = {x:0, y:0},
        nav_timer;

  function init(){
    placeChapters();
    launchNav();
  };

  function placeChapters(){
    // Place each chapters on the ellipse contained on the screen
    var w2, h2, angle, c, s, radius, x, y, a = Math.random() *360;
    $chapitres.each(function(i, e) {

      w2 = $(e).outerWidth(true)/2;
      h2 = $(e).outerHeight(true)/2;

      angle = (360/chapitres_len*i+a)*Math.PI/180;
      // angle = randB(angle*0.95, angle*1.05);

      c = Math.abs(Math.cos(angle));
      s = Math.abs(Math.sin(angle));

      if (c * $container.height() > s * $container.width()) { // It crosses left or right side
          radius = (($container.width()/2) / c)*0.5;
      }else { // Top or bottom side
          radius = (($container.height()/2) / s)*0.5;
      }

      // change randomly radius
      radius = randB(radius, radius*2);

      x = Math.round(centerX+radius *  Math.cos(angle));
      y = Math.round(centerY+radius * -Math.sin(angle));

      $(e).css({
        left:x-w2,
        top:y-h2
      });
    });
  };

  function launchNav(){
    var last_clientX,
          last_clientY,
          td;

    $(document)
      // DESKTOP EVENTS
      .bind('mousedown', function(e){
        last_clientX = e.clientX;
        last_clientY = e.clientY;

         $chapitres.each(function(i, e) {
            td = randB(0.1, 0.3);//Math.random() * (0.3 - 0.1) + 0.1;
            $(e).css({"transitionDuration":td+"s"});
        });

        nav_timer = setInterval(moveNav, 1000/24);

        $(this).bind('mousemove', function(e){
          nav_pos.x += e.clientX - last_clientX;
          nav_pos.y += e.clientY - last_clientY;
          last_clientX = e.clientX;
          last_clientY = e.clientY;
        });
      })
      .bind('mouseup', function(e){
        clearInterval(nav_timer);
        $(this).unbind('mousemove');
      })
      //
      // TOUCH EVENTS - - - - - - - - - - - - - -
      //
      .bind('touchstart', function(e){
          // console.log('touchstart', e);
          last_clientX = e.originalEvent.touches[0].clientX;
          last_clientY = e.originalEvent.touches[0].clientY;

         $chapitres.each(function(i, e) {
            td = randB(0.1, 0.3); //Math.random() * (0.3 - 0.1) + 0.1;
            $(e).css({"transitionDuration":td+"s"});
          });

          nav_timer = setInterval(moveNav, 1000/12);
      })
      .bind('touchmove', function(e){
          // console.log('touchmove', e);
          nav_pos.x += e.originalEvent.touches[0].clientX - last_clientX;
          nav_pos.y += e.originalEvent.touches[0].clientY - last_clientY;
          last_clientX = e.originalEvent.touches[0].clientX;
          last_clientY = e.originalEvent.touches[0].clientY;
      })
      .bind('touchend', function(e){
        // console.log("touchend", e);
        clearInterval(nav_timer);
      });

    // click to preview chapter
    $('h2.node-title, .field-name-field-partie:first>.field-name-field-vignette', $chapitres).bind('click', previewChapter);

    $('.links a', $chapitres).on('click', openChapter);
  };

  function moveNav(){
    // console.log("moveNav");
    $chapitres.each(function(i, e){
      $(e).stop(true, false).css({
        translate:[nav_pos.x, nav_pos.y]
      });
      // $(e).transition({translate:[nav_pos.x, nav_pos.y]}, 200, 'out');
    });
    $header.stop(true, false).css({
      translate:[nav_pos.x*0.2, nav_pos.y*0.2]
      // WebkitTransform:'translate('+nav_pos.x*0.2+', '+nav_pos.y*0.2+')'
    });
  };

  var $chapt, $parties, px, py;
  function previewChapter(e){
    e.preventDefault();
    // console.log('hello', this);

    $chapt = $(this).parents('.node-chapitre');

    closePreview($chapt);

    $parties = $('.field-name-field-partie', $chapt);
    $parties.each(function(i, e) {
      switch(i){
        case 0:
          px=randB(-40, 40); py=randB(40, 60);
        break;
        case 1:
          px=randB(100, 200); py=randB(120,220);
        break;
        case 2:
          px=randB(-200, -100); py=randB(250,320);
        break;
        case 3:
          px=randB(-100, 100); py=randB(320,350)+100;
        break;
      }
      setTimeout(
        (function($chapt, $part, px, py){
          $part
            .css({
              translate:[px, py],
              // opacity:1
            });

          // console.log('part', $part);
          // console.log('part left', $part.height());

        })($chapt, $(e), px, py),10);
    }); // each $parties

    $chapt.addClass('previewed');
    return false;
  }; // previewChapter

  function closePreview($active){
    $chapitres
      .filter('.previewed').not($active)
      .removeClass('previewed')
        .find('.field-name-field-partie')
        .css({transform:"none"});
  }; // closePreview

  var nid;
  function openChapter(e){
    e.preventDefault();
    nid = $(this).attr("href").match(/^\/node\/(\d+)/);
    console.log(nid);
    $.getJSON(
      '/jee/chapter/'+nid[1],
      {},
      displayChapter
    );

    return false;
  }; // openChapter

  var $chapterwrapper;
  function displayChapter(json, textStatus) {
    $chapterwrapper = $('<div>').addClass('chapter-wrapper').append(json.node).appendTo($container);
    // $chapterwrapper.append(json.node);

    console.log('displayChapter :: json', json);

    console.log('displayChapter :: chapterwrapper', $chapterwrapper);
  }; //displayChapter


  /* HELPERS */
  function randB(min, max){
    return Math.random() * (max - min) + min;
  }


  init();
});