﻿(function() {
	var startPageCookieName = "trr-elections-2010-startpage",
		sessionCookieName = 'trr-elections-2010-counting-session',
		cookiesStringsList = document.cookie.split(';'),
		startPageCookieValue;
		
	for(var i=0, currentString; currentString = cookiesStringsList[i];i++) {
		var splittedString = currentString.split('='),
			currentCookieName = splittedString[0],
			currentCookieValue = splittedString[1] || '';
			
		if (currentCookieName.match(sessionCookieName)) {
			return;
		} else if (currentCookieName.match(startPageCookieName)) {
			startPageCookieValue = decodeURIComponent(currentCookieValue);
		}
	}
	
	if (startPageCookieValue && startPageCookieValue != location.href) {
		var path = (function() {
			var cookiePathExp = new RegExp('(.+'+document.domain+')(\/.*(elections|eleicoes)\/?)'),
				splittedLocation = cookiePathExp.exec(location.href),
				path = (splittedLocation && splittedLocation[2]) ? splittedLocation[2] : undefined;
				
			if (!path) {
				path = '/';
			}
			
			return path;
		})();
		document.cookie = sessionCookieName+"=true; path="+path;
		location.replace(startPageCookieValue);
		return;
	}
	
	return;	
})();
