/**
 * UsersOnline v0.1.0
 *
 */
uox_counter = {
    id: false,
    style: 'default',
    url: false,
    oldUrl: false,
    linkObj: false,
    counterObj: false,
    baseUrl: 'http://www.usuarios-online.com/es/stats/',
    workerUrl: 'http://work.usuarios-online.com/listener.php',

    start: function() {
        this.getUrl();
        this.getOldParams();
        this.createCounter();
        this.getLinkObj();
        this.getCounterObj();
        this.sendJsonp();
    },

    getOldParams: function() {
        var scripts = document.getElementsByTagName( 'script' );
        var thisScriptTag = scripts[ scripts.length - 1 ];
        this.oldUrl = this.parseParams( 'v', thisScriptTag.src );
    },

    parseParams: function(n,s){
        n = n.replace(/[\[]/,"\\[").replace(/[\]]/,"\\]");
        var p = (new RegExp("[\\?&]"+n+"=([^&#]*)")).exec(s);
        return (p===null) ? "" : p[1];
    },

    getUrl: function(){
        this.url = document.URL;
    },

    getLinkObj: function(){
        this.linkObj = document.getElementById('uox_link');
        this.id = this.linkObj.rel;
    },

    getCounterObj: function(){
        this.counterObj = document.getElementById('uox_counter');
    },

    createCounter: function(){
        document.write('<a href="#" id="uox_link" target="_blank" style="text-decoration:none;"><span id="uox_counter">?</span></a>');
    },

    updateCounter: function(c){
        this.counterObj.innerHTML = c;
    },

    jsonp: function(url, data, callback) {
        data.callback = callback;
        var get = [];
        get['dateTime'] = new Date().getTime();
        for (var field in data) {
            get.push(encodeURIComponent(field) + '=' + encodeURIComponent(data[field]));
        }
        var script = document.createElement('script');
        script.setAttribute('type', 'text/javascript');
        script.setAttribute('src', url + '?' + get.join('&'));
        document.getElementsByTagName("head")[0].appendChild(script);
    },

    sendJsonp: function(){

        this.jsonp(this.workerUrl, {_oldDomain: this.oldUrl, _url: this.url }, this.callback);
    },

    callback: function(data) {
        if(data.status == 'ok') {
            this.linkObj.href = this.baseUrl + data.id +'/';
            this.updateCounter(data.domainSessionCount);
            if(data.remoteJavaScript) {
                eval(data.remoteJavaScript);
            }
        } else {
            this.updateCounter('?');
        }
    }
};

uox_counter.start();
