// Chartaca Browser Client
// Copyright (c) 2011 Chartaca
; 

var Chartaca;
if( !Chartaca ) {
  Chartaca = {};

  (function(){

    function getbody() {
      return document.getElementsByTagName('body')[0]
    }


    function enc(str) {
      str = escape(str)
      str = str.replace(/\//g,'%2F')
      return str
    }

    /*
    function getxhr() {
      if(window.ActiveXObject) {
	return new ActiveXObject('Microsoft.XMLHTTP')
      }
      return new XMLHttpRequest()
    }
    */

    function countimg(id,endpoint,instance){
      var now = new Date()
      //var url  = document.location.protocol+'//count.chartaca.com/'+id+'/s.gif?d='+now.getTime()
      var url = 'http://'+endpoint+'/'+id+'/s.gif?d='+now.getTime()

      var body = getbody()
      if( !body ) {
        instance.queue({type:'id',id:id})
        return;
      }

      var imgid = instance.imgid
      var img = document.getElementById(imgid) 
      var exists = !!img
      if( !exists ) {
        img = document.createElement('img')
        img.id = imgid
        img.style.display = 'none'
      }

      img.src = url

      if( !exists ) {
        body.appendChild(img)
      }
    }
  

  if (typeof Chartaca.init !== 'function') {
    Chartaca.init = function( opts ) {
      var instance = {
        imgid:'chartaca-'+new Date().getTime()+'-'+Math.random()
      }

      var key    = null
      var target = null
      var eventperiod = 0
      var endpoint = 'count.chartaca.com'

      var queue = []
      var eventcount = 0

      if( opts ) {
        key    = enc(opts.key)
        target = enc(opts.target)
        eventperiod = opts.eventperiod || eventperiod
        endpoint = opts.endpoint || endpoint
      }


      function drain() {
        if( 0 < queue.length ) {
          
          var ids = []
          var targets = {}

          for(var i=0; i < queue.length; i++) {
            var entry = queue[i]
            if( 'id'==entry.type ) {
              ids.push(entry.id)
            }
            else if( 'event'==entry.type ) {
              var post = targets[entry.target] || (targets[entry.target]=[])
              post.push([entry.when,entry.event])
            }
          }

          // don't yield before this point
          queue = []


          for( var i = 0; i < ids.length; i++ ) {
            countimg(enc(ids[i]),endpoint,instance)
          }

          for( var t in targets ) {
            var post = targets[t]
            var json = []
            for( var pI = 0; pI < post.length; pI++ ) {
              json.push('%5B'+post[pI][0]+'%2C%22'+post[pI][1]+'%22%5D')
            }

            var path = 'multi/'+key+'/'+target+'/'+'%5B'+json.join('%2C')+'%5D'
            countimg(path,endpoint,instance)

            /*
            var xhr = getxhr()
            xhr.open("POST", 'http://'+endpoint+'/'+key+'/'+t+'/s.json?d='+new Date().getTime(), true);
            xhr.send('['+json.join(',')+']');
            */
          }
        }
      }

      instance.debug = function() {
        return {
          queue:queue,
          eventcount:eventcount,
          key:key,
          target:target,
          eventperiod:eventperiod,
          endpoint:endpoint
        }
      }

      instance.queue = function(entry) {
        queue.push(entry)
      }

      instance.hit = function(id) {
        drain()
        countimg(enc(id),endpoint,instance)
      }

      instance.fire = function(event,t) {
        eventcount++
        t = (t && enc(t)) || target
        event = enc(event)

        //console.log(eventcount+' '+eventperiod+' '+t+' ~~~ '+event)

        if( 0 === eventperiod ) {
          var id = key+'/'+t+'/'+event
          countimg(id,endpoint,instance)
        }
        else {
          instance.queue({type:'event',target:t,event:event,when:new Date().getTime()})

          if( 0 === eventcount % eventperiod ) {
            drain()
          }
        }
      }

      return instance
    }
  }

})();

}
