//Begin: /Scripts/CorbisUI.getMicroTimestamp.js

// Verify CorbisUI has been created.
if (!CorbisUI) {
    var CorbisUI = {}
}

/**
* Get the current timestamp in milliseconds
*/
CorbisUI.getMicroTimestamp = function() {
    var tdate = new Date();
    return tdate.getTime();
}
//End: /Scripts/CorbisUI.getMicroTimestamp.js
//Begin: /Scripts/CorbisUI.SingleTimer.js

/**
 * Timer Script
 *
 * Note: Need to rename str_buf once added to the CorbisUI namespace
 * 
 * Requires: str_buf.js
 */

// Verify CorbisUI has been created.
if (!CorbisUI) {
    var CorbisUI = {}
}

/**
 * Single Timer Class
 * Tracks a single referenced start / stop time. Built to be used by CorisUI.Timer.
 * @param name Name of the timer
 * @param start_time Integer value micro timestamp
 * @uses CorbisUI.getMicroTimestamp
 * @see CorbisUI.Timer
 */
CorbisUI.SingleTimer = function(name, start_time) {
    this.name = name; // Name of the timer
    this.astart = start_time;
    this.afirst = start_time;
    this.astop = 0;
    this.aelap = 0;

    /**
    * Stop the timer
    */
    this.stop = function(stop_time) {
        if (!stop_time) { // Get current time if undefined
            stop_time = CorbisUI.getMicroTimestamp();
        }

        /* our timer is running */
        if (this.astart > 0) {
            this.astop = stop_time;
            this.aelap += stop_time - this.astart;
        }
        this.astart = -1;
    }

    /**
    * Start the timer
    */
    this.start = function(start_time) {
    this.astart = start_time ? start_time : CorbisUI.getMicroTimestamp();
    }

    this.to_str_json = function(abuf, stime) {
        var tb = new Strbuf();
        this.to_buf_json(tb, stime);
        return tb.to_str();
    }

    this.to_buf_json = function(abuf, stime) {
        abuf.add('"', escape(this.name), '":{');
        abuf.b('"first":').b(this.afirst - stime);
        abuf.b(',"last":').b(this.astop - stime);
        abuf.b(',"elap":').b(this.aelap);
        abuf.b('}');
        return abuf
    }
}


//End: /Scripts/CorbisUI.SingleTimer.js
//Begin: /Scripts/CorbisUI.Timer.js

// Verify CorbisUI has been created.
if (!CorbisUI) {
    var CorbisUI = {}
}

/****************
*** C L A S S ***
*****************
*  ac_timer is a hash containing unique entery for
*  each label.  A label can be started and stopped
*  multiple times.   Inclues utility to dump as
*  hash for easy reporting to server.
*
*  NOTE: Check back and remove CSV related code.
*
* @param mid Market ID
* @param suid Search UID
*/
CorbisUI.Timer = function(sid, rid, mid, suid, pstart) {
    this.timers = {}
    this.ActivityUid = rid;
    this.SessionId = sid;
    this.MarketId = mid;
    this.SearchUid = suid;
    this.NamePrefix = "cs_";
    this.myquery = "..";
    this.myuri = "..";
    this.ptype = "search";

    this.startTime = pstart ? pstart : CorbisUI.getMicroTimestamp();

    // retrieve a timer at label if it does not
    // exist then make a new one.
    this.get = function(name, ptime) {
        if (this.NamePrefix != "") { name = this.NamePrefix + name; }
        var tti = this.timers[name];
        if (!tti) {
            if (!ptime) {
                ptime = CorbisUI.getMicroTimestamp();
            }

            tti = new CorbisUI.SingleTimer(name, ptime);
            this.timers[name] = tti;
        }
        return tti;
    }


    /**
    * Start a timer
    * @param name Name of the timer
    * @param start_time Optional start time of the timer
    */
    function start(name, start_time) {
        this.get(name, start_time).start(start_time);
    }

    function stop(tname, tstop) {
        this.get(tname).stop(tstop);
    }

    function stop_all() {
        for (var key in this.timers) {
            this.timers[key].stop();
        }
    }

    function to_buf_json(abuf) {
        abuf.b("{").b('"header":');
        abuf.b('{"rid":"').b(this.ActivityUid).b('",');
        abuf.b('"sid":"').b(this.SessionId).b('",');
        abuf.b('"mid":"').b(this.MarketId).b('",');
        abuf.b('"suid":"').b(this.SearchUid).b('",');
        abuf.b('"query":"').b(escape(this.myquery)).b('",');
        abuf.b('"ptype":"').b(escape(this.ptype)).b('",');
        abuf.b('"uri":"').b(escape(this.myuri)).b('"}');
        abuf.b(',"values":{');
        for (var akey in this.timers) {
            this.timers[akey].to_buf_json(abuf, this.startTime);
            abuf.b(",");
        }
        abuf[abuf.length - 1] = ""; // clear our last delimiter
        abuf.b("}");
        abuf.b("}");
        return abuf;
    }


    /* Convert timers into a line delimited format.  
    **  first, stop, elap, label\n 
    **  Switched to this from the JSON format to make parsing with standard log tool easier. 
    */
    function to_buf_cdf(abuf) {
        for (var akey in this.timers) {
            atimer = this.timers[akey];
            abuf.b(this.SessionId).b(",");
            abuf.b(this.ActivityUid).b(",");
            abuf.b(atimer.afirst - this.startTime).b(",");
            abuf.b(atimer.astop - this.startTime).b(",");
            abuf.b(atimer.aelap).b(",");
            abuf.b(escape(atimer.name));
            abuf.b("\n");
        }
        return abuf;
    }

    function to_str() {
        var tb = new Strbuf();
        this.to_buf_cdf(tb)
        return tb.to_str();
        //TODO: Remove the last , before
        // adding the final ,

    }

    this.to_json_str = function() {
        var tb = new Strbuf();
        this.to_buf_json(tb);
        return tb.to_str();
    }

    /* inserts our serialized representation 
    * into a div structure by ID name
    */
    function to_div(div_name, isProfile) {
        if (!isProfile) {
            return;
        }

        var tb = new Strbuf();
        tb.b("<br clear=all /><pre>");
        tb.b("sid,rid,first,stop,elap,name\n");
        this.to_buf_cdf(tb);
        tb.b("</pre>");
        tb.to_div(div_name);

        document.getElementById(div_name).style.display = "block";
    }

    function log(cons, astr) {
        if (astr) {
            cons.log(astr)
        }
        var astr = this.to_str();
        cons.log(astr);
    }

    /* parse the current document URI and query parms into 
    the instance variables this.myuri and this.myquery.  If the
    values for myuri and myquery are already set then it will
    skip setting them from the URI line.  This allows the page
    to send custom information */
    function parse_uri() {
        if (this.myuri == "..") {
            var tt = window.location.href;
            var tarr = tt.split("?", 2);
            this.myuri = tarr[0];
            if ((tarr.length > 1) && (this.myquery == "..")) {
                this.myquery = tarr[1];
            }
        }

        if (this.myquery == "..") {
            var tt = window.location.href;
            var tarr = tt.split("#", 2);
            this.myuri = tarr[0];
            if (tarr.length > 1) {
                this.myquery = tarr[1];
            }
        }
    }


    /* sends my accumulated timers
    * back to the server in the form
    * of a post to a URI.
    *  SID = session ID - session is shared for all requests a user makes during given session
    *  RID = request ID - Request is unique for each page requested but shared across all AJAX requests for a given page.
    */
    //    this.reportCSV = function (auri) {

    //        this.parse_uri();

    //        var astr = this.to_str();
    //        var ahttp = this.getHttpRequest();
    //        ahttp.open("POST", auri, true)
    //        ahttp.setRequestHeader("rid", this.myrid);
    //        ahttp.setRequestHeader("sid", this.mysid);
    //        ahttp.setRequestHeader("mid", this.mid);
    //        ahttp.setRequestHeader("suid", this.suid);
    //        ahttp.setRequestHeader("query", this.myquery);
    //        ahttp.setRequestHeader("uri", this.myuri);

    //        ahttp.setRequestHeader("content-length", astr.length);
    //        ahttp.send(astr);
    //        // don't care if we get a response so no callback.
    //    }
    /* sends my accumulated timers
    * back to the server in the form
    * of a post to a URI.
    *  SID = session ID - session is shared for all requests a user makes during given session
    *  RID = request ID - Request is unique for each page requested but shared across all AJAX requests for a given page.
    */
    this.reportJSON = function(auri) {
        if (!auri) {
            auri = "/common/Timer.asmx/Report";
        }

        this.parse_uri();
        var astr = ["data=", this.to_json_str()].join("");

        try {
            var http = this.getHttpRequest();
            http.open("POST", auri, true);

            http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
            http.send(astr);
            // don't care if we get a response so no callback.
        } catch (er) { }
    }

    this.getHttpRequest = function() {
        if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
            return new XMLHttpRequest();
        }
        else {// code for IE6, IE5
            return new ActiveXObject("Microsoft.XMLHTTP");
        }
    }

    this.isProfile = function() {
        var hashString = "isProfile=";
        var h = location.hash;
        var ip = h.indexOf(hashString);
        if (ip == -1 || ip + hashString.length + 1 > h.length) {
            return false;
        }
        ip += hashString.length;
        h = h.substring(ip, ip + 1);
        if (h == "t" || h == "1") {
            return true;
        }

        return false;
    }

    //Set up method pointers
    this.start = start;
    this.stop = stop;
    this.stop_all = stop_all
    this.to_buf = to_buf_cdf;
    this.to_buf_cdf = to_buf_cdf;
    this.to_buf_json = to_buf_json;
    this.to_div = to_div;
    this.parse_uri = parse_uri;


}                        // end class

// Used to initialize a timer after initial initialization.
CorbisUI.Timer.ajaxInit = function() {
    return new CorbisUI.Timer(CorbisUI.TimerCache.SessionId, null, CorbisUI.TimerCache.MarketId, null, CorbisUI.getMicroTimestamp());
}

CorbisUI.TimerCache = {
    SessionId : null,
    MarketId : null
}
//End: /Scripts/CorbisUI.Timer.js
//Begin: /Scripts/strbuf.js

/* strbuf.js -  javascript string buffer  */

/* strbuf for fast string building 
* general trade of is strbuff is 
* a better choice than 2 or more
* document.write and 6 or more 
* string concatonation using +.
* all adds can transparantly handle numbers
*
*  Instance menthods
*    abuf.b - adds a single string
*    abuf.push - adds a single string
*    abuf.add  - Add one or more strings 
*    abuf.log  - add one or more strings
*
*  overloaded names such as add and log
*  used to make clear to make contextual
*  use more clear. 
*/
function Strbuf()  // CONSTRUCTOR 
{
// ------------------------
//  String buffer management
// -------------------------
  /* clean out our and set up for re-use */
  function clear()
  {
    this.length = 0;  
  }

  // single string add function
  function push_s(aStr)
  {    
    this.push(aStr); 
    return this
  } 
  
  // multi parameter buffer add
  // separated from push_s because
  // slightly slower.  so keep the b.b function
  // which is single parm only
  function add()
  {
    for (var i = 0; i < arguments.length; ++i)
    {
      var aparm = arguments[i];
      if (aparm != undefined)
      {
        this.push(aparm)
      }
    }
  }

  /* convert our array into a single
  * string that can be inserted into 
  * a string.   adelim is optional, if
  * supplied it will placed between
  * all array elements otherwise no
  * space will be inserted. 
  */
  function to_str(adelim)
  {
    this.push("");
    if (adelim == undefined)
    {
      return this.join("");
    }
    else
    {
      return this.join(adelim);
    }
  }
 
  
  /* Inserts current contents of buffer into
  * a div if the div by id can be found. Returns
  * the div if sucessful otherwise returns undefined
  */
  function to_div(div_id)
  {
    var adiv = document.getElementById(div_id);
    if (adiv != undefined)
    {
      adiv.innerHTML = this.to_str();
    }
    return adiv
  }


  var arr = [];
  arr.b = push_s;
  arr.log = add;
  arr.add = add;
  arr.to_str = to_str;
  arr.clear = clear;
  arr.to_div = to_div;
  return arr;
}



//End: /Scripts/strbuf.js
CorbisUI.debug = true;