//the address of the rest of the tracking script
var img = "http://someone.muselive.com/tracker/track.php";

var _page="";
var _details;


//page is the name of the current page
function track(page, links, details) {
	//alert("tracking " + page);
	_page = page;
	if(details == undefined) details = 1; //default to using details
	_details = details;
	
	
	
	//do not track local files
	if(document.location.protocol=="file:") return;
	
	//do not track if no page set
	if(!page) return;
	
	//no tracking if logged in
	if(readCookie("meh")!= "") return;
	
	//add tracker to links
	if(links && links!="") addtracker(links);
	
	//read cookies
	var ts = readCookie("ts");	//session cookie - keeps track of which pages you visited so it will only count them once
	var tg = readCookie("tg");	//general cookie - how many times you visited the site
	if(tg=="") tg = 0; else tg = parseInt(tg);
	
	// If this is the first visit this session
	if(ts=="") {
		tg++;
		ts = page;
		send(page, "", details);
		//count unique visitors
		if(tg==1) send("unique", "", 1);
		//track referal
		if(document.referrer!="") send("referrer", document.referrer);
	} else {
		ts = visitpage(ts, page);
	}
	
	//save cookies
	var date = new Date();
	date.setTime(date.getTime()+(3*60*60*1000)); //3 hours
	var expires = "; expires="+date.toGMTString();
	document.cookie = "ts=" + ts + expires + "; path=/";
	
	date.setTime(date.getTime()+(365*24*60*60*1000)); //1 year
	expires = "; expires="+date.toGMTString();
	document.cookie = "tg=" + tg + expires + "; path=/";
	
}

function readCookie(name) {
	var s = document.cookie.indexOf(name + "=");
	if(s<0) return ""; else s+=3;
	var e = document.cookie.indexOf(";", s);
	if(e<s) e = document.cookie.length;
	return document.cookie.substring(s, e);
}

function visitpage(c, page) {
	if(c.indexOf(page)>=0) return c;
	send(page,"",_details);
	return c + "." + page;
}

//Automatically track download links, may make this do more
function addtracker(types) {
	var links = document.getElementsByTagName("a");
	for(var i=0; i<links.length; i++) {
		var path = "" + links[i];
		var re = new RegExp("(?:" + types + ")");
		var file = path.match(re); //	/\.(?:tar.gz|zip|rar)/
		if(file) {
			//add listener
			links[i].onclick = function() { click(this); };
		}
	}
}

function click(item) {
	var path = item.pathname;
	var i = path.lastIndexOf("/");
	if(i>0) {
		var file = path.substring(i+1, path.length);
		send(_page, file, _details);
	}
}

function send(page, link, details) {
	//alert("Tracking: " + page + "." + name + " [" + details + "]");
	var image = new Image(1,1);
	//parameters to send
	var s = "?page=" + page;
	if(link && link!="") s += "&link=" + link;
	if(details==1) s += "&detail=1";
	
	image.src = img + s;
	image.onload=function() { Void(); }
}

function Void() { 
	return; 
}
