$.get('/geokey', function(data){
	var v = new Image(); v.src = '/medias/images/loading-black.gif';
	geoloc = data;
	geoloc_page_ready();
});

function geoloc_page_ready(){
	var cookie_exists = (typeof(geoloc_get_cookie('piwik_visitor20')) != 'undefined');
	if (cookie_exists){
		launch_redirect();
	} else {
		setTimeout(geoloc_page_ready, 500);
	}
}

function get_geolocation_key(){
	return geoloc;
}

function launch_redirect(){
	var redirect = -1;
	var key = get_geolocation_key();
	if (key != 'US'){
		redirect = 'ca.';
	}
	if (redirect != -1){
		var current_url = window.location['href'];
		if (current_url.indexOf('preview=true') == -1){
			current_url = current_url.replace('www.', redirect);
			//var geoloc_html = '<meta http-equiv="refresh" content="0;URL='+current_url+'" />'+"\n";
			//$('head').append(geoloc_html);
			//setTimeout(function(){
				var geoloc_html = '<div id="geolocation-choose"><br /><br />'+"\n";
				geoloc_html +='Loading, please wait...<br /><br />'+"\n";
				geoloc_html +='<img src="/medias/images/loading-black.gif" />'+"\n";
				geoloc_html +='</div>'+"\n";
				geoloc_html +='<style type="text/css"><!--'+"\n";
				geoloc_html +='#geolocation-choose{'+"\n";
				geoloc_html +='z-index:100;'+"\n";
				geoloc_html +='position:absolute;'+"\n";
				geoloc_html +='left:20px;'+"\n";
				geoloc_html +='right:22px;'+"\n";
				geoloc_html +='top:0;'+"\n";
				geoloc_html +='height:1000px;'+"\n";
				geoloc_html +='text-align:center;'+"\n";
				geoloc_html +='font-size:20px;'+"\n";
				geoloc_html +='font-weight:bold;'+"\n";
				geoloc_html +='color:#FFF;'+"\n";
				geoloc_html +='background:rgba(0, 0, 0, 0.90);'+"\n";
				geoloc_html +='}'+"\n";
				geoloc_html +='</style>';
				$('#content').append(geoloc_html);
				var h = $('.content-container2').outerHeight();
				$('#geolocation-choose').css('height', h+'px');
				window.location.replace(current_url);
			//}, 500);
		}
	}
}

function geoloc_get_cookie(c_name) {
	var i,x,y,ARRcookies=document.cookie.split(";");
	for (i=0;i<ARRcookies.length;i++){
		x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
		y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
		x=x.replace(/^\s+|\s+$/g,"");
		if (x==c_name) {
			return unescape(y);
		}
	}
}
