if(typeof tws_Global == 'undefined' || typeof tws_Global === null) {
	var tws_Global = {
		loaded: [],
		callbacks: [],

		scriptLoaded: function(objName)
		{
			tws_Global.loaded.push(objName);
			setTimeout("tws_Global.runCallbacks()",1);
		},

		runCallbacks: function()
		{
			for(var i =0 ; i < tws_Global.callbacks.length; i++)
			{
				if(tws_Global.callbacks[i] !== true)
				{
					try
					{
						tws_Global.callbacks[i]();
						tws_Global.callbacks[i] = true;
					}
					catch(e)
					{
						try { console.log(e); } catch(e) {}
					}
				}
			}
		},

		setCallback: function(func)
		{
			try
			{
				if(!func())
				{
					tws_Global.callbacks.push(func);
				}
			}
			catch(e)
			{
				tws_Global.callbacks.push(func);
			}
		}
	}
};

var tws_Session =
{
    pingInterval: 300000,
    baseURL : "http://session.tibaco.net/",
    siteID : ((typeof tws_Global.siteID != 'undefined' && tws_Global.siteID !== null)?tws_Global.siteID:null),
    docCounters : null,
    docSession : null,
    url : null,
    callBack : null,
    repingTimerID : -1,
    uuid : null,
    trackingData : new Array(),

    setSiteID: function(siteID)
    {
    	tws_Global.siteID = siteID;
        this.siteID = siteID;
    },

    getCookie: function(check_name)
    {
        // first we'll split this cookie up into name/value pairs
        // note: document.cookie only returns name=value, not the other components
        var a_all_cookies = document.cookie.split( ';' );
        var a_temp_cookie = '';
        var cookie_name = '';
        var cookie_value = '';

        for ( i = 0; i < a_all_cookies.length; i++ )
        {
            // now we'll split apart each name=value pair
            a_temp_cookie = a_all_cookies[i].split( '=' );

            // and trim left/right whitespace while we're at it
            cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');

            // if the extracted name matches passed check_name
            if ( cookie_name == check_name )
            {
                // we need to handle case where cookie has no value but exists (no = sign, that is):
                if ( a_temp_cookie.length > 1 )
                {
                        cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
                }
                // note that in cases where cookie is initialized but no value, null is returned
                return cookie_value;
                break;
            }
            a_temp_cookie = null;
            cookie_name = '';
        }
        return null;
    },

    setCookie: function(name, value, expires, path, domain, secure)
    {
        // set time, it's in milliseconds
        var today = new Date();
        today.setTime( today.getTime() );

        /*
        if the expires variable is set, make the correct
        expires time, the current script below will set
        it for x number of days, to make it for hours,
        delete * 24, for minutes, delete * 60 * 24
        */
        if ( expires )
        {
            expires = expires * 1000 * 60 * 60 * 24;
        }
        var expires_date = new Date( today.getTime() + (expires) );

        document.cookie = name + "=" +escape( value ) +
        ( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) +
        ( ( path ) ? ";path=" + path : "" ) +
        ( ( domain ) ? ";domain=" + domain : "" ) +
        ( ( secure ) ? ";secure" : "" );
    },

    setUUID: function(uuid)
    {
        this.uuid = uuid;
        if (uuid)
        {
            this.setCookie('tws_Session_uuid', uuid, 365, '/', '', '' );
        }
    },

    _stringToXML: function(string)
    {
        if (string == null) return null;
        var xmlDoc;
        if (window.ActiveXObject)
        {
            xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
            xmlDoc.loadXML(string);
        }
        else if (document.implementation && document.implementation.createDocument)
        {
            var domParser = new DOMParser();
            xmlDoc = domParser.parseFromString(string, 'application/xml');
        }
        return xmlDoc;
    },

    _reping: function()
    {
        // Send the ping to the server
        var now = new Date();
        var script = document.getElementById('tws_Session_ping');
        var head = document.getElementsByTagName("head")[0];
        if (script) head.removeChild(script);
        script = document.createElement('script');
        script.id = 'tws_Session_ping';
        script.src = this.url + '&nocache=' + now.getTime() + (this.uuid == null ? '' : ('&uuid=' + this.uuid));
        script.type = 'text/javascript';
        head.appendChild(script);
    },

    addTrackingData: function(name, value)
    {
        if (name && value && typeof name == "string" && typeof value == "string" && name != '')
        {
            tws_Session.trackingData[name] = value;
        }
    },

    ping: function()
    {
        if (this.siteID == null) throw "siteID not defined";

        var localTrackingData = '';
        var params = tws_Session._getParameters();
        for (var key in params)
        {
            var value = params[key];
            if (typeof value == "string" && key.substring(0, 4) == 'utm_')
            {
                if (localTrackingData != '') localTrackingData += '&';
                localTrackingData += escape(key);
                localTrackingData += '=';
                localTrackingData += escape(value);
            }
        }
        for (var key in tws_Session.trackingData)
        {
            var value = tws_Session.trackingData[key];
            if (typeof value == "string" && key && key != '')
            {
                if (localTrackingData != '') localTrackingData += '&';
                localTrackingData += escape(key);
                localTrackingData += '=';
                localTrackingData += escape(value);
            }
        }

        // Start by constructing the url
        var now = new Date();
        var url = this.baseURL + "ping?siteid=" + escape(this.siteID);
        if (localTrackingData != '') url += "&td=" + escape(localTrackingData);

        for (var i = 0; i < this.ping.arguments.length; i++)
        {
            if (this.ping.arguments[i] instanceof Array)
            {
                for (var j = 0; j < this.ping.arguments[i].length; j++)
                {
                    url += "&ct=" + escape(this.ping.arguments[i][j]);
                }
            }
            else url += "&ct=" + escape(this.ping.arguments[i]);
        }

        this.url = url;

        // Send the ping to the server
        var head = document.getElementsByTagName("head")[0];
        var script = document.createElement('script');
        script.id = 'tws_Session_ping';
        script.src = this.url + '&firstping&nocache=' + now.getTime() + (this.uuid == null ? '' : ('&uuid=' + this.uuid));
        script.type = 'text/javascript';
        head.appendChild(script);

        if (this.repingTimerID != -1) clearInterval(this.repingTimerID);
        this.repingTimerID = setInterval("tws_Session._reping()", this.pingInterval);
    },

    fetchCounters: function()
    {
        if (this.siteID == null) throw "siteID not defined";

        // Start by constructing the url
        var now = new Date();
        var url = this.baseURL + "counters?nocache=" + now.getTime() + "&output=js&siteid=" + escape(this.siteID) + (this.uuid == null ? '' : ('&uuid=' + this.uuid));

        for (var i = 0; i < this.fetchCounters.arguments.length; i++)
        {
            if (this.fetchCounters.arguments[i] instanceof Array)
            {
                for (var j = 0; j < this.fetchCounters.arguments[i].length; j++)
                {
                    url += "&ct=" + escape(this.fetchCounters.arguments[i][j]);
                }
            }
            else url += "&ct=" + escape(this.fetchCounters.arguments[i]);
        }

        var script = document.getElementById('tws_Session_counters');
	var head = document.getElementsByTagName("head")[0];
        if (script) head.removeChild(script);
        script = document.createElement('script');
        script.id = 'tws_Session_counters';
        script.src = url;
        script.type = 'text/javascript';
        head.appendChild(script);
    },

    getCounter: function(name)
    {
        var result = -1;

        if (this.docCounters)
        {
            if (name == null || typeof name == 'undefined') result = this.docCounters.getElementsByTagName("site")[0].getAttribute("sessioncount");
            else
            {
                var nodes = this.docCounters.getElementsByTagName("counter");
                for (var i = 0; i < nodes.length; i++)
                {
                    if (nodes[i].getAttribute("name") == name)
                    {
                        result = nodes[i].getAttribute("sessioncount");
                        break;
                    }
                }
            }
        }

        return result;
    },

    fetchSession: function()
    {
        if (this.siteID == null) throw "siteID not defined";

        // Start by constructing the url
        var now = new Date();
        var url = this.baseURL + "fetchsession?nocache=" + now.getTime() + "&output=js&siteid=" + escape(this.siteID) + (this.uuid == null ? '' : ('&uuid=' + this.uuid));
        var script = document.getElementById('tws_Session_fetchsession');
	var head = document.getElementsByTagName("head")[0];
        if (script) head.removeChild(script);
        script = document.createElement('script');
        script.id = 'tws_Session_fetchsession';
        script.src = url;
        script.type = 'text/javascript';
        head.appendChild(script);
    },

    getSession: function()
    {
        var result = null;

        var uuid = (this.docSession.getElementsByTagName("session")  && this.docSession.getElementsByTagName("session")[0]) ? this.docSession.getElementsByTagName("session")[0].getAttribute("uuid") : null;
        if (this.docSession && uuid)
        {
            result = new Object();
            result.uuid = uuid;
            result.startTimeStamp = this.docSession.getElementsByTagName("start")[0].getAttribute("timestamp");
            result.endTimeStamp = this.docSession.getElementsByTagName("end")[0].getAttribute("timestamp");
            result.startTrackingData = this.docSession.getElementsByTagName("start")[0].getElementsByTagName("trackingdata")[0].textContent;
            result.endTrackingData = this.docSession.getElementsByTagName("end")[0].getElementsByTagName("trackingdata")[0].textContent;
            result.counters = new Array();
            var ctrs = this.docSession.getElementsByTagName("counter");
            if (ctrs)
            {
                for (var i = 0; i < ctrs.length; i++)
                {
                    var c = new Object();
                    c.name = ctrs[i].getAttribute("name");
                    c.count = ctrs[i].getAttribute("totalcount");
                    c.duration = ctrs[i].getAttribute("totalseconds");
                    result.counters.push(c);
                }
            }
        }

        return result;
    },

    _cb: function(xml)
    {
        this.docCounters = this._stringToXML(xml);
        if (this.callBack != null) this.callBack();
    },

    _cbs: function(xml)
    {
        this.docSession = this._stringToXML(xml);
        if (this.callBack != null) this.callBack();
    },

    setCallBackFunction: function(callBackFunction)
    {
        this.callBack = callBackFunction;
    },

    _getParameters: function()
    {
        var string  = window.location.href.substring(window.location.href.indexOf("?") + 1);
        var pars    = string.replace("&amp;", "&").split("&");
        var params  = new Array();
        for (var i = 0; i < pars.length; i++)
        {
            var arr = pars[i].split("=");
            params[arr[0]] = arr[1];
        }
        return params;
    },

    loaded: tws_Global.scriptLoaded('tws_Session')
};
tws_Session.uuid = tws_Session.getCookie('tws_Session_uuid');
