/**
 * @param target  CSS selector for main wrapper.
 * @param opts    Options : items marked with an asterisk(*) are required
 *                  @property url*            URL of xml file.
 *                  @property interval        Milliseconds between url requests (defaults to 5000).
 *                  @property lang            Current language.
 *                  @property speed           Animation speed (defaults to 1).
 *                  @property stopOnRollover  When set to true, stops animation on rollover of activity tracker.
 */
var ActivityTracker = function( target, opts ) {
  
  var $target = $( target ),
      $wrapper = null,
      totalItems = 0,
      init = false,
      pos = 0,
      last = null,
      itemMaxWidth = 480;

  var addChild = function( _vars ) {
    var _item = $('<li><div class="user col"><div class="avatar"><img src="' + _vars.avatar + '" alt=""></div><img class="flag" src="' + _vars.flag +
    '"/><span class="name">' + _vars.username + '</span></div><div class="msg col"><div class="content">' + _vars.message + '</div><span class="arrow"></span></div></li>');
    $wrapper.append( _item );
    // update wrapper
    $wrapper.css( "width", $wrapper.width() + _item.outerWidth(true) );
  }

  var Animation = {
    interval : 0, running : false, stoppedByUser : false,
    cont : function() {
      $wrapper.css( "left", pos-=(opts.speed || 1) );
    },
    stop : function() {
      Animation.stoppedByUser = arguments[0].data.user;
      clearInterval( Animation.interval );
	    Animation.running = false;
    },
    start : function() {
      if (!Animation.running || !Animation.stoppedByUser) {
		    Animation.interval = setInterval( Animation.cont, 35 );
	      Animation.running = true;
	    }
    }
  };

  var Polling = {
    interval : 0,
    poll : function() {
      //remove non-visible items
      var _wrapperLeft = $wrapper.css( "left" );
      $wrapper.find( "li:lt(" + Math.floor((-_wrapperLeft.slice( 0, _wrapperLeft.length-2 ))/itemMaxWidth) + ")" ).each( function(index,item) {
        var $item = $(item);
        $wrapper.css( "left", pos+=$item.outerWidth(true) );
        $item.remove();
        delete $item;
      } );
      //request new xml
      $.ajax( {
      	type : "POST",
        url : opts.url || "",
        data : "l="+(opts.lang || "en") + ( init ? "&n="+last : "" ),
        complete : function( xhr, status ) {
          parse( $( xhr.responseXML ) );
          Polling.index++;
        },
        error : function( xhr, status, error ) {
          _errors.push( "\"" + _url + "\" could not be loaded!" );
          $target.html( "<div class=\"error\">ERROR : Could not load overview!</div>" );
        }
      } );
    },
    start : function() {
      Polling.poll();
      Polling.interval = setInterval( Polling.poll, opts.interval || 5000 );
    },
    stop : function() {
      clearInterval( Polling.interval );
    }
  };

  var parse = function( $xml ) {
    var _items = $xml.find("item"), _vars;
    totalItems += _items.length;

    for ( var i=0, _node; _node = _items[i++]; ) {
      _node = $(_node);
      _vars = {
        id : _node.attr( "ID" ),
        username : _node.find( "user" ).attr( "name" ),
        avatar : _node.find( "user avatar" ).attr( "href" ),
        flag : _node.find( "user country" ).attr( "href" ),
        message : _node.find( "message" ).text()
      };
      addChild( _vars );
    }

    last = _vars.id;

    if ( !init && opts.startAnimation ) {
      Animation.start();
      init = true;
    }
  }

  this.StopPolling = function() {
    clearInterval( Polling.interval );
  }
  this.StopAnimation = function() {
    clearInterval( Animation.interval );
  }
  this.startAnimation = function() {
    Animation.start();
    init = true;
  }

  $target.find( ".alternate" ).remove();
  $target.append( '<div class="mask"><ul class="items"></ul></div>' );
  /*$target.find( "h3:first" ).css( {
  	background : "url(../images/at_heading_" + opts.lang + ".gif) 12px 8px no-repeat"
  } );*/
  $wrapper = $target.find( "ul.items" );

  Polling.start();

  if ( opts.stopOnRollover ) $target.bind( "mouseover.ActivityTracker", {user:true}, Animation.stop ).bind( "mouseout.ActivityTracker", Animation.start );

}