/**
 * StatLoggerNew is a singleton with two public methods, logEvent and logUniqueEvent
 */
var StatLoggerNew = function() {
    /** private variables */
    var logEventQueue  = [];
    var cookie         = '_uqpgv';
    var eventDelim     = ',';     // Use this delim also in log.php
    

    /** private functions */
    function generateRequestParams(events){
        if (!events) return "";
        var str = "os="+ UserAgent.os;
        str += "&br=" + UserAgent.browser;
        str += "&ver=" + UserAgent.version;
        str += "&dom=" + document.domain;
        str += "&path=" + (UserAgent.path || document.location.pathname);
        str += "&e=" + events;
        str += "&exp=" + UserAgent.experiment;
        str += "&c=" + UserAgent.choice;
        str += "&hc=" + hasCooliris();
        return str;
    }
    
    function sendLogRequest(events, callback) {
        var str = generateRequestParams(events);
        var request = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("MSXML2.XMLHTTP.3.0");
        if (request)
        {
           if (typeof callback == 'function') {
               var callBackWrapper = function(){
                   if (request.readyState == 4){
                       callback();
                   }
               };
               request.onreadystatechange = callBackWrapper;
           }
           // p=2 means protocol 2. log.php.
           var url = location.protocol + "//" + document.domain +"/shared/stats/log.php?p=2&" + str + "&h=" + UserAgent.hithash + '&d=' + (new Date()).getTime();
       
            //alert(url);
            //return;
           request.open("GET", url);
           request.send("");
       
           // We echo time() above because IE won't execute identical AJAX requests in short succession. =)
        }
    }
    
    /**
     * run, iterates over the logEventQueue and sends all accumulated log events in one request
     */
    function run() {
        var q = logEventQueue;
        logEventQueue = [];
        var i = q.length;
        if (i < 1) return;
    
        var req = "";
        var callbacks = []; 
        while (i--)
        {
            req += q[i]['event'];
            if (i) req += eventDelim; // if (i) check here prevents the delimiter from being appended at the last element.
            callbacks.push(q[i].callback);
        }
        var newCallback = function() 
        {
            var i = callbacks.length;
            while (i--)
            {
                if (typeof callbacks[i] == 'function') {
                    callbacks[i]();
                }
            }
        };
        
        sendLogRequest( req , newCallback );    
    }
    
    // detects the version of cooliris/piclens
    // tells us whether it is messaging enabled
    function hasCooliris() {
        // check if the bridge has already been defined
        var clientExists = false;
        if (window.piclensBridge) {
            clientExists = true;
        } else {
            // if not, try to define it here...
            var context = null;
            if (typeof PicLensContext != 'undefined') { // Firefox ONLY
                context = new PicLensContext();
            } else { // IE ONLY
                if (window.ActiveXObject){
                    try {
                      context = new ActiveXObject("PicLens.Context");
                    } catch (e) {}
                } else {
                    if (navigator.mimeTypes['application/x-cooliris']) {
                        // Safari
                        context = document.createElement('object');
                        context.style.height="0px";
                        context.style.width="0px";
                        context.type = 'application/x-cooliris';
                        document.documentElement.appendChild(context);
                    } 
                }
            }
            
           window.piclensBridge = context;
            if (window.piclensBridge) {
                clientExists = true;
            }
        }
        
        return clientExists;
    }
    
    /** Return a new javascript object with the public functions, which, through closure, can access the private variables and methods */
    return {
        logEvent : function (event, callback)
        {
            if (!event) return;
        
            logEventQueue.push( { 'event' : event, 'callback' : callback } );
            setTimeout(run, 1000);
        },
    
        // Store all page-event hits in one cookie.
        // This is okay cause a cookie can take 4096 chars.
        // But there wont be too many unique events per page.
        // This is still better than one cookie per page.
        //
        // If no hash is provided, a page info will be provided.
        // We could hash this, but that = more computation.
        // For now, store plain str.
        // 
        // Format: uripath#event
        // ex: www.cat.com/sound.php -> logUniqueEvent('purr');
        // hash = /sound.php#purr
        //
        logUniqueEvent : function (nEvent, hash, callback) {
            if (!hash) hash = (UserAgent.path || document.location.pathname) + '#' + nEvent;
        
            var c = Cookie.get(cookie);
            if (!c)
            {
                // No cookie. new hit =)
                Cookie.set(cookie, hash, 1);
                StatLoggerNew.logEvent(nEvent, callback);
                return;
            }
        
            var a = c.split('|');
            for (var i = 0; i < a.length; i++)
            {
                if (a[i] == hash)
                    return; // Previous Hit! End function without logging. =(
            }
            // hash not found. new hit =)
            Cookie.set(cookie, c + '|' + hash, 1);
            StatLoggerNew.logEvent(nEvent, callback);
        }
    };
}();
