$(document).ready(function(){
  var timer = [];
  $('.sm').each(function() {
    var sm = $(this);
    var le = 0;
    sm.parent().parent().find('a').each(function() {
      if( $(this).attr('rel') == sm.attr('rel') ) {
        return false;
      }
      le = 1 + le + $(this).outerWidth();
    });
    var dd = $( '#' + sm.attr('rel') );
    dd.css('left',le - 1);
    $('#z' + sm.attr('rel') ).width( sm.outerWidth() - 2 + 'px' );
    sm.mouseenter(function() {
      clearTimeout( timer[sm.attr('rel')] );
      sm.addClass('smHover');
      dd.show();
    }).mouseleave(function() {
      timer[ sm.attr('rel') ] = setTimeout(function() {
        sm.removeClass('smHover');
        dd.hide();
      },50);
    });
    dd.hover(function() {
      clearTimeout(timer[ sm.attr('rel') ]);
    },function() {
      timer[ sm.attr('rel') ] = setTimeout(function() {
        sm.removeClass('smHover');
        dd.hide();
      },50);
    });
  });
});

/*
 * Footer functionality
 */
$(document).ready(function() {

  var url = window.location.href;
  if( url.indexOf('#') > 0 ) {
    var parts = url.split('#');
	url = parts[0];
  }
  $('#up').attr('href',url + '#top');

  $('#slider').Slider();

  Replies.init();
});

var Replies = {

  init: function() {
    Replies.loop( true );
  },

  loop: function( first ) {
    Replies.fetch( first );
    setTimeout('Replies.loop( false );', Replies.timer);
  },

  current: -1,

  timer: 60000,

  fetch: function( first ) {
    var url = 'ajax/replies';
    var top = 54;
    var timer = 500;
    $.post( url, { current : Replies.current, first : first }, function( data ){
      if( first ) { // remove first element
        $('#a_replies a.not').animate({
          top: '-70px'
        },500);
      }
      /*
       * Loop results and append each reaction
       */
      $( data ).each(function() {
        // stop the loop if the first result is equal to the last fetched result
        if( Replies.current == this.current ) {
          return;
        }
        Replies.current = this.current;
        $('#a_replies div').prepend('<a class="com" style="position: relative;margin-top: -' + top + 'px" href="' + this.link + '#n-' + this.current + '"><strong>' + this.head + '</strong><span><!-- --></span>' + this.content + '<br/></a>');
        $('#a_replies a.com:first').animate({
          marginTop: 0
        },timer,function() {
          if( !first ) {
            $('#a_replies a.com:last').remove();
          }
        });
        top = top + top;
        timer = timer + 1000;
      });
    }, 'json');
  }

}

