(function($,s4ntc) {
  
  var EventQueueItem = function(queue, callback, params, target) {
    this.queue = queue;
    this.callback = callback;
    this.params = params !== undefined ? params : [];
    this.target = target !== undefined ? target : {};
    this.when = new $.Deferred();
    this.next = null;
  };
  EventQueueItem.prototype.resolve = function() {
    this.params.push.apply(this.params, [this.when]);
    if(this.callback.apply(this.target, this.params) !== false) {
      this.when.resolve();
    }
  };
  EventQueueItem.prototype.setNext = function(eqItem) {
    this.next = eqItem;
    var queue = this.queue;
    this.when.done(function() {
      queue.current = eqItem;
      eqItem.resolve();
    });
  };

  var EventQueue = function() {
    var currentEqItem = new EventQueueItem(this, function(){
      this.active = true;
    }, [], this);
    this.current = currentEqItem;
    this.last = currentEqItem;
  };
  EventQueue.prototype.enqueue = function(callback, params, target) {
    var eqItem = new EventQueueItem(this, callback, params, target);
    this.last.setNext(eqItem);
    this.last = eqItem;
  };
  EventQueue.prototype.delay = function(millis) {
    var delay_callback = function(when){
      setTimeout(function() {
        when.resolve();
      }, millis);
      return false;
    };
    this.enqueue(delay_callback, [], this);
  }
  EventQueue.prototype.start = function() {
    this.current.resolve();
  };

  s4ntc.tools = {
    events: {
      EventQueue: EventQueue
    },
    test: {
      nNOU: function(variable) {
        return variable !== null && variable !== undefined;
      },
      nNUE: function(variable) {
        return variable !== '' && variable !== null && variable !== undefined;
      },
      pInt: function(variable) {
        return parseInt(variable) > 0;
      }
    },
    url: {
      addParams: function(url, params) {
        var anchor_splitted = url.split('#');
        var has_anchor = anchor_splitted[1] !== undefined;
        var anchor = '';
        if(has_anchor) {
          url = anchor_splitted[0];
          anchor = '#'+anchor_splitted[1];
        }

        var qstring = '';
        var qstring_splitted = url.split('?');
        var has_qstring = qstring_splitted[1] !== undefined;
        if(has_qstring) {
          url = qstring_splitted[0];
          qstring = '?'+qstring_splitted[1];
        }

        var separator = '?';
        if(qstring.length > 0) {
          qstring+='&';
        }

        var params_array = [];
        for(var idx in params) {
          params_array.push([params[idx].name,'=',params[idx].value].join(''));
        }

        return [url,qstring,separator,params_array.join('&'),anchor].join('');
      }
    }
  };
  
})(jQuery, window.s4ntc !== undefined ? window.s4ntc : (window.s4ntc = {}));
