//cédric
var checkmail=function(email){
	var reg = new RegExp('^[a-z0-9]+([_|\.|-]{1}[a-z0-9]+)*@[a-z0-9]+([_|\.|-]{1}[a-z0-9]+)*[\.]{1}[a-z]{2,6}$', 'i');

	if(reg.test(email))
		return true;
	else
		return false;
}


function setCookie( name, value, expires, path, domain, secure )
{
// set time, it's in milliseconds
var today = new Date();
today.setTime( today.getTime() );

/*
if the expires variable is set, make the correct
expires time, the current script below will set
it for x number of days, to make it for hours,
delete * 24, for minutes, delete * 60 * 24
*/
if ( expires )
{
expires = expires * 1000 * 60 * 60 * 24;
}
var expires_date = new Date( today.getTime() + (expires) );

document.cookie = name + "=" +encodeURIComponent( value ) +
( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) +
( ( path ) ? ";path=" + path : "" ) +
( ( domain ) ? ";domain=" + domain : "" ) +
( ( secure ) ? ";secure" : "" );
}


// this fixes an issue with the old method, ambiguous values
// with this test document.cookie.indexOf( name + "=" );
function getCookie( check_name ) {
	// first we'll split this cookie up into name/value pairs
	// note: document.cookie only returns name=value, not the other components
	var a_all_cookies = document.cookie.split( ';' );
	var a_temp_cookie = '';
	var cookie_name = '';
	var cookie_value = '';
	var b_cookie_found = false; // set boolean t/f default f

	for ( i = 0; i < a_all_cookies.length; i++ )
	{
		// now we'll split apart each name=value pair
		a_temp_cookie = a_all_cookies[i].split( '=' );


		// and trim left/right whitespace while we're at it
		cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');

		// if the extracted name matches passed check_name
		if ( cookie_name == check_name )
		{
			b_cookie_found = true;
			// we need to handle case where cookie has no value but exists (no = sign, that is):
			if ( a_temp_cookie.length > 1 )
			{
				cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
			}
			// note that in cases where cookie is initialized but no value, null is returned
			return cookie_value;
			break;
		}
		a_temp_cookie = null;
		cookie_name = '';
	}
	if ( !b_cookie_found )
	{
		return null;
	}
}


var displayTutorial=function(text1, text2) {
var image = document.getElementById('advertisers_image');
 var tutorial = document.getElementById('advertisers_tutorial');
 var tutorial_button = document.getElementById('advertisers_tutorial_button');
 if (image.style.display != "none") {
 image.style.display = "none";
 tutorial.style.display = "block";
 tutorial_button.innerHTML = text2;
 } else {
 image.style.display = "block";
 tutorial.style.display = "none";
 tutorial_button.innerHTML = text1;
 }
} 


var initjc1 = function(auto){

if (typeof forcemobile != 'undefined') return;

if ($jQ("#slider1").css('display')!='none') {

$jQ("#slider1").html('');

var html ='<ul>';
for (var i=0 ; i<jc1content.length ; i++){
html += '<li><img src="'+jc1content[i].img+'" /></li>';
}
html+='</ul>';

$jQ("#slider1").html(html);

	$jQ("#slider1").easySlider({
		prevId :'prevBtn1',
		nextId : 'nextBtn1',
		prevText: '',
		nextText: '',
		auto:auto});

} else return;
		
};

function getItemHTML(item)
{
return '<a href="http://www.blimpme.com/mobile/index.php?gadget='+item.id+'" target="_blank" style="text-decoration:none"><img src="' +item.img+ '" width="310" height="180" alt="' +item.title+ '" style="border:0" /><span>' +item.title+'</span></a>';
};


var initjc2 = function(auto){

if (typeof forcemobile != 'undefined') return;

if ($jQ("#gadgets").css('display')!='none'){

$jQ("#gadgets").html('<div id="slides2"></div>');


$jQ("#slides2").html(jc2html);

	$jQ("#slides2").easySlider({
		prevId :'prevBtn2',
		nextId : 'nextBtn2',
		prevText: '',
		nextText: '',
		auto:auto,
		extCtrl:true,
		speed:400});

		} else return;

};

var showhiderules = function(obj){

	if (jQuery("#divrules").css('display')=='none'){
	jQuery("#hackbr").hide();
	jQuery("#divrules").show();
	jQuery(obj).html(txtrulehide);
	} else {
	jQuery("#hackbr").show();
	jQuery("#divrules").hide();
	
	jQuery(obj).html(txtruleshow);
	}
}

var sec2hms =function(sec){
      hours=pad(Math.floor(sec/3600));
      minutes=pad(Math.floor((sec%3600)/60));
      seconds=pad((sec%3600)%60);
      return {"h":hours,"m":minutes,"s":seconds};
   }
   
var pad=function(num){
       num=num+"";
       if(num.length==1){
           num="0" + num;
       }
       return num;   
   }

   var lptitle = function(o){
   return scorage_lp1+o.h+scorage_lp2+' '+o.m+scorage_lp3+' '+o.s+scorage_lp4;
   }


   var refresh_score = function(){
if(window.XMLHttpRequest)
xhr_object = new XMLHttpRequest(); 
else if(window.ActiveXObject)
xhr_object = new ActiveXObject("Microsoft.XMLHTTP");

var yurl='./mobile/php/scoragen.php';

if (xhr_object)
{
xhr_object.open("POST", yurl, false);

xhr_object.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); 
xhr_object.send(null);

var scores = JSON.parse(xhr_object.responseText);


	try {var h1 = sec2hms(parseInt(scores.lg[0].score));
	//jQuery("#l1st").html('<a href="'+scores.lg[0].url+'" target="_blank"><img class="score_avatar" src="'+scores.lg[0].avatar+'" title="'+lptitle(h1)+'" /></a>');	jQuery("#l1st").html('<img class="score_avatar" src="'+scores.lg[0].avatar+'" title="'+lptitle(h1)+'" />');
	} catch(ee){jQuery("#l1st").html('');};

	try{var h2 = sec2hms(parseInt(scores.lg[1].score));
	jQuery("#l2nd").html('<img class="score_avatar" src="'+scores.lg[1].avatar+'" title="'+lptitle(h2)+'" />');
	}catch(ee){jQuery("#l2nd").html('');}
	
	try{var h3 = sec2hms(parseInt(scores.lg[2].score));
	jQuery("#l3rd").html('<img class="score_avatar" src="'+scores.lg[2].avatar+'" title="'+lptitle(h3)+'" />');
	}catch(ee){jQuery("#l3rd").html('');}
	
	var html='<table class="challengers" cellpadding="0" cellspacing="0"><tr><td>4</td><td>5</td><td>6</td><td>7</td><td>8</td><td>9</td><td>10</td></tr><tr>';
	for (var i=3;i<10;i++){
		try{
		var h7 = sec2hms(parseInt(scores.lg[i].score));
		html+= '<td><img class="score_avatar_mini" src="'+scores.lg[i].avatar+'" title="'+lptitle(h7)+'" /></td>';
		}catch(ee){html+='<td><img class="score_avatar_mini" src="img/empty.jpg"  /></td>'};
		
	}
	html +='</tr></table>';
	
	jQuery("#lothers").html(html);

	
	try{var n1 = parseInt(scores.mo[0].score);
	//jQuery("#m1st").html('<a href="'+scores.mo[0].url+'" target="_blank"><img class="score_avatar" src="'+scores.mo[0].avatar+'" title="'+scorage_mp1+n1+scorage_mp2+'" /></a>');	jQuery("#m1st").html('<img class="score_avatar" src="'+scores.mo[0].avatar+'" title="'+scorage_mp1+n1+scorage_mp2+'" />');
	}catch(ee){jQuery("#m1st").html('');}

	try{var n2 = parseInt(scores.mo[1].score);
	jQuery("#m2nd").html('<img class="score_avatar" src="'+scores.mo[1].avatar+'" title="'+scorage_mp1+n2+scorage_mp2+'" />');
	}catch(ee){jQuery("#m2nd").html('');}

	try{var n3 = parseInt(scores.mo[2].score);
	jQuery("#m3rd").html('<img class="score_avatar" src="'+scores.mo[2].avatar+'" title="'+scorage_mp1+n3+scorage_mp2+'" />');
	}catch(ee){jQuery("#m3rd").html('');}

	
	var html='<table class="challengers" cellpadding="0" cellspacing="0"><tr><td>4</td><td>5</td><td>6</td><td>7</td><td>8</td><td>9</td><td>10</td></tr><tr>';
	for (var i=3;i<10;i++){
		try{
		var n7 = parseInt(scores.mo[i].score);
		html+= '<td><img class="score_avatar_mini" src="'+scores.mo[i].avatar+'" title="'+scorage_mp1+n7+scorage_mp2+'" /></td>';
		}catch(ee){html+='<td><img class="score_avatar_mini" src="img/empty.jpg"  /></td>'};
		
	}
	html +='</tr></table>';
	jQuery("#mothers").html(html);
	
	
}
};
   
var refresh_score_old = function(){
if(window.XMLHttpRequest)
xhr_object = new XMLHttpRequest(); 
else if(window.ActiveXObject)
xhr_object = new ActiveXObject("Microsoft.XMLHTTP");

var yurl='./mobile/php/scorage.php';

if (xhr_object)
{
xhr_object.open("POST", yurl, false);

xhr_object.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); 
xhr_object.send(null);

var scores = JSON.parse(xhr_object.responseText);


	try {var h1 = sec2hms(parseInt(scores.lg[0][1]));
	jQuery("#l1st").html('<img class="score_avatar" src="'+scores.lg[0][2]+'" title="'+lptitle(h1)+'" />');
	} catch(ee){jQuery("#l1st").html('');};

	try{var h2 = sec2hms(parseInt(scores.lg[1][1]));
	jQuery("#l2nd").html('<img class="score_avatar" src="'+scores.lg[1][2]+'" title="'+lptitle(h2)+'" />');
	}catch(ee){jQuery("#l2nd").html('');}
	
	try{var h3 = sec2hms(parseInt(scores.lg[2][1]));
	jQuery("#l3rd").html('<img class="score_avatar" src="'+scores.lg[2][2]+'" title="'+lptitle(h3)+'" />');
	}catch(ee){jQuery("#l3rd").html('');}
	
	var html='<table class="challengers" cellpadding="0" cellspacing="0"><tr><td>4</td><td>5</td><td>6</td><td>7</td><td>8</td><td>9</td><td>10</td></tr><tr>';
	for (var i=3;i<10;i++){
		try{
		var h7 = sec2hms(parseInt(scores.lg[i][1]));
		html+= '<td><img class="score_avatar_mini" src="'+scores.lg[i][2]+'" title="'+lptitle(h7)+'" /></td>';
		}catch(ee){html+='<td><img class="score_avatar_mini" src="img/empty.jpg"  /></td>'};
		
	}
	html +='</tr></table>';
	
	jQuery("#lothers").html(html);
	
	try{var n1 = parseInt(scores.mo[0][1]);
	jQuery("#m1st").html('<img class="score_avatar" src="'+scores.mo[0][2]+'" title="'+scorage_mp1+n1+scorage_mp2+'" />');
	}catch(ee){jQuery("#m1st").html('');}

	try{var n2 = parseInt(scores.mo[1][1]);
	jQuery("#m2nd").html('<img class="score_avatar" src="'+scores.mo[1][2]+'" title="'+scorage_mp1+n2+scorage_mp2+'" />');
	}catch(ee){jQuery("#m2nd").html('');}

	try{var n3 = parseInt(scores.mo[2][1]);
	jQuery("#m3rd").html('<img class="score_avatar" src="'+scores.mo[2][2]+'" title="'+scorage_mp1+n3+scorage_mp2+'" />');
	}catch(ee){jQuery("#m3rd").html('');}

	var html='<table class="challengers" cellpadding="0" cellspacing="0"><tr><td>4</td><td>5</td><td>6</td><td>7</td><td>8</td><td>9</td><td>10</td></tr><tr>';
	for (var i=3;i<10;i++){
		try{
		var n7 = parseInt(scores.mo[i][1]);
		html+= '<td><img class="score_avatar_mini" src="'+scores.mo[i][2]+'" title="'+scorage_mp1+n7+scorage_mp2+'" /></td>';
		}catch(ee){html+='<td><img class="score_avatar_mini" src="img/empty.jpg"  /></td>'};
		
	}
	html +='</tr></table>';
	jQuery("#mothers").html(html);

	
}
};

var scorageto = null;
var start_refreshscorage = function(){
scorageto = setInterval("refresh_score()",300000);
};

var stop_refreshscorage = function(){
clearInterval(scorageto);
scorageto = null;
}

function showRecaptcha(element, themeName) {
  Recaptcha.create("6LdGDQoAAAAAAFWeLh8BB45FKtEK70DijdNS-lmb", element, {
        theme: themeName,
        tabindex: 0,
        callback: Recaptcha.focus_response_field
  });

}

var SendPost=function(url,tab)
{
var xhr_object = null; 
var data = '';
if(window.XMLHttpRequest)
xhr_object = new XMLHttpRequest(); 
else if(window.ActiveXObject)
xhr_object = new ActiveXObject("Microsoft.XMLHTTP");
if (xhr_object)
{
xhr_object.open("POST", url, false);

for (var i=0;i<tab.length;i++)
{
data += tab[i][0]+'='+tab[i][1]+'&'; 
}
xhr_object.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); 
xhr_object.send(data);
return xhr_object;
}
}

function enterpressed(event,func){
if(event.keyCode=='13'){
func.call();
}
}


var lostP = function(login_id){

		var mail = $jQ('#inputlostpass_'+login_id).val();
		var xh=SendPost('./php/lostpass.php',[['ref', mail]]);
		var xml=initXML(xh.responseText);
		var xrep=initXMLtoArray(xml);
		if(xrep == ''){myalert(ssumailsent,400,237,100,'');}else{myalert(ssumailnosent,400,237,100,'');}
	
	$jQ('#passlost_'+login_id).css('display','none');	
	$jQ('#divlogin_'+login_id).css('display','block');	
		

return false;
}

var rlogin = function(login_id){
if (token=="") token="TOKENBIDONANTIBOUCLEINFINIE";
$jQ("#token_"+login_id).val(token);
$jQ("#loginbutton_"+login_id).click();
};

var loginF=function(login_id) {

if ($jQ('#login_'+login_id).val()=='') {
myalert(ssulogin,400,237,100,'');
return false;
} else if ( ($jQ('#password_'+login_id).val()=='') &&($jQ("#token_"+login_id).val()=="")) {
myalert(ssupassword,400,237,100,'');
return false;
}

if ($jQ("#token_"+login_id).val()==""){
$jQ("#divlogin_"+login_id).css('display','none');
$jQ("#loginwait_"+login_id).css('display','block');
//$jQ("#token_"+login_id).val('0');
var s = document.createElement('SCRIPT');
s.type="text/javascript";
//s.src = 'https://ssl3.ovh.net/~blimpme/php/tmppwd.php?lid='+login_id+'&pseudo='+encodeURIComponent($jQ("#login_"+login_id).val())+'&pwd='+encodeURIComponent($jQ("#password_"+login_id).val())+'&r='+Math.random();
s.src = 'http://www.blimpme.com/php/tmppwd.php?lid='+login_id+'&pseudo='+encodeURIComponent($jQ("#login_"+login_id).val())+'&pwd='+encodeURIComponent($jQ("#password_"+login_id).val())+'&r='+Math.random();
//s.src = 'http://www.blimpme.com/php/tmppwd.php?lid='+login_id+'&pseudo='+encodeURIComponent($jQ("#login_"+login_id).val())+'&pwd='+encodeURIComponent($jQ("#password_"+login_id).val())+'&r='+Math.random();

if (typeof ie =='undefined'){

s.onload = function(){
this.parentNode.removeChild(this);
rlogin(login_id);
}

} else {
s.onreadystatechange=function(){
	if ((this.readyState=='complete')||((this.readyState=='loaded'))) {
	this.parentNode.removeChild(this);
	rlogin(login_id);
	}
};
};

document.getElementsByTagName('head')[0].appendChild(s);
return false;
} else {
$jQ("#password_"+login_id).val('');
return true;
}

}




var initXML=function initXML(string) //Retourne objet XML de ResponseText
{
//cleanXML(string);
if (window.ActiveXObject) {
var obj = new ActiveXObject("Microsoft.XMLDOM" );
obj.loadXML(string);}
else if (window.XMLSerializer) {
var  obj = (new DOMParser()).parseFromString(string,"text/xml" );
}
return obj;
}

var initXMLtoArray=function initXMLtoArray(myxml)
{
var G=new Array();
var res=[];
res=XMLtoArray(myxml.childNodes[0],G);
return res;
}


var XMLtoArray=function XMLtoArray(child,Myarr)
{
try {
if ((child.nodeType==1))
{
for (var j=0;j<child.childNodes.length;j++)
{
if (((child.childNodes[j].nodeType==3)||(child.childNodes[j].nodeType==4))&&(child.childNodes[j].nodeValue!=null))
{
//try {
//Myarr=decodeURIComponent2(child.childNodes[j].nodeValue);
//} catch(ee) {
Myarr=child.childNodes[j].nodeValue;
//} 
} else {
Myarr.push(XMLtoArray(child.childNodes[j],[]));
}
}
}
return Myarr;
} catch(ee) {
alert('xmltoarray failed '+ee.description);
return [];
}
}

var creatediv=function(xw,xh,ximg) {
var cho=document.createElement('DIV');
cho.className='alert';
cho.style.position='absolute';
cho.style.left='50%';
cho.style.top='50%';
cho.style.width=xw+'px';
cho.style.height=xh+'px';
cho.style.marginLeft=-parseInt(xw/2)+'px';
cho.style.marginTop=-parseInt(xh/2)+'px';
//cho.style.backgroundImage='url('+ximg+')';
cho.style.fontSize='2em';
cho.style.color='black';
cho.style.fontWeight='800';
cho.style.fontWeight='bold';
cho.style.border = '1px solid black';
cho.style.background = 'white';
cho.style.zIndex=10000;
cho.onmousedown=function() {xalert=0;document.body.removeChild(this);clearInterval(this.t0);}

var choimg=document.createElement('IMG');
choimg.style.position='absolute';
choimg.style.left='100%';
choimg.style.marginLeft='-30px';
choimg.style.marginTop='5px';
choimg.style.top='0%';
choimg.src='./images/close.png';
choimg.style.zIndex=2;
choimg.onmouseover=function() {this.src='./images/close_o.png';}
choimg.onmouseout=function() {this.src='./images/close.png';}

cho.appendChild(choimg);

document.body.appendChild(cho);

return cho;
}

var myalert=function(mes,xw,xh,xt,xi) {
if (xalert!=1)
{

//alert(brow);
var sct=parseInt(brow?Math.max(document.body.getAttribute("scrollTop"),document.documentElement.scrollTop):window.pageYOffset);

var adiv=creatediv(xw,xh,xi);
adiv.style.top=parseInt(screen.availHeight/2-xh/2)+sct+'px';
adiv.style.textAlign='center';
adiv.style.padding='15px';
adiv.style.zIndex = 1000;
var myspan=document.createElement('SPAN');
myspan.style.display='block';
myspan.style.marginTop=xt+'px';
myspan.innerHTML=mes;

adiv.style.left=50+'%';
adiv.style.marginLeft=-375+'px';

adiv.appendChild(myspan);
xalert=1;

var checksc=function() {var mysct=parseInt(brow?Math.max(document.body.getAttribute("scrollTop"),document.documentElement.scrollTop):window.pageYOffset);if (mysct!=sct) {document.body.removeChild(adiv);xalert=0;clearInterval(adiv.t0);}}

adiv.t0=setInterval(checksc,250);

var cla=function() {try{document.body.removeChild(adiv);}catch(ee){};xalert=0;try {clearInterval(adiv.t0)} catch(ee) {};}

setTimeout(cla,3000);

}
}


var useraction = function(lat,lon,ip){
	if (currentPage=='userinscription'){
	registeruser(lat,lon,ip);
	} else if (currentPage=='useraccount') {
	updateuser(lat,lon,ip);
	}
}

	$jQ(window).bind('hashchange', function(){
  	var page = location.hash.replace(/#/,'');
		if (page=='') page = 'welcome';
		displayPageA(page);
		
	});



//wait until page load to init nav functions
$jQ(document).ready(function() {
	
	jc2html ='<ul>';
	for (var i=0 ; i<20 ; i++){
	jc2html += '<li>'+getItemHTML(jc2content[i])+'</li>';
	}
	jc2html+='</ul>';

	
	showAside = function(aside){
	$jQ("#"+aside).show();
	}

	hideAside = function(aside){
	$jQ("#"+aside).hide();	
	}

	displayPage = function(page){
	location.hash = page;
	}
	
	displayPageA = function(page){

	//alert(page);
	//get the page main element
	
	if (typeof aliasList[page]!='undefined'){
	var p = aliasList[page];
	}else{
	var p = page;
	}
	
	pgobj = $jQ("#"+p);

	// if requested page doesnot exist then return
	if (pgobj.html()==null) return;

	// if already this page then return
	if (page==currentPage) return;
	
	try{stopanimation1();}catch(ee){};
	
	for(var i=0 ; i<pagesList.length; ++i){
	$jQ("#"+pagesList[i]).hide();	
	}

	if ( (paList[page]==null) || (paList[currentPage]!=paList[page])){
		for(var i=0;i<asidesList.length;i++){
		hideAside(asidesList[i]);	
		}
	}
	
	
	
	try{showAside(paList[page]);}catch(ee){};
	
	$jQ('.navButton').each(function(){
		$jQ(this).removeClass('active');
	});	
	
	if ((page=='thegame') || (page=='challengers') ){
	try{refresh_score();}catch(ee){};
	try{start_refreshscorage();}catch(ee){};
	}
	
	if (page=='userinscription'){
	$jQ("#useraction").html(btnusersubscribe);
	$jQ("#captchacont").css('display','block');
	showRecaptcha('recaptcha2', 'white');
	//$jQ('#recaptcha2').css('display','inline-block');
	}
	
	if (page=='useraccount'){
	$jQ("#captchacont").css('display','none');
	$jQ("#useraction").html(btnuserupdate);
	$jQ('#recaptcha2').html('');
	//$jQ('#recaptcha2').css('display','none');
	getuser();

	}
	
	//if (btn){
	$jQ("#"+btnList[page]).addClass('active');
	//}
	
	pgobj.show();
	
	if (page=="welcome"){
	$jQ("#map").html('');
	loadMap();
	initjc1(2);	
	}

	//if ( (page!="welcome") && (page!='thegame') && ((currentPage=='welcome') || (currentPage=='thegame')) ){
	//if ($jQ("#gadgets").css('display')!='none'){
	initjc2(2);
	//}
	
	
	
	currentPage = page;
	//currentButton = btn;
	setCookie( 'page', page, 30, '', '', '' );
	}//displayPage

	
	//alert(currentPage);

	if (currentPage=="welcome") loadMap();
	
	if (currentPage=='useraccount'){
	getuser();
	}
	
	if (currentPage=='welcome'){
	initjc1(2);	
	}
	
	
	
	if ((currentPage!='welcome')&& (currentPage!='thegame') && (currentPage!='challengers')){
	initjc2(2);
	}
	
	if (currentPage=='userinscription'){
	showRecaptcha('recaptcha2', 'white');
	}
	
	if ( (currentPage=='thegame') || (currentPage=='challengers') ){
	refresh_score();
	start_refreshscorage();
	}
	
	if (loginerr!=''){
	myalert(loginerr,400,237,100,'');
	}
	//alert(getCookie('page'));
	

});
