/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
   JQuery plugins settings
 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */

/* JQuery DatePicker */
if(typeof($.datepicker)!='undefined'){
	$.datepicker.setDefaults({
		'closeText':MU.$lang('datepicker_closeText'),
		'prevText':'&lt;',
		'nextText':'&gt;',
		'currentText':'',
		'monthNames':DATEPICKER_MONTHS,
		'monthNamesShort':DATEPICKER_MONTHS_SHORT,
		'dayNames':DATEPICKER_DAYS,
		'dayNamesShort':DATEPICKER_DAYS_SHORT,
		'dayNamesMin':DATEPICKER_DAYS_MIN,
		'firstDay':DATEPICKER_FIRST_DAY,
		'weekHeader':DATEPICKER_WEEK_HEADER,
		'dateFormat':'yy-mm-dd'
	});
}

/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
   Yacado Object
 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */

var YO={};
YO.regional='fr';
YO.tmp={}; /* Used to store temporary data */
YO.profile={
	'style':{
		'ok':'ok',
		'focus':'focus',
		'error':'error'
	},
	'order':['civilite','prenom','nom','pseudo','naissancePick','email','pays','codepostal','ville','ccWord'],
	'timeoutEmail':null,
	'timeoutNickname':null,
	'timeoutZipCode':null,
	'cellPhone':(typeof(_cellPhoneRegExp)!='undefined')?_cellPhoneRegExp:[],
	'homePhone':(typeof(_homePhoneRegExp)!='undefined')?_homePhoneRegExp:[],
	'zipCodes':(typeof(_zipcodeRegExp)!='undefined')?_zipcodeRegExp:[]
};
YO.attrDefaultValue='dv';
YO.cartVersion=1;

YO.accountInit=function(){
	/*$("#itemAccount").hide();*/
	$('#btnAccount').click(function(){
		$("#itemAccount").slideToggle('fast');
		return false;
	});
	$('#myPerfs').click(function(){
		$(this).next().slideToggle('fast');
		return false;
	});
};

/**
* Called by a game when a play is ended.
*/
YO.afterPlay=function(status,session,gameIdentifier,playId,showAds,score){
	this.debug('YO.afterPlay() called. ====================');
	this.debug('status='+status);
	this.debug('session='+session);
	this.debug('gameIdentifier='+gameIdentifier);
	this.debug('playId='+playId);
	this.debug('showAds='+showAds);
	this.debug('score='+score);
	if(showAds=='1'){
		YO.ajax('showAdsBanners',playId,session,gameIdentifier);
	}
};

/**
* Launch an AjaxEngine request.
*/
YO.ajax=function(){
	AjaxEngine.call('process',arguments);
};

YO.authenticationInit=function(){
	$('#identification ul li a').tipsy({
		'fade':true,
		'gravity':'s',
		'html':true,
		'opacity':1,
		'title':function(){
			return $(this).next('span[class="tooltipContainer"]').html();
		}
	});
	var messages=$('#btnMessagerie').parent().find('q').text();
	if(parseInt(messages)>0){
		$('#btnMessagerie').parent().addClass('waitingMessage');
	}
	$('#buddha img').tipsy({
		'fade':true,
		'gravity':'w',
		'html':true,
		'opacity':1,
		'title':function(){
			return $(this).next('span[class="tooltipContainer"]').html();
		}
	});
	this.accountInit();
};

YO.avatarClose=function(){
	location.href='/';
};

YO.backgroundsMessage=function(message){
	$("#backgroundModifyResult").html(message).show('fast');
	if(YO.tmp.backgroundsMessageTimeout) clearTimeout(YO.tmp.backgroundsMessageTimeout);
	YO.tmp.backgroundsMessageTimeout=setTimeout("$('#backgroundModifyResult').hide('fast');",4000);
};

YO.backgroundsSave=function(){
	var i,v=$('#backgroundForm').serializeArray();
	var list=[];
	for(i in v){
		list[list.length]=v[i].value;
	}
	list=list.join('|');
	this.ajax('memberBackgroundsSave',list);
};

YO.backgroundsSelectInit=function(list){
	this.tmp.backgroundsSelectTimeout=null;
	var bg=list.split('|');
	var i;
	for(i in bg){
		$('#backgroundForm input[value="'+bg[i]+'"]').attr('checked',true);
	}
	$('#backgroundForm :checkbox').click(function(){
		if(YO.tmp.backgroundsSelectTimeout) clearTimeout(YO.tmp.backgroundsSelectTimeout);
		YO.tmp.backgroundsSelectTimeout=setTimeout('YO.backgroundsSave();',2000);
	});
};

YO.cartAddById=function(id){
	var d=this.cartParseId(id);
	var a,i;
	if(typeof(this.games[d.gameId])=='undefined') return;
	var items=this.games[d.gameId].packages[d.packageId].items;
	this.cart.bonusCredits=0;
	for(i in items){
		if(i==d.gameId){
			a=this.cart.tmpDisplayCredits;
			this.cart.credits+=parseInt(items[i]);
		}else{
			a=this.cart.tmpDisplayBonus;
			this.cart.bonusCredits+=parseInt(items[i]);
		}
		if(typeof(a[i])=='undefined'){
			a[i]=0;
		}
		a[i]+=parseInt(items[i]);
	}
	this.cart.tmpField[this.cart.tmpField.length]=d.id;
	this.cart.total+=parseFloat(this.games[d.gameId].packages[d.packageId].price);
};

YO.cartDisplay=function(cartReset){
	var i,t;
	$('#'+this.cart.formId+' .creditsQuantity').text('0');
	eval('var loop={'+this.cart.blockIdCredits+':this.cart.tmpDisplayCredits,'+this.cart.blockIdBonus+':this.cart.tmpDisplayBonus};');
	for(t in loop){
		d=loop[t];
		for(i in d){
			if(typeof(this.games[i])=='undefined') continue;
			if(d[i]>0){
				$('#'+t).append(MU.sprintf(this.cart.itemPattern,d[i],this.games[i].label));
				$('#'+this.cart.creditQuantityTextIdPrefix+i).text(d[i]);
			}
		}
	}
	$('#'+this.cart.textIdEmpty).toggle(this.cart.tmpDisplayCredits.length==0);
	$('#'+this.cart.textIdBonus).toggle(this.cart.tmpDisplayBonus.length!=0);
	$('#'+this.cart.textIdTotal).text(this.moneyFormat(this.cart.total));
	$('.'+this.cart.textIdCreditsCount).text(this.cart.credits);
	$('.'+this.cart.textIdBonusSumup).text(this.cart.bonusCredits);
	if(!cartReset){
		if(this.cart.bonusCredits>0){
			$('.'+this.cart.blockClassBonusSumup).show();
		}else{
			$('.'+this.cart.blockClassBonusSumup).hide();
			$('#'+this.cart.blockIdBonusSumupDetails).hide();
		}
	}
	var d,i,s;
	for(i in this.paymentSolutionsLimits){
		s=this.paymentSolutionsLimits[i];
		d=(this.cart.total==0||(s[0]<=this.cart.total&&s[1]>=this.cart.total));
		$('.pay_'+i).parent().toggle(d);
	}
};

YO.cartInit=function(firstInit){
	this.cart={
		'blockClassBonusSumup':'packageBonus',
		'blockIdCredits':'creditsList',
		'blockIdBonus':'bonusList',
		'blockIdBonusSumupDetails':'packageBonusSumupDetails',
		'linkIdBonusSumupShowDetails':'packageBonusSumupShowDetails',
		'credits':0,
		'bonusCredits':0,
		'formId':'creditsPaymentForm',
		'fieldIdOrder':'cartField',
		'textIdTotal':'cartTotal',
		'creditQuantityTextIdPrefix':'creditsQuantity',
		'itemPattern':'<li><strong>%1$s</strong> x <strong>%2$s</strong></li>',
		'prefix':'pack_',
		'textIdCreditsCount':'creditsCount',
		'textIdEmpty':'cartEmpty',
		'textIdBonus':'creditsBonusTitle',
		'textIdBonusSumup':'creditsBonusCount',
		'tmpDisplayCredits':[],
		'tmpDisplayBonus':[],
		'tmpField':[],
		'total':0
	};
	if(firstInit){
		$('.'+this.cart.blockClassBonusSumup).hide();
		$('#'+this.cart.blockIdBonusSumupDetails).hide();
	}
	$('#'+this.cart.blockIdCredits).html('');
	$('#'+this.cart.blockIdBonus).html('');
	this.cartDisplay(true);
};

YO.cartPageInit=function(jsonGames,jsonLimits,happyHourRemainingTime,legalNoticeDisplay){
	YO.cartInit(true);
	YO.games=$.parseJSON(jsonGames);
	YO.paymentSolutionsLimits=$.parseJSON(jsonLimits);
	$('#'+this.cart.formId).find('input:checkbox,input:radio').click(function(){
		YO.cartUpdate();
	});
	if(!legalNoticeDisplay){
		$('#paymentLegalNotice').hide();
	}
	/* v2 */
	$('#'+this.cart.linkIdBonusSumupShowDetails).hover(function(){
		$('#'+YO.cart.blockIdBonusSumupDetails).slideToggle();
		return false;
	}).click(function(){
		return false;
	});
	$('#happyHourAllPackages').hide();
	if(typeof(happyHourRemainingTime)!='undefined'){
		time=parseInt(happyHourRemainingTime);
		if((!isNaN(time))&&time>0){
			this.tmp.happyHourRemainingTime=time;
			this.tmp.happyHourRemainingTimeInterval=setInterval('YO.happyHourCountDownUpdate()',1000);
			setTimeout('$("#happyHourAllPackages").slideDown();',1100);
		}
	}
};

YO.cartParseId=function(id){
	var id=id.replace(this.cart.prefix,'');
	tmp=id.split('_');
	var data={
		'id':id,
		'gameId':tmp[0],
		'packageId':tmp[1]
	};
	return data;
};

YO.cartUpdate=function(){
	this.cartInit(false);
	$('input[rel^="'+this.cart.prefix+'"]').each(function(){
		if(!$(this).attr('checked')) return;
		YO.cartAddById($(this).attr('rel'));
	});
	this.cartDisplay(false);
	$('#'+this.cart.fieldIdOrder).val(this.cart.tmpField.join('|'));
};

/**
* Display city proposal. Called by ajax.
*/
YO.cityProposals=function(json,fieldId){
	var obj=$.parseJSON(json);
	fieldId='#'+fieldId;
	if(obj.length==1){
		$(fieldId).val(obj[0].city);
		$(fieldId).blur();
	}else if(obj.length>1){
		var containerId='cityProposals';
		/* Build tooltip content */
		var i;
		var html='<ul id="'+containerId+'">';
		var pattern='<li><a href="#" title="%1$s">%1$s</a></li>';
		for(i in obj){
			html+=MU.sprintf(pattern,obj[i].city);
		}
		html+='</ul>';
		YO.tmp.cityProposals=html;
		/* Tooltip */
		$('#ville').tipsy({
			'trigger':'manual',
			'gravity':'n',
			'fade':true,
			'html':true,
			'title':function(){
				return YO.tmp.cityProposals;
			}
		});
		$('#ville').tipsy('show');
		/* Add listerners on proposals */
		$('#'+containerId+' a').click(function(){
			$('#ville').val($(this).attr('title'));
			$('#ville').blur();
			$('#ville').tipsy('hide');
			return false;
		});
	}
};

YO.createCombo=function(idSelect,optionValue,selectedOption,attribute){
	var idAppend='container_'+idSelect;
	document.write('<span id="'+idAppend+'"></span>&nbsp;');
	idAppend=MU.$(idAppend);
	st=document.createElement('select');
	st.setAttribute('name',idSelect);
	st.setAttribute('id',idSelect);
	if(typeof(attribute)!='undefined'){
		var i;
		for(i in attribute){
			st.setAttribute(i,attribute[i]);
		}
	}
	if(typeof(optionValue)!='undefined'){
		var i;
		for(i in optionValue){
			var j=i;
			if(j.indexOf('_')==0) j=j.substring(1);
			var slted=(j==selectedOption);
			st.options[st.options.length]=new Option(optionValue[i],j,slted,slted);
		}
	}
	st=idAppend.appendChild(st);
	return(st);
};

YO.debug=function(text){
	$('body').append('<!-- '+text+' -->');
};

/**
* Init FB session
*/
YO.facebookInit=function(){
	if(typeof(FB)=='undefined') return;

	if(typeof(FB.getAuthResponse())!='undefined'){
		if ($('#identFalse').length!=0){
		  FB.api({method: 'fql.query',
		      query: 'SELECT email FROM user WHERE uid=' + FB.getAuthResponse().uid
		    },
		    function(response) {
		      var user = response[0];
		      YO.ajax('facebookCheckLogin',FB.getAuthResponse().uid,user.email);
		    }
		  );

		}else{
			YO.tmp.logoutLink=$('#btnLogout').attr('href');
			$('#btnLogout').attr('href','#');
		}
	}else{
		return;
	}
};

/**
* Called by a game.
* Obsolete.
*/
YO.fbPublishFromGame=function(type,opt){
	this.debug('YO.fbPublishFromGame() called. --------------------------------');
	this.debug('<strong style="color:red">THIS METHOD IS OBSOLETE.</strong>');
};

YO.fieldCivilite=function(selectedOption){
	return YO.createCombo('civilite',CIVILITE_SELECT_OPTIONS,selectedOption,{'class':'mfc-intPosStr','title':lg_gender});
};

YO.flowplayer=function(id,imgServer,suffix){
	flowplayer(id,'http://'+imgServer+'/core/swf/'+suffix+'/flowplayer.commercial-3.2.5.swf',{'key':'#$8ee9427877e5388c55e'});
};

YO.formInit=function(form,data){
	var f=MU.$(form);
	if(f){
		var i;
		for(i in data){
			MU.formTagSetValue(i,data[i]);
		}
	}
};

YO.gameDisable=function(gameId,comingSoon){
	if(!comingSoon){
		$('#visible'+gameId).addClass('opacity');
	}
	var gameBlock=$('#game'+gameId);
	gameBlock.addClass((comingSoon)?'comingSoon':'off');
	gameBlock.click(function(){
		return false;
	});
	var gameLink=$('#gameLink'+gameId);
	gameLink.attr('href','#'+gameBlock.find('strong').text());
	gameLink.find('.blocCredits').hide();
	gameLink.click(function(){
		return false;
	});
	if(comingSoon){
		gameLink.parent().addClass('comingSoon');
	}
};

YO.gamePageInit=function(swf,gameId){
	/* Flash display */
	var flashvars={};
	var params={};
	var attributes={'wmode':'opaque'};
	var expressInstall='/expressInstall.swf?imgBack=http://img.mediastay.com/yacado-v2/img/expresseInstallImg.jpg';
	swfobject.embedSWF(swf,'flash','660','530','10.2',expressInstall,flashvars,params,attributes);
	/* Game rating */
	this.tmp.ratingGameId=gameId;
	$('#ratingButton').click(function(){
		YO.ajax('sendRating',YO.tmp.ratingGameId,$('input:radio[name=star]:checked').val());
		return false;
	});
	/* Preload */
	if($('#preload').length==1){
		PLoad.timeFromPreload = null;
		PLoad.focusOnSite = true;
		PLoad.preloadInit();
	}
	/* Misc initializations */
	YO.rankingPopinInit();
	YO.helpInit();
	$('.questionGame .showQuestion').click(function(){
		$(this).next('ul.listQuest').slideToggle();
		return false;
	}).click();
};

YO.gamesInit=function(games){
	var i,game;
	for(i in games){
		game=games[i];
		if(game.group=='3'){
			$('#gameLink'+i+' .blocCredits').hide();
		}
		if(game.allowedAccess=='0'){
			this.gameDisable(i,false);
		}
		$('#group'+game.group).append($('#game'+i));
	}
	this.gamesOrder();
	this.gamesGroupsOrder();
};

YO.gameTopFive=function(ident){
	$('.desc'+ident).tipsy({
		'trigger':'manual',
		'delayIn':250,
		'html':true,
		'gravity':'w',
		'opacity':0.95,
		'title':function(){
			return $(".ident"+ident).html();
		}
	});
	$('.desc'+ident).tipsy('show');
};

YO.gamesOrder=function(){
	$('div.module').each(function(){
		$(this).find('li.off,li.comingSoon').each(function(){
			$(this).appendTo($(this).parent());
		});
	});
};

YO.gamesGroupsOrder=function(){
	var cols=['homeLeft','homeRight'];
	var i;
	for(i in cols){
		$('#'+cols[i]).find('div.module').each(function(){
			if($(this).find('li').length==$(this).find('li.off').length){
				$(this).appendTo($(this).parent());
			}
		});
	}
};

YO.getUrlParams=function(){
	var vars = [], hash;
	var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
	for(var i = 0; i < hashes.length; i++)
	{
		hash = hashes[i].split('=');
		vars.push(hash[0]);
		vars[hash[0]] = hash[1];
	}
	return vars;
}

YO.happyHourCountDownUpdate=function(){
	var s=this.tmp.happyHourRemainingTime;
	if(s<0){
		clearInterval(this.tmp.happyHourRemainingTimeInterval);
		$('#happyHourAllPackages').slideUp();
		return;
	}
	var d=Math.floor(s/86400);
	s-=d*86400;
	var h=Math.floor(s/3600);
	s-=h*3600;
	var i=Math.floor(s/60);
	s-=i*60;
	if(h<10) h='0'+h;
	if(i<10) i='0'+i;
	if(s<10) s='0'+s;
	$('#happyHourAllPackages #hhd-d').text(d);
	$('#happyHourAllPackages #hhd-h').text(h);
	$('#happyHourAllPackages #hhd-i').text(i);
	$('#happyHourAllPackages #hhd-s').text(s);
	this.tmp.happyHourRemainingTime--;
};

YO.helpInit=function(){
	$('.question').each(function(){
		$(this).next('ul').hide();
	});
	$('.question').click(function(){
		if($(this).hasClass('open')){
			$(this).next('ul').hide('slow');
			$(this).removeClass('open');
		}else{
			$(this).next('ul').show('slow');
			$(this).addClass('open');
		}
		return false;
	});
};

YO.leftBarInit=function(){
	if($('#identFalse').length==1){
		$('#jackpot').hide();
		$('#topGame').hide();
		$('#survey').hide();
	}
	$('#zoneItem h2 a').click(function(){
		var cls='active';
		var content=$(this).parent().next();
		if($(this).hasClass(cls)){
			$(this).removeClass(cls);
			content.slideUp('slow');
		}else{
			$(this).addClass(cls);
			content.slideDown('slow');
		}
		return false;
	});
	$("#cagnotte").tipsy({
		'fade':true,
		'gravity':'w',
		'html':true,
		'opacity':1,
		'title':function(){
			return $('#cagnotte span[class="tooltipContainer"]').html();
		}
	});
};

YO.loginFormInit=function(){
	MFC.formInit('loginForm');
};

YO.mdsmBannerOffersClick=function(){
	// Ouvrir la popup de confirmation
	var url='/tracker.php?g='+$('#gameIdentifier').val();
	var popupName='yoPopup'+((new Date()).getTime());
	window.open(url,popupName,'width=416,height=326,directories=0,location=0,menubar=0,status=0,toolbar=0');
	// Valider le formulaire
	var myFormAction='/url.php?mdsm=1';
	var openInNewWindow=false;
	CDV.validBanner(myFormAction,openInNewWindow);
};

YO.menuTopInit=function(){
	$("#menu ul.sousMenu").hide();
	$("#menu li.deroul").mouseover(function(){
		$(this).children('ul.sousMenu').slideDown('fast');
		return false;
	});
	$("#menu li.deroul").mouseleave(function(){
		$(this).children('ul.sousMenu').slideUp('fast');
		return false;
	});
};

/**
* MESSAGING
*/

YO.messagingInit=function(){
	$('.messaging').each(function(){
		$('.messageContent').hide();
	});
	$('.messaging').each(function(){
		$(this).find('td').each(function(){
			$(this).find('a.open').live('click',function(){
				if($(this).parent().parent().next().hasClass('hidden')){
					if($(this).parent().parent().find('td.img').hasClass('read')){
						var num=$('span.nbMsg').html();
						$('span.nbMsg').empty().append(parseInt(num)-1);
					}
					$(this).parent().parent().find('td.img').removeClass().addClass('unread');
					$(this).parent().parent().find('td input').removeClass().addClass('unread');
					$(this).parent().parent().next().removeClass('hidden');
					var idMessage=$(this).attr('id');
					YO.ajax('getMessageContent',idMessage);
					$(this).parent().parent().next().show();
				}else{
					$(this).parent().parent().next().addClass('hidden');
					$(this).parent().parent().next().hide();
				}
				return false;
			});
		});
	});
	$('.all').click(function(){
		$('input[name=msg[]]').attr('checked',true);
		return false;
	});
	$('.none').click(function(){
		$('input[name=msg[]]').attr('checked',false);
		return false;
	});
	$('.readed').click(function(){
		$('input[name=msg[]]').attr('checked',false);
		$('input[name=msg[]].unread').attr('checked',true);
		return false;
	});
	$('.messLus').click(function(){
		if($(':checked').length > 0) {
		var i=0;
			$(':checked').each(function(){
				if($(this).hasClass('read')){
					YO.ajax('messageRead',$(this).val());
					i++;
				}
			});
			var num=$('span.nbMsg').html();
			$('span.nbMsg').empty().append(parseInt(num)-i);
		}else{
			alert(lg_messaging_checkOne);
		}
		return false;
	});
	$('.suppMess').click(function(){
		var data = new Array;
		if($(':checked').length > 0) {
			var i=0;
			$(':checked').each(function(){
				data[i]=$(this).val();
				i++
			});
			eval('var buttons={"'+MU.$lang('yes')+'":true,"'+MU.$lang('no')+'":false};');
			message=lg_messaging_deleteConfirm;
			$.prompt(message,{
				buttons:buttons,
				callback:function(v,m,f){if(v)YO.ajax('messageDelete',data);}
			});
		}else{
			alert(lg_messaging_checkOne);
		}
		return false;
	});
};

YO.moneyFormat=function(number){
	var t='';
	if(number){
		var m=Math.pow(10,parseInt(MONEY_FORMAT_DECIMALS));
		t=Math.round(number*m);
		t=t.toString();
	}else{
		var i;
		for(i=0;i<MONEY_FORMAT_DECIMALS+1;i++){
			t+='0';
		}
	}
	var n1=t.substr(0,t.length-MONEY_FORMAT_DECIMALS);
	var n2=t.substr(n1.length,MONEY_FORMAT_DECIMALS);
	var f=n1+MONEY_FORMAT_DECIMAL_POINT+n2;
	return f;
};

YO.rankingInit=function(podium,slideShow){
	$('.tableRank img[src=""],.tableRank img[src*="{"]').hide();
	$('#noRanking').hide();
	if($('#noRanking').text()!=''){
		$('#bgPodium,#displayTable').hide();
		$('#noRanking').show();
		setTimeout('$.fancybox.resize();',500);
	}
	if(!podium){
		$('#podium').hide();
	}
	if(slideShow){
		$('#bgPodium').addClass('leftPodium');
		$('#gainContent').sudoSlider({
			'continuous':true,
			'auto':true
		});
	}else{
		$('#bgPodium').addClass('middlePodium');
		$('#gainSlider').hide();
	}
	/* */
	$('#displayTable table').dataTable({
		'bPaginate':true,
		'sPaginationType':'full_numbers',
		'iDisplayLength':15,
		'bSort':false,
		'bLengthChange':false,
		'bInfo':false,
		'bFilter':true,
		'oLanguage':{
			'oPaginate':{
				'sFirst':MU.$lang('paginateFirstPage'),
				'sLast':MU.$lang('paginateLastPage'),
				'sNext':MU.$lang('paginateNextPage'),
				'sPrevious':MU.$lang('paginatePreviousPage')
			},
			'sSearch':MU.$lang('rankingSearchNickname'),
			'sZeroRecords':MU.$lang('rankingSearchNoResult')
		}
	});
	$('#displayTable .dataTables_filter').appendTo($('#displayTable .dataTables_paginate').parent());
};

YO.rankingPopinInit=function(){
	$("a.rankingPopin").fancybox({
		"autoDimensions":false,
		"width":716,
		"height":600,
		"transitionIn":"elastic",
		"transitionOut":"elastic",
		"type":"ajax"
	});
};

YO.myRankingsInit=function(){
	this.rankingPopinInit();
	$('.facebookStreamPublish').click(function(){
		var message=$(this).attr("alt");
		FB.streamPublish(message,fb_publishAttachmentSrc,fb_publishLink,fb_publishAttachmentTitle);
	});
	$('.twitterStreamShare').click(function(){
		YO.twitterShare($(this).attr("alt"),fb_publishLink);
	});
};

YO.offermatchOpen=function(url,gameId){
	var cn='active';
	$('#sponsor a.pay_offermatch').parent().removeClass(cn);
	$('#omGame'+gameId).parent().addClass(cn);
	$('#omFrameContainer').html('<iframe id="omFrame" src="'+url+'"></iframe>');
	$('html,body').animate({
		scrollTop:$('#omFrameContainer').offset().top
	},'slow');
};

YO.paymentForce=function(){
	var cart=$('#cartField').val();
	var url="payment.php?presta=forcePBX&cart="+cart;
	window.open(url,"payment",PBX_PARAMS);
	$.fancybox.close();
	return false;
}

YO.paymentByOffermatchInit=function(gameId){
	if(gameId){
		$('#omGame'+gameId).click();
	}
};

YO.paymentInit=function(JQSelector,cartEnabled,isExpress){
	this.tmp.paymentCartEnabled=cartEnabled;
	$(JQSelector).live('click',function(){
		if(YO.cartVersion==2){
			var jParent=$(this).parent('div[class*="blocPayment"]');
			var jContent=jParent.find('.paymentContent');
			if(jParent.find('.paymentContent:hidden').length>0){
				$('.blocPayment').not(jParent).slideUp();
				jParent.find('.paymentContent').slideDown();
				$('.paymentContent').hide();
				YO.paymentProcess(jParent,YO.tmp.paymentCartEnabled);
			}
		}else{
			YO.paymentProcess($(this),YO.tmp.paymentCartEnabled);
			return false;
		}
	});
	if(isExpress){
		var jSelector;
		if(this.cartVersion==2){
			$('.choicePayment ul:first-child').before($('.choicePayment .pay_pbx').parent());
			jSelector=$('.choicePayment .itemPayment').not('.pay_pbx .itemPayment');
		}else{
			jSelector=$('#offers li[class!="express"] a');
		}
		jSelector.each(function(){
			$(this).css('opacity',0.4);
			$(this).hover(function(){
				$(this).css('opacity',1);
			},function(){
				$(this).css('opacity',0.4);
			});
		});
	}
	/* v2 */
	$('#paiement').hide();
	$('.paymentContent').hide();
	/* Happy hour */
	$('#creditsPaymentForm .choiceCredits').each(function(){
		var jCreditsElm=$(this).find('.blocCredits label span');
		var credits=parseInt(jCreditsElm.text());
		var jCreditsNoHHElm=$(this).find('.moreCredits span');
		var creditsNoHH=parseInt(jCreditsNoHHElm.text());
		if(credits>creditsNoHH){
			jCreditsElm.text(creditsNoHH);
			jCreditsElm.parent().css('text-decoration','line-through');
			jCreditsNoHHElm.text(credits);
		}else{
			jCreditsNoHHElm.parent().text('');
		}
	});
	/* Bouton "Continuer" */
	$('#goToPaymentChoice').click(function(){
		if($('#cartField').val()!=''){
			$('#promo').slideUp('fast',function(){
				$('#paiement').slideDown('fast');
			});
		}else{
			alert(MU.$lang('paymentPickAtLeastAGame'));
		}
		return false;
	});
	/* Bouton "Modifier" */
	$('#backToOfferChoice').click(function(){
		$('#paiement').slideUp('fast',function(){
			$('#promo').slideDown('fast');
		});
		return false;
	});
	/* Changer de moyen de paiement */
	$('#paiement .linkChange').click(function(){
		$('.paymentContent:visible').slideUp(function(){
			$('.blocPayment:hidden').slideDown();
		});
		return false;
	});
};

/**
* Payment methods
*/
YO.paymentProcess=function(JElm,cartEnabled){
	var cart='';
	if(cartEnabled){
		cart=$('#cartField').val();
		if(!cart){
			alert(MU.$lang('paymentPickAtLeastAGame'));
			return false;
		}
	}
	var presta='';
	var cn=JElm.attr('class');
	cn=cn.split(' ');
	var i;
	for(i in cn){
		if(cn[i].match(/^pay_/)){
			presta=cn[i].replace('pay_','');
			break;
		}
	}
	if(presta=="offermatch"){
		var gId=JElm.attr('id').replace('omGame','');
		cart='&gId='+gId;
		var linkJElm=$('#morePackages a');
		var url=linkJElm.attr('href').replace(/\?gId=[0-9]*$/,'');
		url+='?gId='+gId;
		linkJElm.attr('href',url);
	}
	var url="payment.php?presta="+presta+"&cart="+cart;
	if (($('#expressCheckout').val()==1 && presta=="pbx") || presta=="sms" || presta=="telephone" || presta=="ip" || presta=="yc"){
		if(this.cartVersion==2){
			$('.pay_'+presta+' .paymentPopin').load(url);
		}else{
			$.fancybox({
				'href':url
			});
		}
	}else if(presta=="offermatch"){
		this.offermatchOpen(url,gId);
	}else{
		var params='';
		if(presta=="pbx"){
			params=PBX_PARAMS;
		}else if(presta=="mb"){
			params=MB_PARAMS;
		}else if(presta=="pp"){
			params=PP_PARAMS;
		}else if(presta=="ts"){
			params=TS_PARAMS;
		}else{
			params=DEF_PARAMS;
		}
		window.open(url,"payment",params);
	}
};

YO.popinMessageInit=function(){
	$('#popinMessageContainer').hide();
	$('#popinMessage a.close').click(function(){
		$.fancybox.close();
		return false;
	});
	$('#popinMessage').fancybox({
		'padding':0,
		'showCloseButton':false,
		'onComplete':function(){
			$('#fancybox-outer').css('background','none');
			$('.fancy-bg').hide();
		},
		'onCleanup':function(){
			$('#fancybox-outer').css('background-color','#fff');
			$('.fancy-bg').show();
		}
	});
	$(document).ready(function(){
		$('#popinMessage').click();
	});
};

/**
* Ouvre une popup centrÃ©e en hauteur et largeur
*/
YO.popupcenter=function(fichier,largeur,hauteur,param){
	var id=Math.round(Math.random()*100);
	var gauche=(screen.width-largeur)/2;
	var haut=(screen.height-hauteur)/2;
	if(param){
		param='width='+largeur+',height='+hauteur+',top='+haut+',left='+gauche+','+param;
	}else{
		param='width='+largeur+',height='+hauteur+',top='+haut+',left='+gauche;
	}
	window.open(fichier,id,param);
}

//YO.preloadClicked=function(){
//	/* Si le membre clique, on ouvre un popup pour garder le jeu en arriÃ¨re plan */
//	var d=new Date();
//	d.setTime(d.getTime()+10*1000);
//	document.cookie='preload=1; expires='+d.toUTCString()/*+'; path=/'*/;
//	var w=window.open(location.href);
//	if(w){
//		w.blur();
//		window.focus();
//	}
//};
//
//YO.preloadClose=function(){
//	$('#preload,#preloadBackground').fadeOut('fast',function(){
//		$(this).remove();
//	});
//	if($.browser.msie){
//		$('#blocFlash').fadeIn('fast');
//	}
//	$(window).unbind('unload',YO.preloadClicked);
//};
//
//YO.preloadInit=function(){
//	$('#preload,#preloadBackground').appendTo($('body'));
//	$(window).resize(function(){
//		/* Redimensionner le fond et le contenu du preload */
//		$('#preload,#preloadBackground').css({
//			'width':$(window).width()+'px',
//			'height':$(window).height()+'px'
//		});
//	}).unload(YO.preloadClicked);
//	$('#preloadClose').click(function(){
//		YO.preloadClose();
//	});
//	/* Show time ! */
//	if($.browser.msie){
//		$('#blocFlash').fadeOut('fast');
//	}
//	$(window).resize();
//	$('#preload,#preloadBackground').hide();
//	$('#preloadBackground').fadeIn('fast',function(){
//		$('#preload').fadeIn('fast',function(){
//			$('#preloadBarCursor').animate({
//				'width':'100%'
//			},10*1000,'linear',function(){
//				YO.preloadClose();
//			});
//		});
//	});
//};


YO.profileExperienceInit=function(backgrounds,belt,beltStartSlide){
	/* Ycard */
	$('.btnYcard').fancybox({
		'autoDimensions':false,
		'width':640,
		'height':510,
		'onClosed':function(){
			location.href=location.href;
		}
	});
	/* Backgrounds */
	$('#backgroundModifyResult').hide();
	this.backgroundsSelectInit(backgrounds);
	this.tmp.bodyDefaultClass=$('body').attr('class');
	this.tmp.wrapperDefaultClass=$('#wrapper').attr('class');
	$('#backgroundForm li img').hover(function(){
		YO.tmp.newBackgroundId=$(this).prevAll(':checkbox').val();
		$('body').removeClass(YO.tmp.bodyDefaultClass).addClass('degrade'+YO.tmp.newBackgroundId);
		$('#wrapper').removeClass(YO.tmp.wrapperDefaultClass).addClass('wrapperHeader'+YO.tmp.newBackgroundId);
	},function(){
			$('body').removeClass('degrade'+YO.tmp.newBackgroundId).addClass(YO.tmp.bodyDefaultClass);
			$('#wrapper').removeClass('wrapperHeader'+YO.tmp.newBackgroundId).addClass(YO.tmp.wrapperDefaultClass);
	});
	/* Belts */
	$('#ceintureSlider').sudoSlider({
		'startSlide':beltStartSlide
	});
	$('#belt'+belt).addClass('activeBelt');
};

/**
* Profile: Init form.
*/
YO.profileFormInit=function(values){
	var id='profileForm';
	this.formInit(id,values);
	MFC.formInit('profileForm');
	/* Nickname field */
	this.tmp.signupNickname='';
	$('#pseudo').keyup(function(){
		if(YO.tmp.signupNickname!=$(this).val()){
			if(MU.is_(MFC.fieldsTypes.nickname.regExp,$(this).val())){
				YO.tmp.signupNickname=$(this).val();
				YO.signupNicknameStatus('');
				if(YO.profile.timeoutNickname!=null) clearTimeout(YO.profile.timeoutNickname);
				YO.profile.timeoutNickname=setTimeout('YO.ajax("nicknameAvailability",$("#pseudo").val());',750);
			}else{
				YO.signupNicknameStatus('badFormat');
			}
		}
	});
	$('#pseudo').blur(function(){
		if(YO.tmp.signupNickname!=$(this).val()&&MU.is_(MFC.fieldsTypes.nickname.regExp,$(this).val())){
			YO.tmp.signupNickname=$(this).val();
			YO.signupNicknameStatus('');
			if(!YO.profile.timeoutNickname){
			}
			YO.ajax("nicknameAvailability",$("#pseudo").val());
		}
	});
	/* Zipcode field */
	$('#codepostal').keyup(function(){
		if(MFC.fieldsTypes.zipcode.check($(this)[0])){
			if(YO.profile.timeoutZipCode!=null) clearTimeout(YO.profile.timeoutZipCode);
			YO.profile.timeoutZipCode=setTimeout('YO.ajax("cityByZipCode",$("#codepostal").val(),$("#pays").val());',750);
			try{
				$('#ville').tipsy('hide');
			}catch(e){}
		}
	});
	if(typeof(values.newsletterHidden)!='undefined'){
		$('#newsletter').attr('checked',(values.newsletterHidden=='1'));
	}
	if(typeof(values.partenairesHidden)!='undefined'){
		$('#partenaires').attr('checked',(values.partenairesHidden=='1'));
	}
	if(typeof(values.couponingHidden)!='undefined'){
		$('#couponing').attr('checked',(values.couponingHidden=='1'));
	}
};

YO.pseudoEnableChange=function(enabled){
	if(!enabled){
		var pseudo=$('#pseudo').val();
		$('#pseudo').parent().replaceWith('<div class="fakeInput">'+pseudo+'</div>');
	}
};

YO.questInit=function(){
	$('div.quest').each(function(){
		$(this).find('div.explain').hide();
		$(this).parent().removeClass('open').addClass('close');
		$(this).addClass('hidden');
		$(this).find('p').each(function(){
			if($(this).find('img').length==1){
				var attribut;
				var image;
				var attribut = $(this).find('img').attr('alt');
				var image = $(this).find('img').attr('src');
				$(this).parent().parent().prev().find('span.statusClose').append('<img src="'+image+'" alt="'+attribut+'" />');
			}
		});
		$(this).find('font.statusClose').show();
	});

	$('div.quest').each(function(){
		$(this).find('a').click(function(){
			$(this).next().slideToggle(function(){
				if($(this).hasClass('hidden')){
					$(this).removeClass('hidden');
					$(this).prev().find('span.statusClose').show();
					$(this).prev().find('.close').remove();
					$(this).parent().removeClass('close').addClass('open');
				}else{
					$(this).parent().removeClass('open').addClass('close');
					$(this).addClass('hidden');
					$(this).prev().find('span.statusClose').hide();
				}
			});
			return false;
		});
	});
};

YO.signupConfirmInit=function(url){
	if($('#signupConfirmContent').html()==''){
		$('#signupConfirmContent').hide();
		setTimeout('location.href="'+url+'";',1000);
	}
};

YO.signupEmailSelect=function(email){
	$('#email').val(email);
	try{
		$('#email').tipsy('hide');
	}catch(e){}
	$('#email').keyup();
	return false;
};

YO.signupEmailStatus=function(status,text){
	$('#checkWS').val(status);
	this.signupFormFieldCheck($('#email'));
	if(text!=''){
		this.tmp.signupEmailError=text;
		$('#email').tipsy({
			'trigger':'manual',
			'gravity':'e',
			'fade':true,
			'html':true,
			'title':function(){
				return YO.tmp.signupEmailError;
			}
		});
		$('#email').tipsy('show');
		$('.tipsy').addClass('signupTooltip');
	}else{
		try{
			$('#email').tipsy('hide');
		}catch(e){}
	}
};

YO.signupFormCheck=function(/*data*/){
	var check=false;
	this.signupFormCheckBefore();
	MFC.formCheck('signupForm',function(data){
		YO.tmp.signupFormErrors=data.err;
		YO.tmp.signupFormErrorsElm=data.errElm;
	});
	this.signupFormCheckAfter();
	var errors=this.tmp.signupFormErrors;
	check=(errors.length==0);
	if(!check){
		var errorsElm=this.tmp.signupFormErrorsElm;
		var jElm,i;
		for(i in errorsElm){
			jElm=$(errorsElm[i]);
			jElm.addClass(this.profile.style.error).removeClass(this.profile.style.ok);
		}
		MFC.formCheckDisplayResult(errors,errorsElm);
	}
	return check;
};

YO.signupFormCheckAfter=function(data){
	$('#signupForm input[type="text"]').each(function(){
		if($(this).val()==''){
			$(this).val($(this).attr(YO.attrDefaultValue));
		}
	});
};

YO.signupFormCheckBefore=function(data){
	$('#signupForm input[type="text"]').each(function(){
		if($(this).val()==$(this).attr(YO.attrDefaultValue)){
			$(this).val('');
		}
	});
};

YO.signupFormFieldCheck=function(elm,next,css){
	if(typeof(next)=='undefined') next=true;
	if(typeof(css)=='undefined') css=true;
	if($(elm)[0]!=elm){
		elm=elm[0];
	}
	var jElm=$(elm);
	var validated=MFC.formElementCheck(elm,true);
	if(validated){
		if(css){
			jElm.addClass(this.profile.style.ok).removeClass(this.profile.style.error);
		}
		if(next){
			//this.signupFormFocusNext();
		}
	}else{
		if(css){
			jElm.addClass(this.profile.style.error).removeClass(this.profile.style.ok);
		}
	}
	return validated;
};

YO.signupFormFocusNext=function(id){
	if(typeof(id)=='undefined') id='';
	var b,i,o;
	for(i in this.profile.order){
		o='#'+this.profile.order[i];
		if(($(o).val()==$(o).attr(YO.attrDefaultValue))||(!this.signupFormFieldCheck($(o),false,false))){
			if(id!=$(o).attr('id')){
				$(o).focus();
			}
			break;
		}
	}
};

/**
* Signup: Init form
*/
YO.signupFormInit=function(){
	$(document).ready(function(){
		$('#ui-datepicker-div').hide();
	});
	/* Default texts */
	var i,id;
	$('#signupForm input[type="text"]').each(function(){
		if($(this).val()==''){
			$(this).val($(this).attr('title'));
		}
		$(this).attr(YO.attrDefaultValue,$(this).attr('title'));
	});
	/* Email field */
	this.tmp.signupEmail='';
	$('#email').keyup(function(){
		if(YO.tmp.signupEmail!=$(this).val()&&MU.isEmail($(this).val())){
			YO.tmp.signupEmail=$(this).val();
			YO.signupEmailStatus(0,'');
			if(YO.profile.timeoutEmail) clearTimeout(YO.profile.timeoutEmail);
			YO.profile.timeoutEmail=setTimeout('YO.ajax("emailCheck",$("#email").val());clearTimeout(YO.profile.timeoutEmail);',750);
		}
	});
	$('#email').blur(function(){
		if(YO.tmp.signupEmail!=$(this).val()&&MU.isEmail($(this).val())){
			YO.tmp.signupEmail=$(this).val();
			YO.signupEmailStatus(0,'');
			if(!YO.profile.timeoutEmail){
				YO.ajax("emailCheck",$("#email").val());
			}
		}
	});
	/* Nickname field */
	this.tmp.signupNickname='';
	$('#pseudo').keyup(function(){
		if(YO.tmp.signupNickname!=$(this).val()){
			if(MU.is_(MFC.fieldsTypes.nickname.regExp,$(this).val())){
				YO.tmp.signupNickname=$(this).val();
				YO.signupNicknameStatus('');
				if(YO.profile.timeoutNickname!=null) clearTimeout(YO.profile.timeoutNickname);
				YO.profile.timeoutNickname=setTimeout('YO.ajax("nicknameAvailability",$("#pseudo").val());',750);
			}else{
				YO.signupNicknameStatus('badFormat');
			}
		}
	});
	$('#pseudo').blur(function(){
		if(YO.tmp.signupNickname!=$(this).val()&&MU.is_(MFC.fieldsTypes.nickname.regExp,$(this).val())){
			YO.tmp.signupNickname=$(this).val();
			YO.signupNicknameStatus('');
			if(!YO.profile.timeoutNickname){
			}
			YO.ajax("nicknameAvailability",$("#pseudo").val());
		}
	});
	/* Zipcode field */
	$('#codepostal').keyup(function(){
		if(MFC.fieldsTypes.zipcode.check($(this)[0])){
			if(YO.profile.timeoutZipCode!=null) clearTimeout(YO.profile.timeoutZipCode);
			YO.profile.timeoutZipCode=setTimeout('YO.ajax("cityByZipCode",$("#codepostal").val(),$("#pays").val());',750);
			try{
				$('#ville').tipsy('hide');
			}catch(e){}
		}
	});
	$('#codepostal,#ville').focus(function(){
		if(!$('#pays').val()){
			setTimeout('$("#'+$(this).attr('id')+'").blur();',5);
			//$(this).blur();
		}
	});
	/* Birthdate field */
	$('#naissancePick').datepicker({
		'changeMonth':true,
		'changeYear':true,
		'yearRange':'1920:1994',
		'onSelect':function(date,inst){
			var d=date.split('-');
			var nd=DATEPICKER_LOCALE;
			nd=nd.replace('Y',d[0]);
			nd=nd.replace('m',d[1]);
			nd=nd.replace('d',d[2]);
			$(this).val(nd);
			$(this).blur();
			$('#naissance').val(date);
		},
		'defaultDate':-AGE_MIN*365
	});
	/*
	if($('#naissance').attr(YO.attrDefaultValue)==''){
		$('#naissance').attr(YO.attrDefaultValue,'fix-a-bug');
	}
	*/
	/* Cryptocode */
	$('#ccWord').focus(function(){
		$(this).addClass('uppercase');
	});
	$('#ccWord').blur(function(){
		if($(this).val()==''||$(this).val()==$(this).attr(YO.attrDefaultValue)){
			$(this).removeClass('uppercase');
		}
	}).blur();
	/* */
	$('#signupForm :input').each(function(){
		if(MFC.formElementMustBeChecked($(this)[0])){
			$(this).blur(function(){
				YO.signupFormFieldCheck($(this),true,true);
				if($(this).val()==''){
					$(this).val($(this).attr(YO.attrDefaultValue));
					$(this).addClass(YO.profile.style.error);
				}
			});
			if($(this).attr('type')=='text'){
				$(this).focus(function(){
					if($(this).val()==$(this).attr(YO.attrDefaultValue)){
						$(this).val('');
					}
				});
			}
		}
		var fcn=function(){
			YO.signupFormFieldCheck($(this),true,true);
		};
		$(this).change(fcn);
		var fcn=function(){
			YO.signupFormFieldCheck($(this),false,true);
		};
		$(this).keyup(fcn);
		/* Trigger events for pre-filled fields */
		if($(this).val()!=$(this).attr(YO.attrDefaultValue)){
			$(this).keyup();
		}
	});
	/* Form listener */
	$('#signupForm').submit(function(){
		return YO.signupFormCheck();
	});
	/* */
	//this.signupFormFocusNext();
};

/**
* Called by a game.
* Display "social buttons" when needed.
*/
YO.socialPublish=function(type,text,img,link,linkText){
	this.debug('YO.socialPublish() called. ====================');
	this.debug('type='+type);
	this.debug('text='+text);
	this.debug('img='+img);
	this.debug('link='+link);
	this.debug('linkText='+linkText);
	if(typeof(this.tmp.socialPublishInit)=='undefined'){
		this.tmp.socialPublishInit=true;
		$('#socialPublishBox').fancybox({
			'showCloseButton':true,
			'autoDimensions':false,
			'width':350,
			'height':'auto',
			'transitionIn':'none',
			'transitionOut':'none',
			'scrolling':'no',
			'titleShow':false,
			'padding':0,
			'autoScale':false,
			'onClosed':function(){
				$("#socialPublishBox").hide();
			},
			'onComplete':function(){
				$("#socialPublishBox").show();
			}
		});
		$('.facebookStreamPublish').click(function(){
			var message=text;
			FB.streamPublish(text,img,link,linkText);
		});
		$('.twitterStreamShare').click(function(){
		  YO.twitterShare(text,link);
		});
	}
	$('#socialPublishBox').trigger('click');
};

YO.signupNicknameStatus=function(msg){
	$('#checkPseudo').val('0');
	try{
		$('#pseudo').tipsy('hide');
		$('.tipsy-inner').html('');
	}catch(e){}
	if(msg=='alreadyUsed'||msg=='badFormat'){
		if(msg=='alreadyUsed') this.tmp.nicknameStatus='signup_nicknameAlreadyUsed';
		else if(msg=='badFormat') this.tmp.nicknameStatus='signup_nicknameBadFormat';
		$('#pseudo').tipsy({
			'trigger':'manual',
			'gravity':'e',
			'fade':true,
			'html':true,
			'title':YO.signupNicknameStatusGetText
		});
		$('#pseudo').tipsy('show');
		$('.tipsy').addClass('signupTooltip');
	}else if(msg=='OK'){
		$('#checkPseudo').val('1');
		try{
			$('#pseudo').tipsy('hide');
		}catch(e){}
	}
	this.signupFormFieldCheck($('#pseudo'));
};

YO.signupNicknameStatusGetText=function(){
	return MU.$lang(YO.tmp.nicknameStatus);
};

/**
* Store initialization
*/

YO.storeInit=function(){
	this.storeRange=[0,5000,30000,60000,80000,120000,180000,250000,500000,1500000,3000000,6000000];
	this.ajax('getStore',this.storeRange[0],this.storeRange[this.storeRange.length-1]);
	$("#slider-range").slider({
		'range':true,
		'min':0,
		'max':YO.storeRange.length-1,
		'values':[0,YO.storeRange.length-1],
		'change':function(event,ui){
			YO.ajax('getStore',YO.storeRange[ui.values[0]],YO.storeRange[ui.values[1]]);
		}
	});
};

YO.storeInitFromAjax=function(){
	$('#store a.descriptionLink').fancybox({
		'width':660,
		'height':450,
		'titleShow':false,
		'showCloseButton':false
	});
};

/**
* Store : Confirm message (30 parties for 15000 points)
*/

YO.confirmPurchaseMessage=function(confirmMsg){
	$("div#gamesList a").click(function(){
		var gameTitle = $(this).attr("title");
		var gameId = $(this).attr("id");
		var msg = confirmMsg.replace('{gameName}',gameTitle);
		if (confirm(msg)){
			YO.ajax('convertPointsToParties',gameId,gameTitle);
		}
		return false;
	});
};
/**
* Display a confirm message and disapear.
*/
YO.toastOnStore=function(message,milliseconds){
	if(typeof(milliseconds)=='undefined') milliseconds=2000;
	$.fancybox(message,{
		'modal':true,
		'onStart':function(){setTimeout('$.fancybox.close();location.href=\'./store.php\'',milliseconds);}
	});
};


/**
* Store: Launch after confirmation process
* This function is a callback of "jquery.impromptu".
*/
YO.storeIsConfirmed=function(v,m,f){
	if(v){
		$.fancybox({
			'orig':$(this),
			'autoScale':true,
			'hideOnOverlayClick':false,
			'enableEscapeButton':false,
			'href':YO.tmp.storePurchaseLink
		});
	}
	YO.tmp.storePurchaseLink=null;
};

YO.surveyInit=function(){
	MU.eventAddListener('surveyForm','submit',function(evt){
		MU.eventPreventDefault(evt);
		var elm=MU.eventGetTarget(evt);
		var response = MU.formTagGetValue(elm.elements['survey']);
		if(response!=null){
			YO.ajax('surveyAnswer',MU.formTagGetValue(elm.elements['survey']));
		}else{
			$.prompt(MU.$lang('surveyPickAnswer'),{ show:"slideDown" });
		}
	});
};

/**
* Display a message and disapear.
*/
YO.toast=function(message,milliseconds){
	if(typeof(milliseconds)=='undefined') milliseconds=2000;
	$.fancybox(message,{
		'modal':true,
		'onStart':function(){setTimeout('$.fancybox.close();',milliseconds);}
	});
};

YO.trackerInit=function(returnButtonText,returnButtonLink,offerText,offerLink,offerImage){
	$('#valid').hide();
	this.tmp.trackerTimeout=setTimeout('YO.trackerNextStep();',3000);
	/* Return button */
	$('#backBtn').text(returnButtonText).attr('href',returnButtonLink);
	/* Offer */
	if(offerText&&offerLink){
		$('#valid .offer a').attr('href',offerLink);
		$('#valid .offer .text a').text(offerText);
		if(offerImage){
			$('#valid .offer img').attr('src',offerImage).attr('alt',offerText);
		}
	}else{
		$('#valid .offer').hide();
	}
	/* */
	$('#valid a').click(function(){
		var popupName='popup'+((new Date()).getTime());
		window.open($(this).attr('href'),popupName,'toolbar=yes,location=yes,status=yes,menubar=yes,scrollbars=yes,resizable=yes,width=800,height=600,');
		self.close();
		return false;
	});
};

YO.trackerNextStep=function(){
	$('#wait,#valid').toggle();
	clearTimeout(this.tmp.trackerTimeout);
};

/**
* Displays a twitter popup window.
*/
YO.twitterShare=function(text,link){
  window.open( tw_shareLink+"url="+link+"&text="+text, "twitter", "status=1,height=400,width=534,resizable=0" );
}

YO.winningsInit=function(tabId,showMoney){
	$('#myMonney').toggle(showMoney);
	$('#'+tabId).addClass('active');
	$(document).ready(function() {
		$('#withdrawLink').fancybox({
			'width':'auto',
			'autoDimensions':false,
			'scrolling':'no',
			'titleShow':false,
			'overlayOpacity':0.65,
			'overlayColor':'#000',
			'transitionIn':'elastic',
			'transitionOut':'elastic',
			'onClosed':function(){
				location.href=location.href;
			}
		});
	});
	$('#myJack table').dataTable({
		'bPaginate':true,
		'sPaginationType':'full_numbers',
		'iDisplayLength':5,
		'bSort':false,
		'bLengthChange':false,
		'bInfo':false,
		'bFilter':false,
		'oLanguage':{
			'oPaginate':{
				'sFirst':MU.$lang('paginateFirstPage'),
				'sLast':MU.$lang('paginateLastPage'),
				'sNext':MU.$lang('paginateNextPage'),
				'sPrevious':MU.$lang('paginatePreviousPage')
			},
			'sSearch':MU.$lang('rankingSearchNickname'),
			'sZeroRecords':MU.$lang('rankingSearchNoResult')
		}
	});
};

YO.ycardInit=function(ycard,percent){
	if(ycard==0){
		$('#currentYcard,#stepCard').text('');
	}
	if(percent==100){
		$('#nextYcard,#objectif').hide();
	}
	$('#text').html($('#text'+(ycard+1)).html());
	/* Progress bar */
	percent=100-percent;
	var maskMaxWidth=$('#ycardProgressMask').css('max-width').replace('px','');
	var maskMinWidth=$('#ycardProgressMask').css('min-width').replace('px','');
	var maskSpace=maskMaxWidth-maskMinWidth;
	var maskSize=Math.round(percent/100*maskSpace);
	var newWidth=parseInt(maskSize)+parseInt(maskMinWidth);
	$('#ycardProgressMask').css('width',maskMaxWidth+'px');
	$('#ycardProgressMask').animate({
		'width':newWidth
	},2000);
};


YO.tombolaInit=function(){
	$('.btnValid').click(function() {
		var id=$(this).attr('href').replace("#t","");
		var quantity=$('#quantity'+id).val();
		if(!quantity||isNaN(quantity)) quantity=1;
		$('#n'+id).text(quantity);
		$('#p'+id).text($('#p'+id).text()*quantity);

		$('#valid'+id).die('click');
		$('#valid'+id).live('click', function(event) {
			$.post("include/tombolaPurchase.php", { quantity: quantity, tombolaId: id },
				function(data) {
					$('#t'+data.tId).removeClass('achatTombola').addClass('confirmTombola');
					$('#confirm'+id).html(data.message);
				},"json");
			return false;
		});
	});

	$('a.btnValid').fancybox({
		'width':760,
		'height':450,
		'titleShow':false,
		'showCloseButton':false,
		'onClosed':function(){
			window.location.reload();
		}
	});
};

/**
* Cache les éléments contenus dans le tableau
*/
YO.multiHide=function(obj){
	if(obj.length!=0){
		for(i in obj){
			var j=obj[i];
			$('#'+j).hide();
		}
	}
}

/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
   MdsFormCheck types
 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */

if(typeof(MFC)=='undefined'){
	var MFC={};
}
if(typeof(MFC.fieldsTypes)=='undefined'){
	MFC.fieldsTypes={};
}

MFC.fieldsTypes.cryptocode={
	'regExp':new RegExp('^[a-z0-9]{4}$','i'),
	'check':function(elm){
	        	var v=MU.formTagGetValue(elm);
	        	var rv=MU.is_(MFC.fieldsTypes.cryptocode.regExp,v);
	        	return rv;
	        }
};

MFC.fieldsTypes.emailWS={
	'regExp':null,
	'check':function(elm){
	        	var v=MU.formTagGetValue(elm);
	        	var f=elm.form;
	        	var ckd=(MU.formTagGetValue(f.checkWS)=='1');
	        	var rv=ckd&&MU.isEmail(v);
	        	return rv;
	        }
};

MFC.fieldsTypes.nickname={
	'regExp':new RegExp('^[a-z0-9_-]{3,16}$'),
	'check':function(elm){
	        	var v=MU.formTagGetValue(elm);
	        	v=v.toLowerCase();
	        	v=v.replace(/\s/g,'-');
	        	MU.formTagSetValue(elm,v);
	        	var f=elm.form;
	        	var ckd=(MU.formTagGetValue(f.checkPseudo)=='1');
	        	var rv=ckd&&MU.is_(MFC.fieldsTypes.nickname.regExp,v);
	        	return rv;
	        }
};

MFC.fieldsTypes.password={
	'regExp':new RegExp('^[A-Za-z0-9-_$.]{2,25}$','i'),
	'check':function(elm){
	        	var v=MU.formTagGetValue(elm);
	        	var rv=(elm.readOnly||MU.is_(MFC.fieldsTypes.password.regExp,v));
	        	return rv;
	        }
};

MFC.fieldsTypes.passwordConfirm={
	/*
	Class: mfc-passwordConfirm_pass1
	       pass1 is the input name of the field which must be the same as elm in the check function.
	*/
	'check':function(elm){
	        	var v=MU.formTagGetValue(elm);
	        	var p=MFC.formElementCheckGetParams(elm);
	        	var rv=true;
	        	if(p[0]){
	        		var f=elm.form;
	        		if(f.elements[p[0]]){
	        			rv=(f.elements[p[0]].value==v);
	        		}
	        	}
	        	return rv;
	        }
};

MFC.fieldsTypes.passwordLogin=MFC.fieldsTypes.password;

MFC.fieldsTypes.zipcode={
	'regExp':null,
	'check':function(elm){
	        	var rv=false;
	        	var v=MU.formTagGetValue(elm).toUpperCase();
	        	MU.formTagSetValue(elm,v);
	        	var f=elm.form;
	        	var country=MU.formTagGetValue(f.elements['pays']);
	        	var zipcodes=YO.profile.zipCodes;
	        	if(country&&zipcodes[country]){
	        		if(typeof(zipcodes[country])=='function'){
	        			rv=zipcodes[country](v);
	        		}else{
	        			rv=MU.is_(zipcodes[country],v);
	        		}
	        	}
	        	return rv;
	        }
};

MFC.fieldsTypes.cellphone={
	'regExp':null,
	'check':function(elm){
	        	var v=MU.formTagGetValue(elm);
	        	v=v.replace(/[^0-9]/,'');
	        	var rv=(v=='');
	        	var f=elm.form;
	        	if(!rv){
	        		var country=MU.formTagGetValue(f.elements['pays']);
	        		var cellphones=YO.profile.cellPhone;
	        		if(typeof(cellphones[country])=='function'){
	        			rv=cellphones[country](v);
	        		}else if(typeof(cellphones[country])!='undefined'){
	        			rv=MU.is_(cellphones[country],v);
	        		}else{
	        			rv=MU.is_(/^[0-9]{6,}$/,v);
	        		}
	        	}else{
	        		v='';
	        	}
	        	MU.formTagSetValue(elm,v);
	        	rv=(elm.readOnly||rv);
	        	return rv;
	        }
};

MFC.fieldsTypes.homephone={
	'regExp':null,
	'check':function(elm){
	        	var v=MU.formTagGetValue(elm);
	        	v=v.replace(/[^0-9]/,'');
	        	var rv=(v=='');
	        	var f=elm.form;
	        	if(!rv){
	        		var country=MU.formTagGetValue(f.elements['pays']);
	        		var homephones=YO.profile.homePhone;
	        		if(typeof(homephones[country])=='function'){
	        			rv=homephones[country](v);
	        		}else if(typeof(homephones[country])!='undefined'){
	        			rv=MU.is_(homephones[country],v);
	        		}else{
	        			rv=MU.is_(/^[0-9]{6,}$/,v);
	        		}
	        	}else{
	        		v='';
	        	}
	        	MU.formTagSetValue(elm,v);
	        	rv=(elm.readOnly||rv);
	        	return rv;
	        }
};

/*----------------------- pub preload ---------------------------*/

var PLoad = {};
/*Time for progresse barre. (null no timer)*/
PLoad.timeFromPreload = 10*1000;
/*Time that the cookie remains in the browser*/
PLoad.cookieExpires = PLoad.timeFromPreload;
/*on click to ads, reload the site in new popup and focus,
 * else close ads and let the ads popup open normaly
 */
PLoad.focusOnSite = true;
/*coockies prefix*/
PLoad.cookiePrefix = '';

PLoad.preloadClicked=function(){
	/* Si le membre clique, on ouvre un popup pour garder le jeu en arriére plan */
	var d=new Date();
	if(PLoad.cookieExpires != null){
		d.setTime(d.getTime()+PLoad.cookieExpires);
	}else{
		d.setTime(d.getTime()+15*1000);
	}
	document.cookie=PLoad.cookiePrefix+'preload=1; expires='+d.toUTCString();/*+'; path=/';*/
	if(PLoad.focusOnSite){
		var w=window.open(location.href);
		if(w){
			w.blur();
			window.focus();
		}
	}
	PLoad.preloadClose();
};

PLoad.preloadClose=function(){
	$('#preload,#preloadBackground').fadeOut('fast',function(){
		$(this).remove();
	});
	if($.browser.msie){
		$('#blocFlash').fadeIn('fast');
	}
	$(window).unbind('unload',PLoad.preloadClicked);
};

PLoad.preloadInit=function(){

	$("#preload").mouseenter(function(){
		$(window).unload(PLoad.preloadClicked);
	}).mouseleave(function(){
		$(window).unbind('unload',PLoad.preloadClicked);
	});

	$('#preloadClose').click(function(){
		PLoad.preloadClose();
	});
	if($.browser.msie){
		$('#blocFlash').fadeOut('fast');
	}
	$(window).resize();
	$('#preload,#preloadBackground').hide();
	$('#preloadBackground').fadeIn('fast',function(){
		$('#preload, #preload #preloadClose').fadeIn('fast',function(){
			if(PLoad.timeFromPreload != null){
				$('#preloadBarCursor').animate({
					'width':'100%'
				},PLoad.timeFromPreload,'linear',function(){
					PLoad.preloadClose();
				});
			}
		});
	});

};

function gebi(o){
	return(document.getElementById(o));
}

/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
   Code to run onload
 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */

$(document).ready(function(){
	YO.facebookInit();
});

function doClick(campId,bannerId,clicking,smoothing) {
	if (!bannerId||!campId) {
		alert(YOU_MUST_CLICK_ON_A_BANNER);
	} else {
		var gameId=MU.$('gameId');
		if (gameId=='') {
			alert(BANNER_GAMEID_ERROR);
		} else {
			popupName='popup'+((new Date()).getTime());

			window.open('/tracker.php?g='+MU.$('gameIdentifier').value,popupName,'width=416,height=326,directories=0,location=0,menubar=0,status=0,toolbar=0');
			MU.$('bannerID').value=bannerId;
			MU.$('campID').value=campId;
			MU.$('clicking').value=clicking;
			MU.$('smoothing').value=smoothing;
			MU.$('formGrilles').submit();
		}
	}
}

function checkParrainClassic(){
	var f=document.getElementById('tafForm');
	if(f){
		var err='';
		var nl='\n- ';
		document.getElementById('Email1').value=document.getElementById('Email1').value.toLowerCase();
		if(!MU.isEmail(document.getElementById('Email1').value)) err+=nl+lg_godsonEmail;
		if(f.ccWord){
			if(f.ccWord.value.length<4) err+=nl+lg_securityCode;
		}
		if(err!='') alert(lg_formPleaseCheck+err);
		else f.submit();
	}
	return(false);
}

