Ext.namespace('Ext.ux');

Ext.ux.Stats = (function(){
	
	var initialized = false;
	
	return {
		
		
		linkClass 	: '.stats',
		linkClassBody : '.stats-page',
		
		/***********************************************************************************/
		init : function(){
			if(!initialized){
				this.initEvent();
				initialized = true;
			}
		},
		
		initEvent : function(){

			/* Stats pour une région */
			if(Ext.getBody().dom.className.search("stats-region") > -1){
				var id = Ext.getBody().id.split('_');
				this.setStatsRegion(id[1]);
			}
			
			/* Stats pour une territoire */
			var linkStatsTerritoire = Ext.select('.stats-territoire');
			linkStatsTerritoire.on('click', this.setStatsTerritoire, this);
			
			/* Stats pour une compagnie: clic sur le site web, sur le courriel, etc */
			var linkStats = Ext.select('.stats');
			linkStats.on('click', this.setStats, this);
			
			/* Stats pour l'accordeon panel des compagnie */
			var accordeonStats = Ext.select('.AccordionPanelTab');
			accordeonStats.on('click', this.setStats);
			
			/* Stats pour une compagnie: nombre de chargement de la page */
			/*if(Ext.getBody().dom.className.search("stats-page") > -1)
			{
				this.setStats(Ext.getBody().id);
			}*/
		},
		
		
		setStatsRegion : function(idRegion){
			Ext.Ajax.request({
				url : 'stats/task.php',
				method : 'POST',
				params : {
					task : 'statsRegion',
					id   : idRegion
				}
			});
		},
		
		setStatsTerritoire : function(e){
			
			idTerritoire = e.target.id.split("_");
			Ext.Ajax.request({
				url : 'stats/task.php',
				method : 'POST',
				params : {
					task : 'statsTerritoire',
					id   : idTerritoire[1]
				},
				success : function(){
					location.replace(document.getElementById(e.target.id).href);
				}
			});
			
		},
		
		setStats : function(e, el, o){
			
			//console.log(e.getTarget().parentNode.id);
			//console.log(e.getTarget().parentNode.classList[0]);
			
			var target;
			var wholetarget;
			if(Ext.isPrimitive(e))
			{
				target 		= e.split('-');
			}
			else if(e.getTarget().parentNode.id.substr(0,13) == 'click_general'){
				target = e.getTarget().parentNode.id.split('-');
			}
			else if(e.getTarget().parentNode.parentNode.id.substr(0,13) == 'click_general'){
				target = e.getTarget().parentNode.parentNode.id.split('-');
			}
			else
			{
				target		= e.target.id.split('-');
			}	

			var targetZone	= target[0];
			var targetCompId= target[1];

			Ext.Ajax.request({
			   url: 'stats/task.php',
			   method: 'POST',
			   params: {
				    task: 'stats',
					zone: targetZone,
					id	: targetCompId
			   },
			   success: function(){
				   	if(document.getElementById(targetZone+'-'+targetCompId).href)
					{
				  		//location.replace(document.getElementById(targetZone+'-'+targetCompId).href);
					}
				},
			   failure: function(){}
			});

		}
	}
	
})();

Ext.onReady(Ext.ux.Stats.init, Ext.ux.Stats);
