/*
 *  debug code - tracing and timing © 2006-2011, Horus Web Engineering Ltd
 *
 *  $Id: trace.js,v 1.6 2011-01-23 18:52:11 horus Exp $
 *
 *  licensed under the terms of the GNU Lesser General Public License:
 *    http://www.opensource.org/licenses/lgpl-license.php
 *
 *  autoloads dom.js if horus.trace() is used
 *
 */


horus.trace=
  function () {
    var trace=
      document.getElementById('tracebox') ||
      horus.insertChild([ 'div', { id: 'tracebox', classname: 'error' } ]);

    horus.childText
      (trace, Array.prototype.lambda.call(arguments, horus.toString).join(' '), true);

  };


horus.$alert=
  function ( argv, offset ) {
    alert(Array.prototype.lambda.call(argv, offset, horus.toString).join(' '));
  };


horus.alert   = function ()    { horus.$alert(arguments, 0) };
horus.alertIf = function ( c ) { if (c) horus.$alert(arguments, 1) };


horus.watcher=
  function ( property, oldval, newval) {
    horus.trace
      (horus.toString(this), ': ', property, ' changed from ',
       horus.toString(oldval), ' to ', horus.toString(newval));

  };


horus.timer=
  function ( id ) {
    if (id!=null) horus.timer.data[id]=new Date().valueOf();
  };


horus.timer.get=
  function ( id ) {
    if (id in horus.timer.data) {
      var time=horus.timer.data[id];
      return time<=0 ? -time : new Date().valueOf()-time;
    }
  };


horus.timer.pause=
  function ( id ) {
    if (id in horus.timer.data) {
      if (horus.timer.data[id]>0)
	horus.timer.data[id]-=new Date().valueOf();

      return -horus.timer.data[id];
    }
  };


horus.timer.start=
  function ( id ) {
    if (!(id in horus.timer.data)) horus.timer.data[id]=0;

    if (horus.timer.data[id]<=0)
      horus.timer.data[id]+=new Date().valueOf();

  };


horus.timer.restart=
  function ( id ) {
    var time=horus.timer.get(id);
    horus.timer.data[id]=new Date().valueOf();
    return time;
  };


horus.timer.stop=
  function ( id ) {
    var time=horus.timer.get(id);
    horus.timer.data[id]=0;
    return time;
  };


horus.timer.remove=
  function ( id ) {
    if (id in horus.timer.data) delete(horus.timer.data[id]);
  };


horus.counter=
  function ( id ) {
    if (id!=null) horus.counter.data[id]=0;
  };


horus.counter.get=
  function ( id ) {
    return horus.counter.data[id];
  };


horus.counter.set=
  function ( id, count ) {
    var old=horus.counter.data[id];
    horus.counter.data[id]=count;
    return old;
  };


horus.counter.reset=
  function ( id ) {
    return horus.counter.set(id, 0);
  };


horus.counter.increment=
  function ( id, count ) {
    if (count==null) count=1;
    if (!(id in horus.counter.data)) horus.counter.data[id]=0;
    horus.counter.data[id]+=count;
    return horus.counter.data[id];
  };


horus.counter.decrement=
  function ( id, count ) {
    if (count==null) count=1;
    return horus.counter.increment(id, -count);
  };


horus.timer.data={};
horus.counter.data={};


horus.script.loaded('trace');

