$(document).ready(function() {

  /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
   *  BEGIN DECLARATIONS OF VARS                               *
   * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

  // utility functions
  var dskOpenArticle = function(e,u) {

    $(document).off('click', '.front.no-mobile.gt-768 #articles a#prev, .front.no-mobile.gt-768 #articles a#next', dskBtnClk);

    //console.log( e + ' >> ' + u )

    if(  $('section[rel="' + e + '"]').hasClass('first') ) 
      { hideBtnPrev(e); }
    else
      { showBtnPrev(e); }

    if(  $('section[rel="' + e + '"]').hasClass('last') ) 
      { hideBtnNext(e); }
    else 
      { showBtnNext(e); }

    //console.log( $('#articles article#' + e).is(e) ) 

    if ( !$('#articles article#' + e).is('#'+e) ) {

      $.ajax({
        url: u,
          type: "GET",
          cache: false,
        beforeSend: function ( xhr ) {
          //xhr.overrideMimeType("text/plain; charset=x-user-defined");
          $('#overlay').addClass('progress')
        }
      }).done(function ( data ) {

        //var article = '<article id="' + e + '">' + data + '</article>';

        var article = data

        $( article ).appendTo('div#articles').attr('id', e);

      }).always(function() { 

        $('#overlay').removeClass('progress')
        animPosWin(e)
        updLocaleLinks(e)

      });

    } else {

      animPosWin(e)
      updLocaleLinks(e)

    }

  }

  // utility functions
  var dskOpenArticleNF = function(e,u,a,d) {
    
    var currArticle = $('#page div.main article[rel="'+a+'"]')

    $(document).off('click', '.not-front.no-mobile.gt-640 a[rel="ajax"]', dskBtnClkNF);

    //console.log( e + ' >> ' + u )
    //console.log( e )

    if( $('section#footer footer nav li.' + e).hasClass('first') ) 
      { hideBtnPrev(e); }
    else
      { showBtnPrev(e); }

    if(  $('section#footer footer nav li.' + e).hasClass('last') ) 
      { hideBtnNext(e); }
    else 
      { showBtnNext(e); }

    $.ajax({
      url: u,
        type: "GET",
        cache: false,
      beforeSend: function ( xhr ) {
        //xhr.overrideMimeType("text/plain; charset=x-user-defined");

        if ( d == 'left' ) {
          currArticle.animate({'left': +(window.outerWidth / 2 + currArticle.width())}, 600, 'swing', function (){ $(this).remove() })
        } else if ( d == 'right' ) {
          currArticle.animate({'left': -(window.outerWidth / 2 + currArticle.width())}, 600, 'swing', function (){ $(this).remove() })
        } else {
          currArticle.slideUp(300, 'swing', function (){ $(this).remove() })
        }

        //$('#overlay').addClass('progress')

      }
    }).done(function ( data ) {

      //$( data ).appendTo('#page div.main').css({'display': 'none'}).delay(100).slideDown(500);
      var newArticle = $( data ).appendTo('#page div.main').css({'display': 'none'})
      
      //console.log( data )

      if ( d == 'left' ) {
        newArticle.css({'left': -(window.outerWidth / 2 + newArticle.width()), 'display': 'block'})
          .animate({'left': 0 }, 600, 'easeOutBack')
      } else if ( d == 'right' ) {
        newArticle.css({'left': +(window.outerWidth / 2 + newArticle.width()), 'display': 'block'})
          .animate({'left': 0 }, 600, 'easeOutBack')
      } else {
        newArticle.delay(100).slideDown(500);
      }
        
      history.pushState(null, null, u);

    }).always(function() { 

      //$('#overlay').removeClass('progress')
      updLocaleLinks(e)

      $(document).on('click', '.not-front.no-mobile.gt-640 a[rel="ajax"]', dskBtnClkNF);

    });

  }

  var dskCloseArticle = function(e){
    $('#'+e).css({'z-index': '50'})
      .animate({'top': '100%', 'opacity': '0', 'marginTop': '0px'}, 600, 'easeInBack', function(){
        $(this).removeClass('opened').removeAttr('style');
      });
  };

  var showBtnPrev = function(e) {
    $('a#prev').css({visibility: 'visible'})
      .animate({opacity: '0.6', 'left': '-5px'}, 500, 'easeOutQuint');
  };

  var showBtnNext = function(e) {
    $('a#next').css({visibility: 'visible'})
      .animate({opacity: '0.6', 'right': '-5px'}, 500, 'easeOutQuint');
  };

  var hideBtnPrev = function(e) {
    $('a#prev').animate({opacity: '0'}, 300, 'easeInQuint', function(){
      $(this).css({opacity: '0', visibility: 'hidden', 'left': '-60px'})
    });
  };

  var hideBtnNext = function(e) {
    $('a#next').animate({opacity: '0'}, 300, 'easeInQuint', function(){
      $(this).css({opacity: '0', visibility: 'hidden', 'right': '-60px'})
    });
  };

  var dskBtnClk = function(e) {

    var active = $('#articles article.opened').attr('id'),
      next = $('section[rel="'+ active +'"]').next().attr('rel'),
      prev = $('section[rel="'+ active +'"]').prev().attr('rel');

    //console.log( active )

    if ( $(this).is('#next') ) {
      dskOpenArticle( next, $('section[rel="'+next+'"] a').attr('href') );
    }

    if ( $(this).is('#prev') ) {
      dskOpenArticle( prev, $('section[rel="'+prev+'"] a').attr('href') );
    }

    dskCloseArticle( active );

        // Prevent the anchor's default click action
        e.preventDefault();

  };

  var dskBtnClkNF = function(e) {

    var active = $('div.main article.node').attr('rel'),
      next = $('section#footer footer nav li.'+active).next().find('a'),
      prev = $('section#footer footer nav li.'+active).prev().find('a');

    //console.log( $('section#footer a[rel="'+ next +'"]').attr('href') )
    //console.log( $(this).next().attr("id") )

    if ( $(this).is('#next') ) {
      dskOpenArticleNF( next.attr('id'), next.attr('href'), active, 'right' );
    } else if ( $(this).is('#prev') ) {
      dskOpenArticleNF( prev.attr('id'), prev.attr('href'), active, 'left' );
    } else {
      if ( $(this).attr("id") != active) {
        dskOpenArticleNF( $(this).attr("id"), $(this).attr('href'), active, 'left' );
      }
    }

        // Prevent the anchor's default click action
        e.preventDefault();

  };
  

  /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
   *  BEGIN FUNCTIONS AND EVENTS BIND                          *
   * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

  $(this).on('click', 'html.gt-768 #sections section a', function(e){

        // Prevent the anchor's default click action
        e.preventDefault();

    dskOpenArticle( $(this).attr('rel'), $(this).attr('href') );

    $('html.gt-768 div#overlay').css({'display':'block'}).animate({'opacity': '1'}, 300, function(){
      $('html').addClass('overlay'); 
    });

  });

  $(this).on('click', 'html.gt-768 #articles article header', function(){

    var active = $(this).parents('article').attr('id');

    //console.log( active )

    dskCloseArticle(active);

    $('html.gt-768 div#overlay').delay(500).animate({'opacity': '0'}, 300, function(){
      //$(this).css({'display':'none'});
      $('html').removeClass('overlay');
      $(this).removeAttr('style');
    });

    hideBtnPrev(this);
    hideBtnNext(this);

  });

  // add bind for buttons previous and next
  $(this).on('click', '.front.no-mobile.gt-768 #articles a#prev, .front.no-mobile.gt-768 #articles a#next', dskBtnClk);
  
  $(this).on('click', '.not-front.no-mobile.gt-640 a[rel="ajax"]', dskBtnClkNF);


  /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
   *  BEGIN FUNCTIONS AND EVENTS BIND FOR MOBILE               *
   * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

  // utility functions
  /*var mobOpenArticle = function(e) {

    //console.log( e )

    $('#articles article.opened').css({'display': 'none'}).removeClass('opened');

    $('article#' + e).addClass('opened')
      .css({'display': 'block'})
        .animate({'opacity': '1'}, 300, 'easeOutBack');
  };

  var mobCloseArticle = function(e){
    $('article#' + e)
      .animate({'opacity': '0'}, 300, 'easeInBack', function(){
        $(this).css({'display': 'none'}).removeClass('opened');
      });
  };*/

  // bind event to open article
  /*$(this).on('click', 'html.lt-768 #sections section a', function(e){

    mobOpenArticle( $(this).parent().attr('rel') );

        // Prevent the anchor's default click action
        e.preventDefault();

  });

  // bind event to close article
  $(this).on('click', 'html.lt-768 #articles article header', function(){

    var active = $(this).parents('article').attr('id');

    mobCloseArticle(active);

  });*/

  // bind event to navicon
  $('html.mobile.lt-480 section#footer footer nav ul li:not(".home")').hide(10)
  $(this).on('click', 'html.mobile.lt-480 section#footer footer nav ul li a:first', function(e){

        e.preventDefault();

        $('html.mobile.lt-480 section#footer footer nav ul li:not(".home")').toggle()

  });



  /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
   *  HELPER FUNCTIONS                                         *
   * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

  // show buttons for the not-front pages
  if ( $('html.page-node.no-mobile.gt-640').is('.not-front') ) {

    var active = $('div.main article.node').attr('rel');

    if( $('section#footer footer nav li.' + active).hasClass('first') ) 
      { hideBtnPrev(); }
    else
      { showBtnPrev(); }

    if(  $('section#footer footer nav li.' + active).hasClass('last') ) 
      { hideBtnNext(); }
    else 
      { showBtnNext(); }

    // activate wallpaper changer
    setInterval(function() {
      cloneAnimBg('#bg')
    }, 60000);

  }

  // animate the exiting of article
  var animPosWin = function(el) {

    var hArt = $('#articles article#' + el).height(),
      hWin = $(window).height()

    var wBox = $('#articles article#' + el).width(),
      hBox = (hWin <= hArt) ? 0 : hArt;

    var top = hBox == 0 ? '0px' : '50%',
      marginTop = ( hBox / 2 ) <= 10 ? '20px' : -( hBox / 2 );

    //console.log( hBox )

    if ( ( hBox / 2 ) <= 10 ) {
      $('div#articles article#' + el).css({'position': 'fixed'})
    }

    $('div#articles article#' + el)
      .addClass('opened')
      .css({'top': -hBox, 'margin-left': -(wBox / 2), 'display': 'block', 'z-index': '100'})
        .stop(true, false).animate({'top': top, 'opacity': '1', 'marginTop': marginTop }, 600, 'easeOutBack', function(){

          if ( ( hBox / 2 ) <= 10 ) {
            $('div#articles article#' + el).css({'position': 'absolute'})
          }
          
          $(document).on('click', '.front.no-mobile.gt-768 #articles a#prev, .front.no-mobile.gt-768 #articles a#next', dskBtnClk);

        });

  } // END animPosWin

  function updLocaleLinks(e) {

    var nodes = $('article[rel="'+e+'"]').data('nodes');

    for (x in nodes) {
      //console.log( x +' '+ nodes[x] );
      $('#block-locale-0 li.'+x).find('a').attr('href', 'http://'+globalVars.langsLabel[x]+nodes[x])
    }

  }

  window.cloneAnimBg = function(id) {

    var currBg = $(id).first(),
      randmtime = microtime(true);

    $(id).clone().css({ 'left': window.outerWidth, 'right': -(window.outerWidth), 'background-image': 'url("http://www.spidersolutions.it/sites/default/themes/spidersolutions_it/rotate_wallpapers_colored.php?_='+randmtime+'")'}).appendTo('body')
      .delay(600).animate({'left': '0px', 'right': '0px'}, 600, 'swing', function(){
        currBg[0].remove()
      })

  }

});


function microtime (get_as_float) {
  // http://kevin.vanzonneveld.net
  // +   original by: Paulo Freitas
  // *     example 1: timeStamp = microtime(true);
  // *     results 1: timeStamp > 1000000000 && timeStamp < 2000000000
  var now = new Date().getTime() / 1000;
  var s = parseInt(now, 10);

  return (get_as_float) ? now : (Math.round((now - s) * 1000) / 1000) + ' ' + s;
}

String.prototype.replaceAll = function(str1, str2, ignore) {
    return this.replace(new RegExp(str1.replace(/([^\w\,\!\\\^\$\{\}\[\]\(\)\.\*\+\?\|\<\>\-\&])/g, function(c){return "\\" + c;}), "g"+(ignore?"i":"")), str2);
};