var jQueryWysistats = function(params) {

	var $this = this;
	var $j = jQuery;
	this.param = params
	
	this.setAccount = function(account) {
		this.param.account = account;
	}
	
	this.getAccount = function() {
		return this.param.account;		
	}
	
	this.cleanUrl = function(url) {	
		url  = url.replace(new  RegExp('http://([^/]*)/(.*)', "g"),'$2');
		url  = url.replace(new  RegExp('http://', "g"),'');
		return url;
	}
	
	this.init = function(exts) { 
			var ext = '';
			for(var x in exts) {
				ext += ',a[href$=".'+exts[x]+'"]';
			}
		
			ext = ext.substring(1);
			
			this.param.account = (typeof this.param.account == 'undefined') ? "": this.param.account;				
				
			$j(ext).live('click', function(e){			
				l = $(this);
				var base  = l.attr('href');
				base  = $this.cleanUrl(base);
				$this.url  = base.replace(new  RegExp('(.*)/(.*)$', "g"),'$2');
				
				if(typeof $this.postProcess == 'function') {
					$this.postProcess(base);
				}
				
				stat($this.param.client,'','','document;'+$this.url,'','','',$this.param.account);			
			});
		}
		
	if(typeof params.ext == 'object' && params.client!='') {		
		this.init(params.ext);
	}
	
}

function getAccount(account) {

	switch(account) {
		case 'balades-rando':
			account = 'balades';
		break;
		case 'espace-presse':
			account = 'jardins';
		break;
		case 'site-pro':
			account = 'pro';
		break;
		case 'voies-vertes':
			account = 'voiesvertes';
		break;
		case 'week-end-et-sejours':
			account = 'weekends';
		break;
		default:
			account = 'site';
		break;
	}
	
	if(account == 'site') {
		var win = window.location.search;
		
		if(win.match(/site=2/g)) {
			account = 'voiesvertes';
		}
		else if(win.match(/site=3/g)) {
			account = 'weekends';
		}	
		else if(win.match(/site=4/g)) {
			account = 'balades';
		}	
		else if(win.match(/site=5/g)) {
			account = 'pro';
		}		
		else if(win.match(/site=6/g)) {
			account = 'jardins';
		}		
	}
			
	return account;
}

$(document).ready(function(){	
	
		jStat = new jQueryWysistats({
			'ext' : ['pdf', 'doc', 'xls', 'odt', 'ods', 'csv', 'jpg',],
			'client' : 'cdt27'
		});		
		
		var account = window.location.pathname.replace(new  RegExp('/([^/]*)/(.*)', "g"),'$1');	
			
		jStat.setAccount(getAccount(account));	
		
		jStat.postProcess = function(base) {
		
			if(base.match(/download/g)) {
				var account = base.replace(new  RegExp('download/([^/]*)/(.*)', "g"),'$1');	
				account = getAccount(account);
				
				if(jStat.getAccount()!=account) {
					jStat.setAccount(account);
				}				
			}
			else {
				var title = $('.div_product_label span').text();
				
				if(title != '') {
					this.url = title+' : '+this.url;
				}
				
			}
		}

});