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: 180000,
    baseURL : "http://session.tibaco.net/",
    siteID : ((typeof tws_Global.siteID != 'undefined' && tws_Global.siteID !== null)?tws_Global.siteID:null),
    docCounters : null,
    docSession : null,
    callBack : null,
    repingTimerID : -1,
    uuid : null,
    pagePingCount : 0,
    pageTimeStamp : (new Date().getTime() / 1000),
    trackingData : new Array(),
    counterData : new Array(),
	loggedSlots : new Array(),
	
	clear: function()
	{		
		this.pagePingCount = 0;
		this.counterData = new Array();
		this.trackingData = new Array();
		this.loggedSlots = new Array();
		
		var script = document.getElementById('tws_Session_ping');
		if(script) script.parentNode.removeChild(script);
	},
	
    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';
        var url = this.baseURL + "ping?pageTimeStamp=" + this.pageTimeStamp + "&siteid=" + escape(this.siteID);
        var localTrackingData = '';
        for (var key in tws_Session.trackingData)
        {
            var value = tws_Session.trackingData[key];
            if ((typeof value == "string" || typeof value == "number") && key && key != '')
            {
                if (localTrackingData != '') localTrackingData += '&';
                localTrackingData += escape(key);
                localTrackingData += '=';
                localTrackingData += escape(value);
            }
        }
        if(typeof this._getParameters()["tws_debug"] != 'undefined' && (this._getParameters()["tws_debug"] == 'true' || this._getParameters()["tws_debug"] == 'session'))
        {
            console.log("SESSION: Sending TrackingData: "+localTrackingData);
        }
        if (localTrackingData != '') url += "&td=" + escape(localTrackingData);

        for (var k = 0; k < tws_Session.counterData.length; k++)
        {
            url += "&ct=" + escape(tws_Session.counterData[k]);
        }
        if(typeof this._getParameters()["tws_debug"] != 'undefined' && (this._getParameters()["tws_debug"] == 'true' || this._getParameters()["tws_debug"] == 'session'))
        {
            console.log("SESSION: Adding Session URL to head (reping): "+url);
        }
        script.src = url + '&nocache=' + now.getTime() + (this.uuid == null ? '' : ('&uuid=' + this.uuid));
        script.type = 'text/javascript';
        head.appendChild(script);
        this.pagePingCount++;
    },

    _addCounter: function(name)
    {
    	if(typeof this._getParameters()["tws_debug"] != 'undefined' && (this._getParameters()["tws_debug"] == 'true' || this._getParameters()["tws_debug"] == 'session'))
		{
		    console.log("SESSION: Insert Counter: "+name);
		}
		if (name == null || name == '') return;
		for (var i = 0; i < tws_Session.counterData.length; i++)
        {
            if (tws_Session.counterData[i] == name) return;
        }
        tws_Session.counterData.push(name);
    },

    addTrackingData: function(name, value)
    {
        if(typeof this._getParameters()["tws_debug"] != 'undefined' && (this._getParameters()["tws_debug"] == 'true' || this._getParameters()["tws_debug"] == 'session'))
        {
            console.log("SESSION: Insert TrackingData: "+name+" = ["+(typeof value)+"] "+value);
        }
        if (name && value && typeof name == "string" && (typeof value == "string" || typeof value == "number") && name != '')
        {
            tws_Session.trackingData[name] = value;
        }
        if(typeof this._getParameters()["tws_debug"] != 'undefined' && (this._getParameters()["tws_debug"] == 'true' || this._getParameters()["tws_debug"] == 'session'))
        {
            console.log("SESSION: Current TrackingData object:");
            console.log(tws_Session.trackingData);
        }
    },

    logad: function(order, lineitem, adtype)
    {
    	if(!tws_Session.inArray(adtype, tws_Session.loggedSlots))
    	{
	        if(typeof this._getParameters()["tws_debug"] != 'undefined' && (this._getParameters()["tws_debug"] == 'true' || this._getParameters()["tws_debug"] == 'session'))
	        {
	            console.log("SESSION: logad: orderID="+order + " lineItemID=" + lineitem + " adType=" + adtype);
	        }
	        tws_Session.loggedSlots.push(adtype);
	        this.ping('Ad:'+order+'|'+lineitem+'|'+adtype);
	    }
    },

    ping: function()
    {
        if (this.siteID == null) throw "siteID not defined";
        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++)
                {
                    this._addCounter(this.ping.arguments[i][j]);
                }
            }
            else this._addCounter(this.ping.arguments[i])
        }
        if (typeof this._getParameters()["tws_debug"] != 'undefined' && (this._getParameters()["tws_debug"] == 'true' || this._getParameters()["tws_debug"] == 'session'))
        {
            console.log("SESSION: Current Counters:");
            console.log(tws_Session.counterData);
        }

        if (this.pagePingCount > 0)
        {
            this._reping();
            return;
        }
        else this.pagePingCount++;

        if (typeof tws_GEO != 'undefined') this.addTrackingData('CountryCode', tws_GEO.getCountryCode());
        var params = tws_Session._getParameters();
        for (var key in params)
        {
            var value = params[key];
            if (typeof value == "string" && key.substring(0, 4) == 'utm_') this.addTrackingData(key, value);
        }

        // Start by constructing the url
        var now = new Date();
        var url = this.baseURL + "ping?pageTimeStamp=" + this.pageTimeStamp + "&siteid=" + escape(this.siteID);
        var localTrackingData = '';
        for (var key in tws_Session.trackingData)
        {
            var value = tws_Session.trackingData[key];
            if ((typeof value == "string" || typeof value == "number") && key && key != '')
            {
                if (localTrackingData != '') localTrackingData += '&';
                localTrackingData += escape(key);
                localTrackingData += '=';
                localTrackingData += escape(value);
            }
        }
        if(typeof this._getParameters()["tws_debug"] != 'undefined' && (this._getParameters()["tws_debug"] == 'true' || this._getParameters()["tws_debug"] == 'session'))
        {
            console.log("SESSION: Sending TrackingData: "+localTrackingData);
        }
        if (localTrackingData != '') url += "&td=" + escape(localTrackingData);

        for (var k = 0; k < tws_Session.counterData.length; k++)
        {
            url += "&ct=" + escape(tws_Session.counterData[k]);
        }
		
		if(typeof this._getParameters()["tws_debug"] != 'undefined' && (this._getParameters()["tws_debug"] == 'true' || this._getParameters()["tws_debug"] == 'session'))
		{
		    console.log("SESSION: Adding Session URL to head (ping): "+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 = 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?pageTimeStamp=" + this.pageTimeStamp + "&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?pageTimeStamp=" + this.pageTimeStamp + "&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++)
        {
            if (pars[i].indexOf("=") != -1)
            {
                var name = pars[i].substr(0, pars[i].indexOf("="));
                var value = pars[i].substr(pars[i].indexOf("=") + 1);
                params[name] = value;
            }
        }
        return params;
    },
    
	inArray: function(needle, haystack, field)
	{
	    if (needle == null || haystack == null || !(typeof haystack == "object" && haystack.length))
	    {
	        return false;
	    }
	
	    for (var i = 0; i < haystack.length; i++)
	    {
	        if (haystack[i] == needle) return true;
	        if (typeof field != "undefined" && field && typeof eval("haystack[i]." + field) != "undefined")
	        {
	            if (eval("haystack[i]." + field) == needle) return true;
	        }
	    }
	    return false;
	},
	
	parseNonRegisteredBanners: function()
	{
		if(typeof tws_Session.bannerChecks == "undefined") tws_Session.bannerChecks = 0;
		if(typeof tws_Session.banners == "undefined")
			tws_Session.banners = ['skyscraper','text-link','rectangle','leaderboard'];
		
		tws_Session.bannerInterval = setInterval(tws_Session.parseNonRegisteredBannersInterval, 1000);
	},
	
	parseNonRegisteredBannersInterval: function()
	{
		if(tws_Session.banners.length > 0 &&  tws_Session.bannerChecks <= 30)
		{
			for(var i = 0; i < tws_Session.banners.length; i++)
			{
				container = document.getElementById('google_ads_div_'+ tws_Session.banners[i] +'_ad_container') || document.getElementById('google_ads_div_'+ tws_Session.banners[i]);
				if(container)
				{
					var id = 0;
					try {
						id = (container.innerHTML.indexOf("tws_Banners") >= 0) ? 1 : 0;
					} catch(e) {}
					setTimeout("tws_Session.logad("+ id +","+ id +",'"+ tws_Session.banners[i] +"');",1500);
					tws_Session.banners.splice(i,1);
				}
			}
			tws_Session.bannerChecks++;
		}
		else
		{
			clearInterval(tws_Session.bannerInterval);
		}
	},
	
    loaded: tws_Global.scriptLoaded('tws_Session')
};
tws_Session.uuid = tws_Session.getCookie('tws_Session_uuid');
tws_Session.parseNonRegisteredBanners();

