var skycount = {
	url : '/common/infos.xml.php',
	req : false,
	infos : new Array(),
	ids : new Array(),
	intervals : new Array(),
	old_heure : null,
	heure_nav : 0,
	done : 0,
	callcount : 0,
	xhr_interval : 1, /* in minutes */


	debug : function(str)
	{
	/*	if (typeof console.log != 'undefined')
		{
		    console.log(str);
		}*/
	},

	init : function()
	{
		if (!skycount.req)
		{
			skycount.req = new RemoteStateSuggestions();
		}

		var i;

		if (skycount.req.http.readyState != 0)
		{
			skycount.req.http.abort();
		}
		while ((i = skycount.intervals.pop()))
		{
			clearInterval(i);
			skycount.debug('Clearing interval ' + i + '\n');
		}

		skycount.debug('skycount_init()\n');

		skycount.callcount += 1;
		// if(skycount.callcount > 15)
		if(skycount.callcount > 60)
		{
			/* au bout de 15 appels (donc 15 minutes), espacer de 5 minutes au lieu d'1 minute */
			skycount.xhr_interval = 5;
		}
		if(skycount.callcount > 336)
		{
			/* au bout de 24 heures on arrete de mettre a jour et donc de miam de la mémoire
			   on ne doit pas faire de refresh des pages : c'est mal ça fait de la fausse audience
			   (surtout si c'est toutes les heures).
			 */
			return;
		}

		skycount.find_ids();
		skycount.req.http.onreadystatechange = skycount.parse_xml;
		skycount.req.http.open('GET', skycount.url + '?t=' + (new Date().getTime()), true);
		skycount.req.http.send(null);
		setTimeout(skycount.init, 1000 * 60 * skycount.xhr_interval);
	},

	find_ids : function()
	{
		skycount.ids['blog'] = document.getElementById('nbr_blog');

 		skycount.ids['blog_today'] = document.getElementById('nbr_blog_today');
		skycount.ids['article'] = document.getElementById('nbr_article');
		skycount.ids['article_today'] = document.getElementById('nbr_article_today');
		skycount.ids['comment'] = document.getElementById('nbr_commentaire');
		skycount.ids['profils'] = document.getElementById('nbr_profils');
		skycount.ids['profils_today'] = document.getElementById('nbr_profil_today');
		skycount.ids['videos'] = document.getElementById('nbr_video_profil');
		skycount.ids['photos'] = document.getElementById('nbr_photo_profil');
	},

	do_parse_xml : function(node)
	{
		if (node && node.firstChild)
		{
			node = node.firstChild; /* on parcourt tous les fils, commencons par le premier */
		}
		else
		{
			node = false;
		}

		while (node)
		{
			var parent = node.parentNode;

			if (node.nodeType == 1)
			{
				skycount.do_parse_xml(node); /* il doit avoir des enfants, allez hop on y va */
			}
			else if (node.nodeType == 3 && parent.nodeName == 'heure')
			{
				skycount.old_heure = parseInt(node.data);
				skycount.debug('oldheure = ' + skycount.old_heure + '\n');
			}
			else if (node.nodeType == 3)
			{
				var grandparent = parent.parentNode;

				if ((typeof skycount.infos[grandparent.nodeName] != 'undefined')
				 && (typeof skycount.infos[grandparent.nodeName][parent.nodeName] != 'undefined'))
				{
					skycount.debug('Adding infos[' + grandparent.nodeName + '][' + parent.nodeName + '] = ' + parseInt(node.data) + ' \n')
					skycount.infos[grandparent.nodeName][parent.nodeName] = parseInt(node.data);
				}
			}
			node = node.nextSibling; /* fils suivant */
		}
	},

	catchup_and_start : function(id, group, type)
	{
		var ketchup;

		if (!skycount.check_values(id, group, type))
		{
			skycount.debug('prout sur ' + group + '/' + type + '\n');
			return;
		}

		if (skycount.heure_nav < 1)
		{
			skycount.heure_nav = Math.ceil((new Date().getTime()) / 1000);
			if (cur_heure == 4815162342)
			{
			    cur_heure = skycount.heure_nav;
			}
		}
		else
		{
			/*
				cur_heure vient de ZXTM (sauf si c'est 4815162342 auquel cas ya eu un soucis).
				On l'a chargé une fois au début, si on est la c'est que du temps s'est écoulé
				et que donc la valeur n'est plus correcte. Du coup, on fait la différence entre
				l'heure qu'on a enregistrée au précédent passage et l'heure courante pour la mettre a jour.
				De plus on enregistre la nouvelle valeur pour re-décaler au prochain passage.
			*/
			if (cur_heure == 4815162342)
			{
			    cur_heure = skycount.heure_nav;
			}
			cur_heure = cur_heure - skycount.heure_nav;
			skycount.heure_nav = Math.ceil((new Date().getTime()) / 1000);
			cur_heure = cur_heure + skycount.heure_nav;
		}

		/*
			on regarde quand est ce que le xml a été mis a jour (old_heure), et on compare avec cur_heure.
			on augmente le total de la différence * le nombre de blogs dans une intervalle / l'intervalle en secondes.
		 */
		ketchup = Math.floor(((cur_heure - skycount.old_heure) * skycount.infos[group]['nbadd']) / (skycount.infos[group]['interval'] / 1000));

		skycount.debug((cur_heure - skycount.old_heure) + ' seconds elapsed since last update to file (interval is ' + skycount.infos[group]['interval'] + '), need to add ' + ketchup + ' to catch up for ' + id + '/' + group + '/' + type + '\n');

		skycount.infos[group][type] += ketchup;
		skycount.set_value(id, group, type);
		skycount.intervals.push(setInterval('skycount.set_value(\'' + id + '\', \'' + group + '\', \'' + type + '\')', skycount.infos[group]['interval']));
		skycount.debug(skycount.intervals);
	},

	check_values : function(id, group, type)
	{
		skycount.debug('skycount_check_values() :: id: ' + id + '; group: ' + group + '; type: ' + type + '\n');
		skycount.debug('ids[id]: ' + skycount.ids[id] + '; infos[group][type]: ' + skycount.infos[group][type] + '; infos[group]["interval"]: ' + skycount.infos[group]['interval'] + '\n');
		if (!skycount.ids[id] || !skycount.infos[group][type] || !skycount.infos[group]['interval'])
		{
			return false;
		}
		return true;
	},

	init_array_and_elem : function(id, group)
	{
		skycount.infos[group] = new Array();
		skycount.infos[group]['total']    = 0;
		skycount.infos[group]['nbadd']    = 0;
		skycount.infos[group]['interval'] = 0;
		skycount.infos[group]['nbtoday']  = 0;

		if (skycount.ids[id])
		{
			/* texte sur la home */
			if (!skycount.ids[id].firstChild)
			{
				var c = document.createTextNode('');
				skycount.ids[id].appendChild(c);
			}

			skycount.debug('Id ' + id + '/' + group + ' initted.\n');
		}
		else
		{
			skycount.debug('Could not init id ' + id + '/' + group + '\n');
		}
	},


	parse_xml: function()
	{
	 	if (typeof(skycount.req) === 'undefined')
		{
		 	return;
		}
		if (skycount.req.http.readyState == 4 && skycount.req.http.status == 200)
		{
			var node = skycount.req.http.responseXML;

			skycount.init_array_and_elem('blog', 'blog');
			skycount.init_array_and_elem('blog_today', 'blog');
			skycount.init_array_and_elem('article', 'article');
			skycount.init_array_and_elem('article_today', 'article');
			skycount.init_array_and_elem('comment', 'comment');
			skycount.init_array_and_elem('profils', 'profils');
			skycount.init_array_and_elem('profils_today', 'profils');
			skycount.init_array_and_elem('videos', 'videos');
			skycount.init_array_and_elem('photos', 'photos');
			skycount.do_parse_xml(node);

			skycount.catchup_and_start('blog', 'blog', 'total');
			skycount.catchup_and_start('blog_today', 'blog', 'nbtoday');
			skycount.catchup_and_start('article', 'article', 'total');
			skycount.catchup_and_start('article_today', 'article', 'nbtoday');
			skycount.catchup_and_start('comment', 'comment', 'total');
			skycount.catchup_and_start('profils', 'profils', 'total');
			skycount.catchup_and_start('profils_today', 'profils', 'nbtoday');
			skycount.catchup_and_start('videos', 'videos', 'total');
			skycount.catchup_and_start('photos', 'photos', 'total');
		}
		else
		{
			skycount.debug('skycount_parse_xml(): not ready\n');
		}
	},

	set_value : function (id, group, type)
	{
		skycount.infos[group][type] += skycount.infos[group]['nbadd'];
		skycount.update_count(id, skycount.infos[group][type], type);

		skycount.debug('skycount_set_value(' + id + ', ' + group + ', ' + type + ')\n');
	},

	update_count : function (id, total, type)
	{
		if (skycount.ids[id])
		{
			skycount.debug('Updating ' + id + '/' + type + '\n');
			if (total > 0)
			{
				skycount.ids[id].firstChild.data =  skycount.format_count(total);
			}
		}
		else
		{
			skycount.debug('Could not update ' + id + '\n');
		}
	},

	format_count : function(count)
	{
		count = count.toString();
		for (var i = count.length - 3; i > 0 ; i -= 3)
		{
			count = count.slice(0, i) + locale_thousands_sep + count.slice(i, count.length);
		}
		return count;
	}
}
onload_funcs.push(skycount.init);
