/* This source code is Copyright (c) Tailsweep 2007-2010 */
if (typeof(tsCsId)=="undefined") {var tsCsId=0;}
if (typeof(tsTrackClicks)=="undefined") {var tsTrackClicks=false;}
if (typeof(window.tsCsRendered)=="undefined") {window.tsCsRendered=0;}
if (typeof(window.tsCsIdAnalyticsRendered)=="undefined") {window.tsCsIdAnalyticsRendered={};}
var baseTsUrl = "";


if(window.tsCsIdAnalyticsRendered[tsCsId])
{
    ++window.tsCsIdAnalyticsRendered[tsCsId];
}
else
{
    window.tsCsIdAnalyticsRendered[tsCsId] = 1;
}

if(window.tsCsIdAnalyticsRendered[tsCsId] <= 1)
{
    /// new code for ga ///
    var unixtime=Math.round((new Date).getTime()/1000);
    var theDomain = getDomain();

    var tsa = getCookieValue("_tsa");
    var tsb = getCookieValue("_tsb");
    var tsc = getCookieValue("_tsc");
    var tsaToLog = "-";

    if(tsa && tsb && tsc)
    {
        //update tsa to extend the expiration date
        setA(theDomain,tsa);

        //update tsb with pi
        var tsbs=tsb.split(".");
        tsbs[1] = parseInt(tsbs[1])+1;
        setB(theDomain,tsbs.join("."));
        tsaToLog=tsa;
    }
    else
    {
        var domainHash = hashIt(theDomain);
        if(!tsa)
        {
            if(testPersistentCookie())
            {
                //total reset
                tsaToLog = domainHash+"."+makeUid()+"."+unixtime+"."+unixtime+"."+unixtime+".1";

                setA(theDomain,tsaToLog);
                setB(theDomain,domainHash+".1.10."+unixtime);
                setC(theDomain,domainHash);
            }
            else
            {
                tsaToLog = "0.0.0.0.0.0";
            }
        }
        else
        {
            //new session!!!
            var tsas=tsa.split(".");
            tsas[3] = tsas[4];
            tsas[4] = unixtime;
            tsas[5] = parseInt(tsas[5])+1;

            tsaToLog = tsas.join(".");

            setA(theDomain,tsaToLog);
            setB(theDomain,domainHash+".1.10."+unixtime);
            setC(theDomain,domainHash);
        }
    }
    /// end new code ///

    if (typeof(tsCType)=="undefined") {var tsCType=1;}
    if (typeof(tsUrl)=="undefined") {var tsUrl="";}
    if (typeof(tsST)=="undefined") {var tsST=0;}
    if (typeof(tsCPath)=="undefined") {var tsCPath="/";}
    if (typeof(tsAnalyticsAsync)=="undefined") {var tsAnalyticsAsync = false;}


    var _tsbd=document;
    var _tsdl=_tsbd.location;
    var _tsdlh = "";
    var _tsBH = "";
    var _tsDM= "";
    var _tsHO = "";
    var _tsLP = "";
    var _tsQu = "";
    var _tsT =  "";
    var _tsFpc = "";
    var _tsSession =  "";
    var _tsUid = "";
    var _tsUV = "";
    var _tsRef = "";
    var _tsCh = "";
    var tsFeedUrl = "";

    if (_tsdl.hostname && _tsdl.hostname != "") { _tsHO = _tsES(_tsdl.hostname); }
    if (_tsdl.search && _tsdl.search != "") { _tsQu = _tsES(_tsdl.search); }
    //if (_tsdl.hash && _tsdl.hash != "") { _tsdlh=_tsdl.href.substring(_tsdl.href.indexOf('#')); }
    if (_tsbd.domain &&  _tsbd.domain != "") {  _tsDM = _tsbd.domain; }
    if(_tsdl.pathname && _tsdl.pathname != "") { _tsLP = _tsdl.pathname;}
    if(_tsbd.referrer && _tsbd.referrer != "") { _tsRef = _tsES(_tsbd.referrer);}
    //if (_tsbd.title && _tsbd.title != "") { _tsT = _tsES(_tsbd.title); }
    if(typeof(document.characterSet) != 'undefined') { _tsCh = document.characterSet; }
    else if(typeof(document.defaultCharset) != 'undefined') { _tsCh = document.defaultCharset; }
    else if(typeof(document.charset) != 'undefined') { _tsCh = document.charset; }

    var nTsUrl="";
    if(tsUrl != "")
    {
        nTsUrl = _tsES(tsUrl);
        //nTsUrl = escape(tsUrl);
    }

    _tsFpc = getCookieValue("ts_site_cookie");
    if(!_tsFpc || isNaN(_tsFpc))
    {
        _tsFpc = 0;
    }
    _tsFpc++;
    if(tsST == 1 || (tsST == 0 && tsCsId > 0))
    {
    	writePersistentCookie("ts_site_cookie", _tsFpc, "Date", 7);
    }
    else if(tsST == 2 || tsMId > 0)
    {
        if(tsCPath != "/")
        {
        	writePersistentCookie("ts_site_cookie", _tsFpc, "Date", 7);
        }
        else
        {
            var match = new RegExp("^(/.*?)/").exec(_tsLP);
            if(match && match.length > 0)
            {
            	writePersistentCookie("ts_site_cookie", _tsFpc, "Date", 7);
            }
        }
    }

    _tsSession = getCookieValue("ts_session") ? getCookieValue("ts_session") : "";
    _tsUid = getCookieValue("ts_uid") ? getCookieValue("ts_uid") : "";
    _tsUV = getCookieValue("ts_uv") ? getCookieValue("ts_uv") : "";

    baseTsUrl = tsCsId + "?tsSession="+_tsSession+"&tsUid="+_tsUid+"&tsUV="+_tsUV+"&tsUrl="+nTsUrl+tsGetUrl()+"&tsa="+tsaToLog;
    var _tsUrl = "http://script.tailsweep.com/csHit/"+baseTsUrl;
    
    var url = '<img src="'+_tsUrl +'" border="0" width="0" height="0" style="width:0px;height:0px;margin:0;padding:0;border-style:none;border-width:0;display:none;" />';
    if(tsAnalyticsAsync)
    {
        ts_addOnLoadFunction(ts_async_analytics, url);
    }
    else
    {
        document.write(url);
    }
}

function ts_async_analytics(url)
{
    document.write(url);
}

function getPlacementId(name)
{
    if(name == "midContent" || name == "mid_content") { return "2";}
    if(name == "adColumn" || name == "right") { return "1";}
    if(name == "top") { return "4";}
    if(name == "adColumn2" || name == "extendedRight" ||  name == "extended_right") { return "3";}
    if(name == "textColumn" || nam =="text_column") { return "5";}
    return "";
}

function handleData(data)
{
    writePersistentCookie("ts_session", data.session, "Hours", 1);
    writePersistentCookie("ts_uid", data.uid, "Years", 10);
    var _tsUV = getCookieValue("ts_uv");
    if(!_tsUV)
    {
        writePersistentCookie("ts_uv", data.uniqueVisit, "Date", 7);
    }
}

String.prototype.replaceAll=function(s1, s2)
{
    return this.replace(new RegExp(s1,"gim"), s2);
}

String.prototype.trim = function()
{
    return this.replace(/^\s+|\s+$/g, '') ;
}

String.prototype.tsStartsWith = function(str)
{return (this.match("^"+str)==str)}

String.prototype.tsEndsWith = function(str)
{return (this.match(str+"$")==str)}

function tsGetUrl()
{
    var s="";
    s+="&tsUUI="+getRand();
    s+="&tsT=" + _tsT;
    s += "&tsLho=" + _tsHO;
    s += "&tsCh=" + _tsCh;
    //s += "&tsLha=" + _tsdlh;
    s += "&tsQu=" + _tsQu;
    s += "&tsRef=" + _tsRef;
    s += "&tsLP="+_tsLP + getBrowserProperties();
    return s;
}

function getBrowserProperties()
{
    return '&tsSW='+self.screen.width+'&tsSH='+self.screen.height+'&tsSC='+self.screen.colorDepth+'&tsPD='+self.screen.pixelDepth;
}

function _tsVoid() { return; }

function _tsES(s,u)
{
    if (typeof(encodeURIComponent) == 'function')
    {
        if (u)
            return encodeURI(s);
        else
            return encodeURIComponent(s);
    }
    else
    {
        return escape(s);
    }
}
function _tsDS(s,u)
{
    if (typeof(encodeURIComponent) == 'function')
    {
        if (u)
            return decodeURI(s);
        else
            return decodeURIComponent(s);
    }
    else
    {
        return unescape(s);
    }
    //decodeURIComponent(encoded.replace(/\+/g,  " ")
}

// public method for url encoding
function urlEncode (string)
{
    return _tsES(utf8_encode(string));
}

// public method for url decoding
function urlDecode(string)
{
    return utf8_decode(unescape(string));
}

function utf8_encode(string)
{
    string = string.replace(/\r\n/g,"\n");
    var utftext = "";

    for (var n = 0; n < string.length; n++)
    {
        var c = string.charCodeAt(n);

        if (c < 128)
        {
            utftext += String.fromCharCode(c);
        }
        else if((c > 127) && (c < 2048))
        {
            utftext += String.fromCharCode((c >> 6) | 192);
            utftext += String.fromCharCode((c & 63) | 128);
        }
        else
        {
            utftext += String.fromCharCode((c >> 12) | 224);
            utftext += String.fromCharCode(((c >> 6) & 63) | 128);
            utftext += String.fromCharCode((c & 63) | 128);
        }
    }
    return utftext;
}

function utf8_decode(utftext)
{
    var string = "";
    var i = 0;
    var c = c1 = c2 = 0;

    while ( i < utftext.length )
    {
        c = utftext.charCodeAt(i);
        if (c < 128)
        {
            string += String.fromCharCode(c);
            i++;
        }
        else if((c > 191) && (c < 224))
        {
            c2 = utftext.charCodeAt(i+1);
            string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
            i += 2;
        }
        else
        {
            c2 = utftext.charCodeAt(i+1);
            c3 = utftext.charCodeAt(i+2);
            string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
            i += 3;
        }
    }
    return string;
}

function getRand()
{
    return getRandomNr(2147483647);
}

function getRandomNr(max)
{
    return Math.floor(Math.random()*(max));
}

function writePersistentCookie (CookieName, CookieValue, periodType, offset)
{
  var expireDate = new Date ();
  offset = offset / 1;

  if(periodType === "Years")
  {
	 var year = expireDate.getYear();
     if (year < 1000){ year = year + 1900;}
     expireDate.setYear(year + offset);
  }
  else
  {
     expireDate["set"+periodType](expireDate["get"+periodType]() + offset);
  }

  document.cookie = escape(CookieName ) + "=" + escape(CookieValue) + "; expires=" + expireDate.toGMTString() + "; path=/";
}

function writeSessionCookie (cookieName, cookieValue)
{
    if (testSessionCookie())
    {
        document.cookie = escape(cookieName) + "=" + escape(cookieValue) + "; path=/";
        return true;
    }
    else return false;
}

function testSessionCookie ()
{
    document.cookie ="testSessionCookie=Enabled";
    if (getCookieValue ("testSessionCookie")=="Enabled")
        return true
    else
        return false;
}

function getCookieValue (cookieName)
{
    var exp = new RegExp (escape(cookieName) + "=([^;]+)");
    if (exp.test (document.cookie + ";")) {
        exp.exec (document.cookie + ";");
        return unescape(RegExp.$1);
    }
    else return false;
}

function testPersistentCookie ()
{
    writePersistentCookie("testPersistentCookie", "Enabled", "Minutes", 1);
    if (getCookieValue ("testPersistentCookie")=="Enabled")
        return true
    else
        return false;
}

function ts_addOnLoadFunction(theFunction, arg)
{
    var nowOnload = window.onload;
    window.onload = function ()
    {
        theFunction(arg);
        if(nowOnload != null && typeof(nowOnload) == 'function') {
            nowOnload();
        }
    }
}

function loadScript(url)
{
    var line = '<scr'+'ipt src=\"' + url + '\" type=\"text/javascript\"></scr'+'ipt>';
    document.write(line);
}

//new functions for ga
function validate(d){
    // Validation
    return undefined==d||"-"==d||""==d;
}

function hashIt(str){
    var hashen=1;
    var c=0;

    // If not bad string
    if(!validate(str)){
        hashen=0;
        // process each char in str
        for(var i=str["length"]-1;i>=0;i--)
        {
            var ch = str.charCodeAt(i);
            hashen=(hashen<<6&268435455)+ch+(ch<<14);
            c=hashen&266338304;
            hashen=c!=0?hashen^c>>21:hashen;
        }
    }
    return hashen;
}

function simpleRandom(){
    // Simple random function
    return Math.round(Math.random()*2147483647);
}

function browserHash(){
    // Make the Random Unique ID even more unique using some browser props.
    var h=document["cookie"]?document["cookie"]:"";
    var s=[navigator.appName,navigator.version,navigator.language?navigator.language:navigator.browserLanguage,navigator.platform,navigator.userAgent,navigator.javaEnabled()?1:0].join("");

    if(window.screen)
    {
        s+=window.screen.width+"x"+window.screen.height+window.screen.colorDepth;
    }
    else if(window.java)
    {
        var l=java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        s+=l.screen.width+"x"+l.screen.height;
    }
    s+=h;
    s+=document.referrer?document.referrer:"";

    var k=s["length"];

    var o=window.history["length"];
    while(o>0)
    {
        s+=o--^k++;
    }

    return hashIt(s);
}

function makeUid()
{
    // This function returns the Random Unique ID
    var y=(simpleRandom()^browserHash())*2147483647;
    return y;
}

function l(d,a,c){
    c=undefined==c?d["length"]:c;
    return d.substring(a,c)
}

function getDomain(){
    var d=document.domain;
    if("www."==l(d,0,4)) d=l(d,4);
    return d.toLowerCase();
}

function setC(d,domainHash){
    document.cookie = "_tsc=" + escape(domainHash) + "; path=/; domain="+d;
}

function setA(d,val){
    var offset=2; //2 years
    var expireDate = new Date ();
    var year = expireDate.getYear();
    // Note some browsers give only the years since 1900, and some since 0.
    if (year < 1000) year = year + 1900;
    expireDate.setYear(year + offset);

    document.cookie = "_tsa=" + escape(val) + "; expires=" + expireDate.toGMTString() + "; path=/; domain="+d;
}

function setB(d,val){
    var offset=30; //2 years
    var expireDate = new Date ();
    var year = expireDate.getYear();
    var minutes = expireDate.getMinutes();
    // Note some browsers give only the years since 1900, and some since 0.
    if (year < 1000) year = year + 1900;
    expireDate.setMinutes(minutes + offset);

    document.cookie = "_tsb=" + escape(val) + "; expires=" + expireDate.toGMTString() + "; path=/; domain="+d;
}

var xOffset,yOffset;
var tempX = 0;
var tempY = 0;
var ifr = document.createElement('iframe');
var ifrId = "ts_click_iframe";
/*
 style="display:none;" scrolling="no" marginwidth="0" marginheight="0" frameborder="0"
 */
ifr.style.display = "none"
ifr.frameborder="0";
ifr.marginheight="0";
ifr.marginwidth="0";
ifr.scrolling="no";
ifr.id = ifrId;
ifr.src= "";
ifr.width= "0";
ifr.height= "0";

var B = document.getElementsByTagName('body');
if(tsTrackClicks)
{
    if(B)
    {
        var body = B[0];
        body.appendChild(ifr);

        //detect browser
        var IE = document.all?true:false
        if (!IE) {
            document.captureEvents(Event.MOUSEMOVE)
        }
        //find the position of the first item on screen and store offsets
        //find the first item on screen (after body)
        var firstElement=body.childNodes[1];
        //find the offset coordinates
        xOffset=tsfindPosX(firstElement);
        yOffset=tsfindPosY(firstElement);
        if (IE)
        { // In IE there's a default margin in the page body. If margin's not defined, use defaults
            var marginLeftExplorer  = parseInt(body.style.marginLeft);
            var marginTopExplorer   = parseInt(body.style.marginTop);
            /*assume default 10px/15px margin in explorer*/
            if (isNaN(marginLeftExplorer)) {marginLeftExplorer=10;}
            if (isNaN(marginTopExplorer)) {marginTopExplorer=15;}
            xOffset=xOffset+marginLeftExplorer;
            yOffset=yOffset+marginTopExplorer;
        }
        /*attach a handler to the onmousedown event that calls a function to store the values*/
        document.onmousedown = tsHandleMouseEvent;
        //document.onclick = captureClick;
        if (document.captureEvents) document.captureEvents(Event.MOUSEDOWN);
    }
}

/*Functions*/
/*Find positions*/
function tsfindPosX(obj)
{
    var curleft = 0;
    if (obj.offsetParent)
    {
        while (obj.offsetParent)
        {
            curleft += obj.offsetLeft
            obj = obj.offsetParent;
        }
    }
    else if (obj.x)
    {
        curleft += obj.x;
    }
    return curleft;
}

function tsfindPosY(obj)
{
    var curtop = 0;
    if (obj.offsetParent)
    {
        while (obj.offsetParent){
            curtop += obj.offsetTop
            obj = obj.offsetParent;
        }
    }
    else if (obj.y)
    {
        curtop += obj.y;
    }
    return curtop;
}
function tsHandleMouseEvent(e)
{

    if (IE)
    {
        tempX = event.clientX + document.body.scrollLeft
        tempY = event.clientY + document.body.scrollTop
    }
    else
    {
        tempX = e.pageX
        tempY = e.pageY
    }
    tempX-=xOffset;
    tempY-=yOffset;
    var destUrl = '';
    var targ;
    if (e.target)
    {
        targ = e.target;
    }
    else if (e.srcElement)
    {
        targ = e.srcElement;
    }
    if (targ.nodeType == 3) // defeat Safari bug
    {
        targ = targ.parentNode;
    }
    if(targ && targ.href)
    {
        destUrl = targ.href;
    }
    var Q = "x="+tempX+'&y='+tempY+'&dx='+xOffset+'&dy='+yOffset+'&toUrl='+destUrl;
    ifr.src = "http://script.tailsweep.com/siteclick/"+baseTsUrl+"&"+Q;
    return true;
}

function tsGetFeedUrl()
{
    var l = document.getElementsByTagName('link');
    if(l && l.length > 0)
    {
        for(var i = 0;i < l.length; i++)
        {
            if(l[i].rel == 'alternate')
            {
                if(l[i].type.indexOf('xml') != -1)
                {
                    var tsFeedUrl = l[i].href;
                    return tsFeedUrl;
                }
            }
        }
    }
    return "";
}
