
function addlinkUrl(nbTotalResult,nbLignResultByPage,nbLinkByPage,strFctForLink,unArray,page){	
	
	var res ="";
	var ResultLink="";
	
	if( ( nbTotalResult - nbLignResultByPage )>0){
	
			strFctForLink2="javascript:"+strFctForLink+"("; 
			if(unArray.length>0){
				for(var i=0;i<unArray.length;i++){
					strFctForLink2 +="'"+unArray[i]+"'";
					if(i<unArray.length)
						strFctForLink2 +=",";
					
				}
			}
			
		
			var linkDiv="";
			var endNumberLinkInPage = 0;
			var firstNumberLinkInPage = 0;
			if(page==0)
				page=1;
			
			var nbLink = Math.ceil(nbTotalResult/nbLignResultByPage);
			var nbIntervalleLink = ( Math.ceil(nbLink/nbLinkByPage)+1 );
			
			for (var i = 0; i < nbIntervalleLink; i++) {		
				firstNumberLinkInPage = parseInt( (i*nbLinkByPage) + 1 );
				endNumberLinkInPage = parseInt((i*nbLinkByPage)) + parseInt(nbLinkByPage)  ;
				
			if ( ( page>=firstNumberLinkInPage ) && ( page <=endNumberLinkInPage)  ){

					if(firstNumberLinkInPage != 1){
						
						linkDiv = document.getElementById('templateLinkArray').innerHTML;
					
						linkPrecedent = firstNumberLinkInPage-nbLinkByPage;
						if(nbLinkByPage == 1)
							linkDiv = replaceCodeByString(linkDiv,"NumberPage","xxx<<<");				
						else
							linkDiv = replaceCodeByString(linkDiv,"NumberPage",MLJS("txtPrev"));
						linkDiv = replaceCodeByString(linkDiv,"GotoPageUrl",strFctForLink2+linkPrecedent+")");
						res +=linkDiv;
					}
				for(numPage=firstNumberLinkInPage;(numPage<=endNumberLinkInPage)&&(numPage<=nbLink);numPage++){	
					if(numPage==page){							
							linkDiv = document.getElementById('templateLinkInactive').innerHTML;								
							if(nbLinkByPage==1){
								if(numPage != 1 && nbLink != endNumberLinkInPage)
									linkDiv = replaceCodeByString(linkDiv,"NumberPageInactive","|");
								else if(numPage==1 || numPage == endNumberLinkInPage)
									linkDiv = replaceCodeByString(linkDiv,"NumberPageInactive","");
							}
							else
								linkDiv = replaceCodeByString(linkDiv,"NumberPageInactive",numPage);
							res +=linkDiv;
					}		
					else{
						linkDiv = document.getElementById('templateLinkArray').innerHTML;
						linkDiv = replaceCodeByString(linkDiv,"NumberPage",numPage);
						linkDiv = replaceCodeByString(linkDiv,"GotoPageUrl",strFctForLink2+numPage+")");				
						res +=linkDiv;
					}		
				}				
				if(i!=(nbIntervalleLink-1) ){
					
					pageSuivanteNum=endNumberLinkInPage+1;
		
					if(pageSuivanteNum<=nbLink){
						
						linkDiv = document.getElementById('templateLinkArray').innerHTML;	
						if(nbLinkByPage == 1)		
							linkDiv = replaceCodeByString(linkDiv,"NumberPage","xxx>>>");
						else
							linkDiv = replaceCodeByString(linkDiv,"NumberPage",MLJS("txtNex"));
						linkDiv = replaceCodeByString(linkDiv,"GotoPageUrl",strFctForLink2+pageSuivanteNum+")");				
						res +=linkDiv;	
					}	
				}
			}					
		}	
	}	
	if(nbLinkByPage == 1){
		res = replaceCodeByString(res,"<<<",MLJS("txtPrev"));
		res = replaceCodeByString(res,">>>",MLJS("txtNex"));		
	}
	if(res!="")
		ResultLink=CreateLinkPage(res,nbTotalResult,nbLignResultByPage,strFctForLink,unArray);
	
	
	return ResultLink;
}
// pour les templates utilisant les pages
function CreateLinkPage(Links,nbTotalResult,nbLignResultByPage,strFctForLink,unArray){

	var nbLink = Math.ceil(nbTotalResult/nbLignResultByPage);
	
	strFctForLink2="javascript:"+strFctForLink+"("; 
			if(unArray.length>0){
				for(var i=0;i<unArray.length;i++){
					strFctForLink2 +=unArray[i];
					if(i<unArray.length)
						strFctForLink2 +=",";
					
				}
			}
	
	strFctForLinkNewer=strFctForLink2+"1)";
	strFctForLinkOlder=strFctForLink2+nbLink+")";
	
	if(nbLink>1){
		var templateLinkDiv = document.getElementById('templateBlocLink').innerHTML;
		templateLinkDiv=repS(templateLinkDiv,"Links",Links);
		
		if(nbLink>=3){
			templateLinkDiv=repS(templateLinkDiv,"Newer","<li class='page-number'><a href='"+strFctForLinkNewer+"'>"+MLJS("txtNewer")+"</a></li>");
			templateLinkDiv=repS(templateLinkDiv,"Older","<li class='page-number'><a href='"+strFctForLinkOlder+"'>"+MLJS("txtOlder")+"</a></li>");
			
		}else{
			templateLinkDiv=repS(templateLinkDiv,"Newer","");
			templateLinkDiv=repS(templateLinkDiv,"Older","");
		}
	}
	
	return templateLinkDiv;
}
function checkHourlyRate(divhourlyrate){

    valuehorlyrate = divhourlyrate.value;
    valuehorlyrate = treatComma(valuehorlyrate);
    var checkOK = true;
    var message = "";
    if (valuehorlyrate.length == 0) {
        checkOK = false;
        divhourlyrate.style.backgroundColor = "yellow";
    }
    else {
        if (Num(valuehorlyrate) == false) {
        
            divhourlyrate.style.backgroundColor = "red";
            valuehorlyrate = '';
            checkOK = false;
			
        }
    
  }
    if (checkOK == false) {
    

		showalertpanel(MLJS("txtAttention"),message,'',3,1,'');
    }
    divhourlyrate.value = valuehorlyrate;
	

    return checkOK;
}


function Num(strString){

    var strValidChars = "0123456789.";
    var strChar;
    var nombredepoint = 0;
    var blnResult = true;
    for (i = 0; i < strString.length && blnResult == true; i++) {
        strChar = strString.charAt(i);
        if (strChar == '.') 
            nombredepoint += 1;
        if ((strValidChars.indexOf(strChar) == -1) || (nombredepoint > 1)) 
            blnResult = false;
    }
    return blnResult;
}



function treatComma(strString){

    var s2 = "";
    var strChar = "";
    
    for (i = 0; i < strString.length; i++) {
    
        strChar = strString.charAt(i);
        
        if (strChar == ',') {
            s2 += '.';
        }
        else 
            s2 += strChar;
    }
    
    return s2;
}


function onKeyBoardActivity(){

    // récuppérer le tps de la 1ère saisie
    lastActivityTime = new Date();
    isRequestOn = false;
    
    
}
function onKeyBoardActivity2(){

    // récuppérer le tps de la 1ère saisie de l'enfant dans le cas où
	// inscription enfant+parent
    lastActivityTime2 = new Date();
    isRequestOn2 = false;
    
    
}

function replaceCodeByString(strIn,code,str){
	var s = "xxx"+code;
	
	return strIn.replace(new RegExp(s, "g"),str);
}

function repS(strIn,code,str){
	return replaceCodeByString(strIn,code,str);
}

function replaceCodeByString2(strIn,code,str){
	var s = code;
	
	return strIn.replace(new RegExp(s, "g"),str);
}

function repS2(strIn,code,str){
	return replaceCodeByString2(strIn,code,str);
}

function isTheSame(string1, string2) {
	
	return new RegExp(string1).test(string2) && new RegExp(string2).test(string1)
	
}


function MLJS(){
	
	var txt=document.getElementById("MLJS_"+arguments[0]).innerHTML;
	if(txt!=""){
		for(var i = 1; i <arguments.length; i++) {
			var reg=new RegExp("[[](arg"+i+"])", "gi");
			txt=txt.replace(reg,arguments[i]);
		}
	}
return txt;
}

// returns true if email is valid
function isValidEmail(str){
	var maReg = new RegExp ("^([a-zA-Z0-9]+(([\.\\-]?[a-zA-Z0-9\_]+)+)?)\@(([a-zA-Z0-9]+[\.\\-\_])+[a-zA-Z]{2,4})$");
	if ( (str).search( maReg ) == -1 )
		return false;
	else 
		return true;    // return (str.lastIndexOf(".") > 2) &&
						// (str.indexOf("@") > 0) && (str.lastIndexOf(".") >
						// (str.indexOf("@") + 1)) && (str.indexOf("@") ==
						// str.lastIndexOf("@"));
}

// to be moved to general
function new_createPopupYui(mode,strHeader,strBody,handleCancel,handleAction,panelName){

	// Instantiate the Dialog
	var popupPanel = "";
	if(mode == 1){
		
		popupPanel = new YAHOO.widget.Dialog(
		panelName, 
		 {  
		 effect:{effect:YAHOO.widget.ContainerEffect.FADE, 
		         duration:0.1},  
		   fixedcenter: true,
		  modal:true,		   
		   visible: true,
		   draggable: false,
		   close: false,
		   constraintoviewport: true

		  
		 } 
		 
		 );	
		 

	}


	popupPanel.setHeader(strHeader);		 	

	popupPanel.setBody(strBody);

	popupPanel.render(document.body);	
	
	return popupPanel;
	
}
// this function is called in all page when document ready
function new_setHearBeat(){
	// this DOM is in left.php
	var isVisitor = $("#isVisitor")[0].value;
	if(isVisitor == 0){
		new_getSessionsOpen();
		new_setTimeOutSessionOpen();
		new_setTimeOutMsg();		
	}
	else if(isVisitor == 2)
		new_getSessionsOpen();	
	ElementCommun();
	// 4 menu header
	new_setheaderMenu();

}
function new_setHearBeatFicheUser(){
	ElementCommun();
	new_setheaderMenu(); 
}
function notifVisitorQuit(){
	try{
		if(typeof($("#isVisitor")) !== "undefined"){
			// this DOM is in left.php
			var isVisitor = $("#isVisitor")[0].value;
			if(isVisitor == 2){
				$().onUserExit({
					execute:function(){},
					internalURLs:	"www.blueteach.com|blueteach.com|www.glueteach.com|glueteach.com"
				});					
		}
	}				
	}catch(err){}

}
function ElementCommun(){
   // this one for sessions open in left
    $('.lessonNow').cycle({
		 fx:     'fade', 
		 speed:    800, 
   		 timeout:  800 
	});		        	
	clickBtnSettingManager();
	updateTimeZone4UserTmp('');
}
function clickBtnSettingManager(){
	notifVisitorQuit();	
	// this one is for btn setting
	$(document).click ( function(evt){
		try{
			if(evt.target.className != "settingsBtnStyle"&&evt.target.className != "moreoptionsBtnStyle"){
				closeElsOpen("ul","settingsList");
			}		
		}
		catch(err){	}
	});	
}

function new_setheaderMenu(){
	
		// this function is for the drop down menu in header.php
		$("ul.subnav").parent().append("<span class='navArrow'></span>"); // Only
																			// shows
																			// drop
																			// down
																			// trigger
																			// when
																			// js
																			// is
																			// enabled
																			// (Adds
																			// empty
																			// span
																			// tag
																			// after
																			// ul.subnav*)
	
		$("ul.topnav li span").click(function() { // When trigger is
													// clicked...
	
			// Following events are applied to the subnav itself (moving subnav
			// up and down)
			$(this).parent().find("ul.subnav").slideDown('fast').show(); // Drop
																			// down
																			// the
																			// subnav
																			// on
																			// click
	
			$(this).parent().hover(function() {
			}, function(){
				$(this).parent().find("ul.subnav").slideUp('slow'); // When the
																	// mouse
																	// hovers
																	// out of
																	// the
																	// subnav,
																	// move it
																	// back up
			});
	
			// Following events are applied to the trigger (Hover events for the
			// trigger)
			}).hover(function() {
				$(this).addClass("subhover"); // On hover over, add class
												// "subhover"
			}, function(){	// On Hover Out
				$(this).removeClass("subhover"); // On hover out, remove
													// class "subhover"
		});
		
		verifyNexBadgeUser();
}

function verifyNexBadgeUser(){
	var data = {
			action:'newbadge'
		}
	
	ajaxJqueryPost("sscripts/class_controler.php",data,repverifyNexBadgeUser);		

}
function repverifyNexBadgeUser(repJson){

	var result = repJson;
	if(result != null){
		var arraybadge=result.arraynewbadge;
		var params="";
		var Ar=new Array();
		if(arraybadge!=""&&arraybadge!=null){
			
			for(var i=0;i<arraybadge.length;i++){
				Ar.push({'name':arraybadge[i].name,'desc':arraybadge[i].desc,'image':arraybadge[i].image});
			
			}
			
			var action = {'params':Ar};
			createPopupAjaxJquery("popups.php",{'popup':'earnbadges','action':action},null,null);
		       $.fancybox.resize();
		}		
	}


}
function new_setTimeOutSessionOpen(){

	var frequence = 10000;
	ajaxGeneric("G",'sscripts/refreshpage_activelesson.php', null, 
		function(r,p) { 
			var rep = r.responseText;
			if (rep == 1) {
				new_getSessionsOpen();
			}
		}
		,null);
 	window.setTimeout("new_setTimeOutSessionOpen();", frequence);	

}

function new_getSessionsOpen(){
	
	var data = {action:'getsessionopen'};
	ajaxJqueryPost("sscripts/class_controler.php",data,new_getSessionsOpensComplete);

} 

function new_getSessionsOpensComplete(repJson){
	var result = null;
	var nbclass = 0;
	try{
		result = repJson;
	}
	catch(err){
		
	}
	
	if(result != null&&result!=''){
		
		var classarray = result.classarray;
		
			document.getElementById('joinSessionOpenDiv').innerHTML = new_addTemplateSessionOpen(classarray);
			if(classarray != null&&classarray!='')
				nbclass = classarray.length;
			
	}
	// document.getElementById('nbSessionsId').innerHTML = nbclass;

}
function new_addTemplateSessionOpen(classarray){
	
	var res = "";
	if(classarray != null&&classarray!=''){		
		for(var i=0;i<classarray.length;i++){		
			if( !checkIsHidden(classarray[i].id) ){
								
				var tpl = document.getElementById('templatePartAlertDiv').innerHTML;
				var classDiv = "templatePartAlertDiv_"+classarray[i].id;
				tpl = repS(tpl,"templatePartAlertDiv",classDiv);
				tpl = repS(tpl,"Participants","");
				tpl = repS(tpl,"Pid",classarray[i].pid);		
				tpl = repS(tpl,"DivId",classDiv);
				tpl = repS(tpl,"Id",classarray[i].id);				
				res +=tpl;					
			}			
		}	
	}
	return res ;
}
function checkIsHidden(id){
	
	for(var i=0;i< _hideMeArray.length;i++){
		if(_hideMeArray[i].id == id){
			
			return true;
			}
	}
	
	return false;
}
function hideMe(divid,id){

	_hideMeArray.push({id:id});
	document.getElementById(divid).style.display = 'none';
	
}
function new_setTimeOutMsg(){
	
	/*
	 * new_getNewMsgs(); var frequence = 10000;
	 * window.setTimeout("new_setTimeOutMsg();", frequence);
	 * 
	 */
}

function new_getNewMsgs(){

	var data = {action:'getnewmsg'};
	ajaxJqueryPost("sscripts/message_controler.php",data, new_getNewMsgComplete);
}
function new_getNewMsgComplete(repJson){
	var result = null;
	var newmsg = 0;

	try{
		result = repJson;
	}
	catch(err){
		
	}
	if(result != null){
		newmsg = result.newmsg;

	}
	var newMsgsAlertDOM = document.getElementById('newMsgsAlert');
	newMsgsAlertDOM.innerHTML = newmsg;	
	
}

/*
 * these function are used for btn setting
 */
function show(id){
	
	var sessionSettings = document.getElementById(id);
	if(sessionSettings.style.display =="block") {
		sessionSettings.style.display="none";
	}else{
		closeElsOpen("ul","settingsList");
		sessionSettings.style.display="block";
	}	
}
function closeElsOpen(tagname,classname){

	var tag = document.getElementsByTagName(tagname);
	for(var i=0;i<tag.length;i++){
		var el = tag[i];
		if(el.className == classname )
			el.style.display = "none";
		
	}
}

/*
 * fin btn setting
 */

// theses function are used for hover even on div:D
function div4HoverEventGenerate(bool,txtDivId,animeDivId){
	
	if(bool){
		// default
		if($(txtDivId).hide() && $(animeDivId).hide() )
			$(txtDivId).show();
		// onhover
		else if($(txtDivId).hide())	
			$(animeDivId).show();	
		// unhover
		else
			$(animeDivId).hide();	
	}
	else {
		
		$(txtDivId).hide();					
		$(animeDivId).hide();		
	}	
	
}
// this function is call back of fadein, using for IE7
function fadeInManager(div){
	$(div).fadeIn(180,function(){
		try{	this.style.removeAttribute('filter'); }
		catch(err){}
	
	});	
}



// pour agenda.php et past_session.php
function showSessionDetails(obj,iddivresult){

	var id = obj.parentNode.id;	
	
	if($(obj.parentNode).hasClass("row"))
	{	

		if($('#descriptUp_'+id).length!=0)
			$('#descriptUp_'+id).hide();
		if($('#descriptDown_'+id).length!=0)
			$('#descriptDown_'+id).show();	
			
		$('#sessionDetails_'+obj.parentNode.id).slideDown(1000);
		$(obj.parentNode).removeClass("row");
		$(obj.parentNode).addClass("largeRow");
		
		$(obj).removeClass("up");
		$(obj).addClass("down");
		HideOtherDivDetails(obj.parentNode.id,iddivresult);
		
		
	}
	else
	{
		if($('#descriptUp_'+id).length!=0)
			$('#descriptUp_'+id).show();
		if($('#descriptDown_'+id).length!=0)
			$('#descriptDown_'+id).hide();	
			
		$(obj.parentNode).removeClass("largeRow");
		$(obj.parentNode).addClass("row");
		$('#sessionDetails_'+obj.parentNode.id).hide();
		$(obj).removeClass("down");
		$(obj).addClass("up");
		
	}
}
function showListingDetails(obj,iddivresult){
	
	var id = obj.parentNode.id;	
	
	if($(obj.parentNode).hasClass("row"))
	{	
		$('#details_'+id).slideDown(1000);
	
		$(obj.parentNode).removeClass("row");
		$(obj.parentNode).addClass("largeRow");
		$(obj).removeClass("up");
		$(obj).addClass("down");
		
		HideOtherDivDetailsListing(id,iddivresult);
	}
	else
	{
		$(obj.parentNode).removeClass("largeRow");
		$(obj.parentNode).addClass("row");
		$('#details_'+obj.parentNode.id).hide();
		$(obj).removeClass("down");
		$(obj).addClass("up");
		
	}
}

function HideOtherDivDetails(liid,iddivresult){
	if(document.getElementById(iddivresult)!=null){
		var tagli= document.getElementById(iddivresult).getElementsByTagName('li');
		
		for(var i=0;i<tagli.length;i++){
			
			if(tagli[i].className=="alt largeRow"&&tagli[i].id!=liid){
				tagli[i].className="alt row";
				$('#sessionDetails_'+tagli[i].id).hide();
				
				var tagbutton=tagli[i].getElementsByTagName('button');
				for(var j=0;j<tagbutton.length;j++){
					if(tagbutton[j].className=="roundListBtn down")
						tagbutton[j].className="roundListBtn up";
				}
				
			}
	}		
}

}
function HideOtherDivDetailsListing(liid,iddivresult){
	if(document.getElementById(iddivresult)!=null){
		var tagli= document.getElementById(iddivresult).getElementsByTagName('li');
		
		for(var i=0;i<tagli.length;i++){
			if(tagli[i].className=="largeRow"&&tagli[i].id!=liid){
				
				tagli[i].className="row";
				
				$('#details_'+tagli[i].id).hide();
				var tagbutton=tagli[i].getElementsByTagName('button');
				for(var j=0;j<tagbutton.length;j++){
				
					if(tagbutton[j].className=="roundListBtnSmall down")
						tagbutton[j].className="roundListBtnSmall up";
				}
				
			}
	}		
}

}


// these functions are for btn start sesion in left.php
function showPopupStartSession(){
	$.fancybox({
			ajax : {type:"POST",data:{'popup':'divInstantEclass'}},
			type:'ajax',
			href:'popup_agenda.php',
			scrolling:'no'
		});

}

function showPopupStartSessionComplete(repJson){
	var result = null;
	try{
		result = repJson;
	}
	catch(err){	}
	
	if(result != null){	
		var body = addTemplateBtnSessionLeft(result);
		_popupStartSession = new_createPopupYui(1,"",body,"","","popupstartsession");
		document.getElementById('btnStartSessionLeft').disabled = false;		
	}
}


function addTemplateBtnSessionLeft(data){
	
	var currencys = data.currencys;
	var topics = data.topics;	
	var tpl = document.getElementById('templatePopupEclass').innerHTML;
	
// var optionCurrency = addTempleteMenuDeroulant("currencyid",currencys);
	var optionTopic = addTempleteMenuDeroulant("topicid",topics);
	// tpl = repS(tpl,"CurrencyOption",optionCurrency);
		tpl = repS(tpl,"TopicOption",optionTopic);	
		tpl = repS(tpl,"Horlyrate","horlyrate");
		tpl = repS(tpl,"FctCancel","closePopupStartSession()");
	return tpl;
}

function addTempleteMenuDeroulant(idname,data){
	
	if(data != null){
		var res = "<select id='"+idname+"' name='"+idname+"' class='selectInputPopupEclass'>";
		for(var i=0;i<data.length;i++){
			var tpl = "<option value='"+data[i].id+"'>"+data[i].name+"</option>";
			res +=tpl;
		}
	res +="</select>";
	return res;
	}	
}
function closePopupStartSession(){

	
	if(typeof(_popupStartSession) != "undefined" && _popupStartSession != null){
		_popupStartSession.destroy();
		_popupStartSession = null;
	}
	
}
function windowOpenEclass(url) 
{
 window.open(url,'','left=0,top=0,resizable=yes'); 
/*
 * params = 'width=screen.width'; params += ', height=screen.height'; params += ',
 * top=0, left=0' params += ', resizable=yes';
 * newwin=window.open(url,'windowname4', params); if (window.focus)
 * {newwin.focus()} return false;
 */
}

function startSessionLeft(){
		var topicid=98;
		var horlyrate= 0;
		var currencyid=2;
		var levelid = 1;
		var session_params = {'topicid':topicid,'levelid':levelid,'currencyid':currencyid,'horlyrate':horlyrate};

		if(!startSessionLeft4Visitor(session_params)){
			// this DOM is in left.php
			// document.getElementById('btnStartSessionLeft').disabled = true;

			var isVisitor = $("#isVisitor")[0].value;						
			// window.open('directToEclass.php?idtopic='+topicid+'&idlevel='+levelid+'&horlyrate='+horlyrate+'&idcurrency='+currencyid,'','left=0,top=0');
			windowOpenEclass('directToEclass.php?idtopic='+topicid+'&idlevel='+levelid+'&horlyrate='+horlyrate+'&idcurrency='+currencyid);
		}
}
// fin templete start session left
function startSessionLeft4Visitor(session_params){
	
	var horlyrate = parseInt(session_params.horlyrate) ;
	var action = {'action':'quicksessionpay','params':session_params};
	var isVisitor = document.getElementById('isVisitor').value;
	if(isVisitor != 0 && horlyrate > 0){
		showPopupSignup("choice",action);
		return true;
	}
	else if(isVisitor == 1 && horlyrate == 0){
		initUser4Visitor("startsessionleft");
		return true;
	}
	
	return false;
	
}
function ajaxJqueryPost(url,data,fct){
    $.post(url, data, 
        function(res)
        {	
        fct(res);
        },"json"
    );	
}
function createPopupAjaxJquery(url,data,onCompleteFct,onCloseFct){
	$.fancybox(
		{
			ajax : {type:"POST",data:data},
			type:'ajax',
			href:url,
			onComplete:onCompleteFct,				
			onClosed:onCloseFct,
			scrolling:'no',
			padding           : 0,
		    autoScale    	: false
									
		});	

}
/*
 * function gotoForum(){
 * 
 * var isVisitor = document.getElementById('isVisitor').value; if(isVisitor !=
 * 0){ showPopupSignup("forbidden",action); } }
 */
// popup sign up
function showPopupSignup(mode,action){	
		
	try{
		closePopupStartSession();
	}
	catch(err){	}
	if(mode == "choice"){
		createPopupAjaxJquery("popups.php",{'popup':'signup','action':action},onloadPopupSignupComplete,null);
	}
	else if(mode == "forbidden"){
		createPopupAjaxJquery("popups.php",{'popup':'signup','action':action},onloadPopupSignupComplete,closePopupForbidden);			
	}	
}
function closePopupForbidden(){
	window.history.back();	
}
function closePopupSignup(){
	$.fancybox.close();
}
function imageCheckFormManager(bool,input,idok,idnok){
	if(bool){
		$(input).removeClass("checkNotOk");
		$(input).addClass("checkOk");
		$(idok).show();
		$(idnok).hide();
	}
	else{
		$(input).removeClass("checkOk");
		$(input).addClass("checkNotOk");
		$(idok).hide();
		$(idnok).show();		
	}
}

function checkMailSignupAlreadyUsed(email){
	
	var email_old = $("#email_signup_old")[0].value;
	if( email != email_old  ){
		var data = {
			action:'checkemail',
			email:email
		};
		ajaxJqueryPost("sscripts/user_controler.php",data,checkEmailAreadyUsedComplete);	
	}
		
}
function checkEmailAreadyUsedComplete(repJson){
	try{
		var result = repJson;
		if(result.result == 0){
			$("#email_signupCheck")[0].value = 1;
			imageCheckFormManager(true,"#email_signup","#email_signupOK","#email_signupNOK");	
			$("#email_signup_old")[0].value = result.email;			
		}
		else{
			$("#email_signupCheck")[0].value = 0;			
			$("#email_signup_old")[0].value = result.email;		
			imageCheckFormManager(false,"#email_signup","#email_signupOK","#email_signupNOK");	
		}					
	}catch(err){
		
	}
}
function onloadPopupSignupComplete(){
	
	$("#popupSignup input").each(
		function(i,evt){
			if(evt != null && ( evt.type == "text" || evt.type == "password" ) ){
				
				// if( evt.id != null && evt.id != "email_signup" && evt.id !=
				// "verif_code_signup" ){
				if( evt.id != null && evt.id != "email_signup"){

					$("#"+evt.id).blur(function(){
						var id = evt.id											
						var val = $("#"+id)[0].value; 
						var idOK = id+"OK";
						var idNOK = id + "NOK";
						var idCheck = id+"Check";
						
						var imageCheck = false;

						if( ( (id != "password_signup" && val.length >= 3) || ( id == "password_signup" && val.length >= 4 ) ) && val != "" &&  val != null){
							imageCheck = true;
							$("#"+idCheck)[0].value = 1;
						}
						else{
							imageCheck = false;		
							$("#"+idCheck)[0].value = 0;												
						}

						imageCheckFormManager(imageCheck,"#"+id,"#"+idOK,"#"+idNOK);										

					});					
				}
				else if(evt.id != null && evt.id == "email_signup" ){
					
					$("#"+evt.id).blur(
						function(){
							var id = evt.id					
							var val = $("#"+id)[0].value; 
							var idOK = id+"OK";
							var idNOK = id + "NOK";
							
							var imageCheck = false;
											
							if(isValidEmail(val) ){
								checkMailSignupAlreadyUsed(val);				
							}	
							else{
								imageCheckFormManager(false,"#"+id,"#"+idOK,"#"+idNOK);														
								("#email_signupCheck")[0].value = 0;		
							}
						}
					);
				}	
			}
		}
	);

	
}

/*
 * function checkVerifCode(){ var verifcode = $("#verif_code_signup")[0].value;
 * var data = "action=verifycode&verifcode="+verifcode;
 * getDataValueJSON("sscripts/user_controler.php",data,checkCodeComplete); }
 * 
 * function checkCodeComplete(repJson){
 * 
 * var verifcodeCheck = $("#verif_code_signupCheck");
 * 
 * if(repJson){
 * 
 * if(repJson.result == 0){ verifcodeCheck[0].value = 1; } else {
 * verifcodeCheck[0].value = 1; } } }
 */

function checkFormSignup(){
	// checkVerifCode();
	var firstnameCheck = $("#firstname_signupCheck")[0].value;
	var lastnameCheck = $("#lastname_signupCheck")[0].value;
	var emailCheck = $("#email_signupCheck")[0].value;
	var pwdCheck = $("#password_signupCheck")[0].value;	
	
	// var verifcodeCheck = $("#verif_code_signupCheck")[0].value;
	
	// if(firstnameCheck == 1 && lastnameCheck == 1 && emailCheck == 1 &&
	// pwdCheck == 1 && verifcodeCheck == 1)
	if(firstnameCheck == 1 && lastnameCheck == 1 && emailCheck == 1 && pwdCheck == 1)
		return true;
	
	return false;
}

// create user from popup signup
function createUser4Visitor(){
	
	if(checkFormSignup()){
		var action = "";
		
		// this DOM is in left.php
		var isVisitor = 1;
		if ( $("#isVisitor").length > 0 ) 
			isVisitor = $("#isVisitor")[0].value;	
		
		var isok4newsletter = 0;
		var firstname = $("#firstname_signup")[0].value;
		var lastname = $("#lastname_signup")[0].value;
		var email = $("#email_signup")[0].value;
		var password = $("#password_signup")[0].value;		
		var callback = $("#callback")[0].value;
	
		// var verifcode = $("#verif_code_signup")[0].value;
		
		var pid = 0;
		if($("#pid").length > 0){
			pid = $("#pid")[0].value;
		}
		// if(firstname == "" || lastname == "" || email == "" || password == ""
		// || verifcode == "")
		if(firstname == "" || lastname == "" || email == "" || password == "")
			return;
		if(!isValidEmail(email))
			return ;	
		if(isVisitor == 1)
			action ="createvisitor";		
		else if(isVisitor == 2 )
				action = "validvisitor";
		
		var userid = 0;
		if($("#userid").length > 0){
			userid = $("#userid")[0].value;
		}
		var topicid = 0;
		var levelid = 0;
		var currencyid = 0;
		var horlyrate = 0;
		if($("#topicid").length > 0)
			topicid = $("#topicid")[0].value;
		if($("#levelid").length > 0)		
			levelid = $("#levelid")[0].value;
		if($("#currencyid").length > 0)
			currencyid = $("#currencyid")[0].value;
		if($("#holyrate").length > 0)		
			horlyrate = $("#horlyrate")[0].value;		
		
		var toid = 0;
		if($("#toid").length > 0)
			toid = $("#toid")[0].value;

		var sessionid = 0;
		var agendaaction = '';
		var totalfee =0;
		var userkey='';
		if($("#sessionid").length > 0)
			sessionid = $("#sessionid")[0].value;
		if($("#agendaaction").length > 0)		
			agendaaction = $("#agendaaction")[0].value;
		if($("#totalfee").length > 0)				
			totalfee = $("#totalfee")[0].value;
		var userkey = '';
		if(typeof key != 'undefined')
			userkey=key;	
		
		var parentid = 0;
		var type = 0;
		var msg = '';
		if($("#parentid").length > 0)
			parentid = $("#parentid")[0].value;
		if($("#type").length > 0)
			type = $("#type")[0].value;
		if($("#msg").length > 0)		
			msg =  codeUrl($("#msg")[0].value);		
		
		var tonickname ='';
		if($("#tonickname").length > 0)
			tonickname =$("#tonickname")[0].value;
		

		
		var val=calculate_time_zone();
		val=val.split(',');
		var decalage = codeUrl(val[0]);
		var dst = val[1];		

		if( $("#newsletter").length > 0 && document.getElementById('newsletter').checked ){
			isok4newsletter = 1;
		}		

		
		if(action != "")
			var data = {

				action:action,
				firstname:codeUrl(firstname),
				lastname:codeUrl(lastname),
				email:email,
				password:password,
				callback:callback,
				pid:pid,
				userid:userid,
				topicid:topicid,
				levelid:levelid,
				currencyid:currencyid,
				horlyrate:horlyrate,				
				toid:toid,
				sessionid:sessionid,
				agendaaction:agendaaction,
				totalfee:totalfee,
				userkey:userkey,
				parentid:parentid,
				type:type,
				msg:msg,
				tonickname:tonickname,
				decalage:decalage,
				dst:dst,
				isok4newsletter:isok4newsletter
				
				
		};
	
				
		if(action != ""){
			
			ajaxJqueryPost("sscripts/user_controler.php",data,createUserFromPopupComplete);	
			$("#btnCreateUser")[0].disabled = true;		
		}			
	}

}
function createUserFromPopupComplete(repJson){
	
	var topicid = 0;
	var levelid = 0;
	var currencyid = 0;
	var horlyrate = 0;
	var refresh = false;
	try{
		var result = repJson;
		if(result != null){
			
			if(result.result == "ok"){
				googleTracker("signup");
				var params = result.params;
				
				if(params != null){
					
					if(params.callback == "quicksessionpay"){
						topicid = params.topicid;
						levelid = params.levelid;
						currencyid = params.currencyid;
						horlyrate = params.horlyrate;
						if(topicid != 0 && levelid != 0 && currencyid != 0){
							windowOpenEclass('directToEclass.php?idtopic='+topicid+'&idlevel='+levelid+'&horlyrate='+horlyrate+'&idcurrency='+currencyid);
							// window.open('directToEclass.php?idtopic='+topicid+'&idlevel='+levelid+'&horlyrate='+horlyrate+'&idcurrency='+currencyid,'','left=0,top=0');
							location.reload();
						}
							
					}
					else if(params.callback == "write"){
						
						toid = params.toid;
						document.location.href = "newmsg.php?to="+toid;
					
					}
					else if(params.callback == "plan"){
						pid = params.pid;
						document.location.href = "quickLesson.php?pid="+params.pid;
					}
					else if(params.callback == "profile" || params.callback == "createsession"){
						location.reload();
					}
					else if(params.callback == "gestionAgendaFicheuser"){

						var thedata={
							idlesson:params.sessionid,	
							action:params.agendaaction,
							totalfee:codeUrl(params.totalfee)				
						};
						
						gestionAgendaFicheuserbis(thedata);	
							
					}
					else if(params.callback =="gestionWall"){
						
						var data={
							parentid:params.parentid,
							action:'createwall',
							msg: params.msg,
							type:params.type								
						};
					
						ajaxJqueryPost("sscripts/wallsession.php",data,repcreateWallbis);
							
					}
					else if(params.callback =="gestionFeed"){
						
						var data = {
							action:'createfeed',
							msg:codeUrl(params.msg)
						};
					
						ajaxJqueryPost("sscripts/feed_controler.php",data,repcreateNewFeedUserbis);
							
					}
					else if(params.callback == "sendrequestsession" || params.callback == "sendproposesession" ){
						document.getElementById('isVisitor').value = 0;
						// showPopupSignup("choice",null);
						var data = {
							toid:params.toid,
							tonickname:params.tonickname								
						};
						
						if(params.callback == "sendrequestsession")
							ficheuserRequestClass(params.toid,params.tonickname);
						else if(params.callback == "sendproposesession")
							ficheuserProposeClass(params.toid,params.tonickname);							
					}
					else if(params.callback == "index" || params.callback == "signupHome")
						document.location.href = "index.php";
					else if(params.callback == "signup_p")
						// document.location.href = "index.php";
						document.location.href = "bustframe.php?page=index.php";
					else
						location.reload();					
				}
				
				
			}
			else{
				alert(MLJS("txtOopsSthgWrongSignUp"));
			}			
		}		
	}
	catch(err){	}	

}
// fin popup signup
// this function used for goolge analytics
function googleTracker(mode){
	var googlecode = document.getElementById('googleAnalyticCode').value;
	var page = "";
	if(mode == "tmp")
		page = "/action/usagetemp";
	else if(mode == "signup")
		page = "/action/signup";
	else if(mode == "home")
		page = "/action/home";
	else if(mode == "try")	
		page = "action/try";
	else if(mode=="startbuycredit")
		page="action/startbuycredit";
	else if(mode=="buycreditok")
		page="action/buycreditok";
	else if(mode=="buycreditnok")
		page="action/buycreditnok";
	try{	
		var pageTrackerInternal = _gat._getTracker(googlecode);		
		pageTrackerInternal._trackPageview(page);	
	}
	catch(err){
	}
}
// function allows to create user tmp automatique
function initUser4Visitor(callback){
	var action = "";
	// this DOM is in left.php
	var isVisitor = $("#isVisitor")[0].value;
	if(isVisitor == 1){
		action = "initvisitor";
	}
	var data = {
		action:action,
		callback:callback
	};
	ajaxJqueryPost("sscripts/user_controler.php",data,initUser4VisitorComplete);		
}
function initUser4VisitorComplete(repJson){
	
	try{
		var result = repJson;
		if(result.result == "ok"){
			var callback = result.callback;
			googleTracker("tmp");
			if(callback=="startsessionleft"){
				$("#isVisitor")[0].value = 2;
				updateTimeZone4UserTmp('startsessionleft');
			}
			else if(callback == "createsession")
				new_createSession();	
			else if(callback == "submitform")
				return true;
		}	
	}catch(err){
		
	}
}
// this function allows to update time fuseau for user tmp
function updateTimeZone4UserTmp(callback){
	// this dom is in js_lib_commun_inc.php
	if(("#updateUserFuseau").length > 0){
		var updateUserFuseau = $("#updateUserFuseau")[0].value;
		if(updateUserFuseau == 1){
			var val=calculate_time_zone();
			val=val.split(',');
			var data = {
					action:'updatetimezone',
					decalage:codeUrl(val[0]),
					dst:val[1],
					callback:callback					
			} ;
			ajaxJqueryPost("sscripts/user_controler.php",data,updateTimeZone4UserTmpComplete);	
		}		
	}


}	
function updateTimeZone4UserTmpComplete(repJson){
	try{
		var result = repJson;
		if(result != null && result.result == "ok"){
			if(result.callback == "startsessionleft")
				startSessionLeft();		
				location.reload();		
		}	
	}catch(err){
		
	}	

}
// this function allows to know if visitor do some action => google :D
function checkCreatedTmp(isUserTmpCreated){
	// this DOM is in left.php
	var isVisitor = $("#isVisitor")[0].value;
	
	if(isVisitor == 2 && isUserTmpCreated == 1)
		googleTracker("tmp");
}
// these functions are for textearea
function setSelectionRange(input, selectionStart, selectionEnd) {
  if (input.setSelectionRange) {
    input.focus();

    input.setSelectionRange(selectionStart, selectionEnd);
  }
  else if (input.createTextRange) {

    var range = input.createTextRange();
    range.collapse(true);
    range.moveEnd('character', selectionEnd);
    range.moveStart('character', selectionStart);
    range.select();
  }
}

function setCaretToPos (input, pos) {
  setSelectionRange(input, pos, pos);
}  
// fin function for textarea

// function for login && logout
function loginManager(form){
	
	if(form == "open"){
		$("div#panel").slideDown("slow");

	}
	else if(form == "close"){
		$("div#panel").slideUp("slow");			
	}	
	$("#toggle a").toggle();

}
function showEventDiv(event,blockid){

	if (event == "confirmed"){
		
		document.getElementById("liEventConfirmed_"+blockid).className = "currentEvent";
		document.getElementById("liEventDeclined_"+blockid).className = "";
		document.getElementById("liEventNoReply_"+blockid).className = "";
		
		if(document.getElementById("liEventAskInvitation_"+blockid)!=null)
			document.getElementById("liEventAskInvitation_"+blockid).className = "";
		
		document.getElementById("confirmedBlock_"+blockid).style.display="block";
		document.getElementById("declinedBlock_"+blockid).style.display="none";
		document.getElementById("noreplyBlock_"+blockid).style.display="none";
		
		if(document.getElementById("askinvitationBlock_"+blockid)!=null)
			document.getElementById("askinvitationBlock_"+blockid).style.display="none";
		
	} else if (event == "declined"){
		document.getElementById("liEventConfirmed_"+blockid).className = "";
		document.getElementById("liEventDeclined_"+blockid).className = "currentEvent";
		document.getElementById("liEventNoReply_"+blockid).className = "";
		
		if(document.getElementById("liEventAskInvitation_"+blockid)!=null)
			document.getElementById("liEventAskInvitation_"+blockid).className = "";
		
		document.getElementById("confirmedBlock_"+blockid).style.display="none";
		document.getElementById("declinedBlock_"+blockid).style.display="block";
		document.getElementById("noreplyBlock_"+blockid).style.display="none";
		
		if(document.getElementById("askinvitationBlock_"+blockid)!=null)
			document.getElementById("askinvitationBlock_"+blockid).style.display="none";
		
	} else if (event == "noreply") {
		document.getElementById("liEventConfirmed_"+blockid).className = "";
		document.getElementById("liEventDeclined_"+blockid).className = "";
		document.getElementById("liEventNoReply_"+blockid).className = "currentEvent";
		
		if(document.getElementById("liEventAskInvitation_"+blockid)!=null)
			document.getElementById("liEventAskInvitation_"+blockid).className = "";
		
		document.getElementById("confirmedBlock_"+blockid).style.display="none";
		document.getElementById("declinedBlock_"+blockid).style.display="none";
		document.getElementById("noreplyBlock_"+blockid).style.display="block";
		
		if(document.getElementById("askinvitationBlock_"+blockid)!=null)
			document.getElementById("askinvitationBlock_"+blockid).style.display="none";	
	}
	else{
		document.getElementById("liEventConfirmed_"+blockid).className = "";
		document.getElementById("liEventDeclined_"+blockid).className = "";
		document.getElementById("liEventNoReply_"+blockid).className = "";
		
		if(document.getElementById("liEventAskInvitation_"+blockid)!=null)
			document.getElementById("liEventAskInvitation_"+blockid).className = "currentEvent";
		
		document.getElementById("confirmedBlock_"+blockid).style.display="none";
		document.getElementById("declinedBlock_"+blockid).style.display="none";
		document.getElementById("noreplyBlock_"+blockid).style.display="none";	
		
		if(document.getElementById("askinvitationBlock_"+blockid)!=null)
			document.getElementById("askinvitationBlock_"+blockid).style.display="block";
	}
}

// decalage horaire
function calculate_time_zone() {
	var dateuser = new Date();
	var jan1 = new Date(dateuser.getFullYear(), 0, 1, 0, 0, 0, 0);  // jan 1st
	var june1 = new Date(dateuser.getFullYear(), 6, 1, 0, 0, 0, 0); // june 1st
	var temp = jan1.toGMTString();
	var jan2 = new Date(temp.substring(0, temp.lastIndexOf(" ")-1));
	temp = june1.toGMTString();
	var june2 = new Date(temp.substring(0, temp.lastIndexOf(" ")-1));
	var std_time_offset = (jan1 - jan2) / (1000 * 60 * 60);
	var daylight_time_offset = (june1 - june2) / (1000 * 60 * 60);
	var dst="0";
	
	if (std_time_offset == daylight_time_offset) {
		dst = "0"; // daylight savings time is NOT observed
	} else {
		// positive is southern, negative is northern hemisphere
		var hemisphere = std_time_offset - daylight_time_offset;
		if (hemisphere >= 0)
			std_time_offset = daylight_time_offset;
		dst = "1"; // daylight savings time is observed
	}
	var hour= parseInt(std_time_offset);
   	var mins =parseInt((std_time_offset-hour)*60);
	
	if (hour == 0) 
		hour = "00";
	else if (hour >9) 
		hour ="+"+hour;
	else if (hour >0&&hour <10) 
		hour = "+0"+hour;
	else if (std_time_offset<-9) 
		hour = "-"+hour;
	else
		hour = "-0"+hour;
	if (mins == 0) 
		mins = "00";
		
	var decalage=hour+":"+mins;
	
	var data=decalage+","+dst;
	return data;
}

// CONCERNE LE WALL DANS infossesion.php, ficheuser.php, wishlist.php,
function loadWall(parentid,type){
	/*
	 * var data='parentid='+parentid; data+='&action=showwall';
	 * data+='&type='+type;
	 * 
	 * getDataValueJSON("sscripts/wallsession.php",data,reploadWall);
	 */
	var data = {
			parentid:parentid,
			action:'showwall',
			type:type
		};
	ajaxJqueryPost("sscripts/wallsession.php",data,reploadWall);
	
}

function reploadWall(jsonRep){
	
	var res="";
	var infowallarray=jsonRep;
	
	var wallarray=infowallarray.wallarray;
	var userid=infowallarray.userid;
	var parentid=infowallarray.parentid;
	
	if(wallarray!=null&&wallarray!=""){
	
		for(var i=0;i<wallarray.length;i++){
			
			res +=addInfo2TemplateWall(wallarray[i],userid,parentid);
			
	 	}
	}
	
	var templateHautWallDiv=document.getElementById('templateHautWallDiv').innerHTML;
	templateHautWallDiv=repS(templateHautWallDiv,"Parentid",parentid);
	document.getElementById('sessionWall').innerHTML=templateHautWallDiv
	
	if(res=='')
		res=document.getElementById('templateNoWallDiv').innerHTML;
		
	document.getElementById('sessionWall').innerHTML+='<ul>'+res+'</ul>';
	
	$("#textwall").elastic();
}

function addInfo2TemplateWall(wall,userid,parentid){

	var templateWallInfoDiv = "";
	
	if(wall != null){
		templateWallInfoDiv = document.getElementById('templateWallInfoDiv').innerHTML;
		
		templateWallInfoDiv=repS(templateWallInfoDiv,"Wallsrcuser",wall.frompic);
		templateWallInfoDiv=repS(templateWallInfoDiv,"Id",wall.id);
		templateWallInfoDiv=repS(templateWallInfoDiv,"Parentid",parentid);
		templateWallInfoDiv=repS(templateWallInfoDiv,"Nicknamewall",wall.fromnickname);
		
		if(wall.fromid!=userid){
			templateWallInfoDiv=repS(templateWallInfoDiv,"Firstnamewall",wall.fromfirstname);
			templateWallInfoDiv=repS(templateWallInfoDiv,"Lastnamewall",wall.fromlastname);
		}else{
			templateWallInfoDiv=repS(templateWallInfoDiv,"Firstnamewall",MLJS("txtYou"));
			templateWallInfoDiv=repS(templateWallInfoDiv,"Lastnamewall","");
		}
		
		if(wall.ownerid==userid||wall.fromid==userid)
			templateWallInfoDiv=repS(templateWallInfoDiv,"remove","remove");
		else
			templateWallInfoDiv=repS(templateWallInfoDiv,"remove","");
			
		templateWallInfoDiv=repS(templateWallInfoDiv,"Msg",wall.body);
		
		if(wall.timedate==1)
			templateWallInfoDiv=repS(templateWallInfoDiv,"Poste",MLJS("txtToday"));
		else if(wall.timedate==2)
			templateWallInfoDiv=repS(templateWallInfoDiv,"Poste",MLJS("txtYesterday"));
		else
			templateWallInfoDiv=repS(templateWallInfoDiv,"Poste",wall.dayweek+" "+wall.month+" "+wall.date);
			
		templateWallInfoDiv=repS(templateWallInfoDiv,"Time",wall.hour);
	}
	return templateWallInfoDiv;
}

function createWall(parentid,type){
	
	var msg=document.getElementById("textwall").value;
	msg=Trim(msg);
	if(msg.length>0){
		var params = {'parentid':parentid,'type':type,'msg':msg};	
		var action = {'action':'gestionWall','params':params};
		var isVisitor = $("#isVisitor")[0].value;
		if(isVisitor != 0){
			showPopupSignup("choice",action);
			return;			
		}else{
			createCallGeneric(parentid,type,msg,repcreateWall);			
			/*
			var data={
				parentid:parentid,
				action:'createwall',
				msg:codeUrl(msg),
				type:type					
			};
			
			ajaxJqueryPost("sscripts/wallsession.php",data,repcreateWall);
			*/
		}
	}
}
function createWallSearch(parentid,type){
	
	var msg=document.getElementById("textwall").value;
	msg=Trim(msg);
	if(msg.length>0){
		var params = {'parentid':parentid,'type':type,'msg':msg};	
		var action = {'action':'gestionWall','params':params};
		var isVisitor = $("#isVisitor")[0].value;
		if(isVisitor != 0){
			showPopupSignup("choice",action);
			return;			
		}else{
			
			createCallGeneric(parentid,type,msg,repcreateWallSearch);			
		}
	}
}
function createCallGeneric(parentid,type,msg,feedback){

	var data={
			parentid:parentid,
			action:'createwall',
			msg:msg,
			type:type					
		};
	
	ajaxJqueryPost("sscripts/wallsession.php",data,feedback);
}



function Trim (str) {
	var	str = str.replace(/^\s\s*/, ''),
		ws = /\s/,
		i = str.length;
	while (ws.test(str.charAt(--i)));
	return str.slice(0, i + 1);
}

function repcreateWall(jsonRep){
	
	var infowallarray=jsonRep;
	
	var res=infowallarray.res;
	if(res=='ok'){
		var parentid=infowallarray.parentid;
		var type=infowallarray.type;
		loadWall(parentid,type);
	}
}
function repcreateWallbis(jsonRep){
	parent.location="javascript:location.reload()";
}
function repcreateWallSearch(){
	document.location.href='wishlist.php';
}
function removeWall(idwall,parentid,type){
	
	var data={
		parentid:parentid,		
		idwall:idwall,
		action:'removewall',
		type:type
	};
	ajaxJqueryPost("sscripts/wallsession.php",data,repcreateWall);
	
}

function addElement(date,hour,min) {

  
  var ni = document.getElementById('myDiv');  
  counter +=1;
  numArray.push({'id':counter});
 
  var newdiv = document.createElement('div');
  var divIdName = 'my'+counter+'Div';
  newdiv.className='dateLine';
  newdiv.setAttribute('id',divIdName);
  var temp=document.getElementById('templateDate').innerHTML;
  temp=repS(temp,"Num",counter);
  newdiv.innerHTML =temp ;
  ni.appendChild(newdiv);
 
  initDateSession(counter,date,'null');
  initTimePickerSession(counter,hour,min);
  $.fancybox.resize();
}
function removeElement(num) {
	
 
 for(var i=0;i<numArray.length;i++){
		if(numArray[i].id==num)
			 numArray.splice(i,1);
  }
 
 var divIdName = 'my'+num+'Div';
 var d = document.getElementById('myDiv');
 var olddiv = document.getElementById(divIdName);
 d.removeChild(olddiv);
}

function initDateSession(num,firstdatedefault){
	
	if(document.getElementById("date"+num)!=null){
	    
	    var minDate='';
	    
	    if(firstdatedefault=='null'){
	  		var now=new Date();
	  		firstdatedefault=now.format('M-d-Y');
	  	}
	  	
  		var firstvalue=firstdatedefault.split('-');
 		var firstjour=firstvalue[1];
 		var firstmois=indexMoisDate(firstvalue[0]);
  		var firstannee=firstvalue[2];	
  		minDate=new Date(firstannee,firstmois,firstjour);
	  	
	  	document.getElementById("date"+num).value=firstdatedefault;
	    $("#date"+num).datepicker({
	    	minDate:minDate
	    }); 
	 
	    
    }
}

function initTimePickerSession(num,defaulthour,defaultmin){
	
	if(defaulthour=='null')
		defaulthour=new_getTimeActuel4QuickLesson().hr;
	
	if(defaultmin=='null')
		defaultmin=new_getTimeActuel4QuickLesson().min;
	
	if(document.getElementById("timepicker"+num)!=null){
		 
    	 // init time picker start time
	    $(".timepicker"+num).jtimepicker({
	        // Configuration goes here
	        clockIcon: 'jquery/images/icon_clock_2.gif', 
	      	hourDefaultValue:defaulthour,
	        minDefaultValue:defaultmin,
	        hourCombo: 'hourcombo'+num,
	        minCombo: 'mincombo'+num,
	        hourSlider: 'hourSlider'+num,
	         minSlider: 'minSlider'+num,
	    	secView: false,
	    	secLabel:num
	    });
	   
    }
}
function initTimePickerDurationSession(hour,min){
	$("#durationpicker0").jtimepicker({
        // Configuration goes here
	        clockIcon: 'jquery/images/icon_clock_2.gif', 
            // set hours
            hourMode: 5,
            hourCombo:'durationH0',
            minCombo:'durationM0', 
            hourSlider: 'durationHSlider0', 
            hourDefaultValue: hour, 
            minSlider: 'durationMSlider0',             
            // set minutes
            minInterval: 5,
            minDefaultValue:min,        
    		secView: false,
    		secLabel:'0'
    });
}


// Simulates PHP's date function
Date.prototype.format = function(format) {
	var returnStr = '';
	var replace = Date.replaceChars;
	for (var i = 0; i < format.length; i++) {
		var curChar = format.charAt(i);
		if (replace[curChar]) {
			returnStr += replace[curChar].call(this);
		} else {
			returnStr += curChar;
		}
	}
	return returnStr;
};
Date.replaceChars = {
	shortMonths: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
	longMonths: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
	shortDays: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
	longDays: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
	
	// Day
	d: function() { return (this.getDate() < 10 ? '0' : '') + this.getDate(); },
	D: function() { return Date.replaceChars.shortDays[this.getDay()]; },
	j: function() { return this.getDate(); },
	l: function() { return Date.replaceChars.longDays[this.getDay()]; },
	N: function() { return this.getDay() + 1; },
	S: function() { return (this.getDate() % 10 == 1 && this.getDate() != 11 ? 'st' : (this.getDate() % 10 == 2 && this.getDate() != 12 ? 'nd' : (this.getDate() % 10 == 3 && this.getDate() != 13 ? 'rd' : 'th'))); },
	w: function() { return this.getDay(); },
	z: function() { return "Not Yet Supported"; },
	// Week
	W: function() { return "Not Yet Supported"; },
	// Month
	F: function() { return Date.replaceChars.longMonths[this.getMonth()]; },
	m: function() { return (this.getMonth() < 9 ? '0' : '') + (this.getMonth() + 1); },
	M: function() { return Date.replaceChars.shortMonths[this.getMonth()]; },
	n: function() { return this.getMonth() + 1; },
	t: function() { return "Not Yet Supported"; },
	// Year
	L: function() { return (((this.getFullYear()%4==0)&&(this.getFullYear()%100 != 0)) || (this.getFullYear()%400==0)) ? '1' : '0'; },
	o: function() { return "Not Supported"; },
	Y: function() { return this.getFullYear(); },
	y: function() { return ('' + this.getFullYear()).substr(2); },
	// Time
	a: function() { return this.getHours() < 12 ? 'am' : 'pm'; },
	A: function() { return this.getHours() < 12 ? 'AM' : 'PM'; },
	B: function() { return "Not Yet Supported"; },
	g: function() { return this.getHours() % 12 || 12; },
	G: function() { return this.getHours(); },
	h: function() { return ((this.getHours() % 12 || 12) < 10 ? '0' : '') + (this.getHours() % 12 || 12); },
	H: function() { return (this.getHours() < 10 ? '0' : '') + this.getHours(); },
	i: function() { return (this.getMinutes() < 10 ? '0' : '') + this.getMinutes(); },
	s: function() { return (this.getSeconds() < 10 ? '0' : '') + this.getSeconds(); },
	// Timezone
	e: function() { return "Not Yet Supported"; },
	I: function() { return "Not Supported"; },
	O: function() { return (-this.getTimezoneOffset() < 0 ? '-' : '+') + (Math.abs(this.getTimezoneOffset() / 60) < 10 ? '0' : '') + (Math.abs(this.getTimezoneOffset() / 60)) + '00'; },
	P: function() { return (-this.getTimezoneOffset() < 0 ? '-' : '+') + (Math.abs(this.getTimezoneOffset() / 60) < 10 ? '0' : '') + (Math.abs(this.getTimezoneOffset() / 60)) + ':' + (Math.abs(this.getTimezoneOffset() % 60) < 10 ? '0' : '') + (Math.abs(this.getTimezoneOffset() % 60)); },
	T: function() { var m = this.getMonth(); this.setMonth(0); var result = this.toTimeString().replace(/^.+ \(?([^\)]+)\)?$/, '$1'); this.setMonth(m); return result;},
	Z: function() { return -this.getTimezoneOffset() * 60; },
	// Full Date/Time
	c: function() { return this.format("Y-m-d") + "T" + this.format("H:i:sP"); },
	r: function() { return this.toString(); },
	U: function() { return this.getTime() / 1000; 
}
}
function indexMoisDate(shortmois){
	var shortMonths= new Array();
	var shortMonths=['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
	for(var j=0;j<shortMonths.length;j++)
	{
			if(shortMonths[j]==shortmois)
				return j;
	}
	return 0;
}

function addSubtopics(value){

	var res = checkItemInArrayByValue(oldSubtopics,value.name); 
	var nb = 1;
	var index = 0;
	if(res.index !== null){
		nb = (parseInt(res.nb) + 1);
		index = res.index;
	}
	if(nb != 1)
		oldSubtopics.splice(index,1);	
	
	oldSubtopics.push({'id':value.id,'name':$.trim(value.name),'nb':nb});

}
function removeSubtopics(id){
	var res = checkItemInArrayById(oldSubtopics,id); 
	var nb = 0;
	var index = 0;
	if(res.index !== null){
		index = res.index;
		nb = ( parseInt(res.nb) - 1 );
		var id = oldSubtopics[index].id;
		var value = oldSubtopics[index].name;
		oldSubtopics.splice(res.index,1);	
		if(nb != 0)
			oldSubtopics.push({'id':id,'name':$.trim(value),'nb':nb});

	}

}
function addNewSubtopics(value){
	var res = checkItemInArrayByValue(newSubtopics,value); 
	var nb = 1;
	var index = 0;
	if(res.index !== null){
		nb = (parseInt(res.nb)+1);
		index = res.index;
	}
	if(nb != 1)
		newSubtopics.splice(res.index,1);	
	
	newSubtopics.push({'name':$.trim(value),'nb':nb});
}
function removeNewSubtopics(value){
	var res = checkItemInArrayByValue(newSubtopics,value);
	var nb = 0;
	var index = 0;
	if(res.index !== null){
		index = res.index;
		nb = ( parseInt(res.nb) - 1 );
		newSubtopics.splice(index,1);	
		if(nb != 0)
			newSubtopics.push({'name':$.trim(value),'nb':nb});
	}
}

function checkItemInArrayByValue(array,val){
	
	for(var i=0;i<array.length;i++){
		
		if($.trim(array[i].name) === $.trim(val)){
			return {'index':i,'nb':array[i].nb};		
		}
	}
	return {'index':null,'nb':0};
}
function checkItemInArrayById(array,val){
	
	for(var i=0;i<array.length;i++){
		if($.trim(array[i].id) === $.trim(val)){
			return {'index':i,'nb':array[i].nb};		
		}
	}
	return {'index':null,'nb':0};
}

function checkItemInArrayByValue(array,val){
	
	for(var i=0;i<array.length;i++){
		if($.trim(array[i].name) === $.trim(val)){
			return {'index':i,'nb':array[i].nb};		
		}
	}
	return {'index':null,'nb':0};
}
function checkItemInArrayById(array,val){
	
	for(var i=0;i<array.length;i++){
		if($.trim(array[i].id) === $.trim(val)){
			return {'index':i,'nb':array[i].nb};		
		}
	}
	return {'index':null,'nb':0};
}

function new_checkinfoDate(data){
	
	var res = true;
	var currentTime = new Date();
	var curDate = currentTime.getDate();
	var curMonth = currentTime.getMonth();
	var curYear = currentTime.getFullYear();
	var curHours = currentTime.getHours();
	var curMins = currentTime.getMinutes();
	
	var arraydate = data[0].datesArray;
	var arrayhour= data[0].hoursArray;
	var arraymin = data[0].minsArray;
	
	for(var j=0;j<numArray.length;j++)
	{
		
		var date = arraydate[j].replace(/-/g,",");
		var dateObj = new Date(date);
		var month = (dateObj.getMonth());
		var date = dateObj.getDate();
		var year = dateObj.getFullYear();
		
		if(isNaN(date) || isNaN(year) || isNaN(month) ){
		
			document.getElementById('date'+numArray[j].id).className = 'planInputErrorStyle Date';		
			$("#ErrorDate"+numArray[j].id).show();
			return false;
		}
		else{
	
			if( ( year < curYear ) || ( year == curYear && month < curMonth ) || ( year == curYear && month == curMonth && date < curDate ) ){
				$("#ErrorDate"+numArray[j].id).show();
				res = false;
			}else if(year == curYear && month == curMonth && date == curDate){
		
				if( (curHours > arrayhour[j]) ){
			
						$("#ErrorDate"+numArray[j].id).show();				
						return false;
				}		
				else if (curHours == arrayhour[j] && curMins > arraymin[j]) {
						$("#ErrorDate"+numArray[j].id).show();		
						return false;	
				}	
			}
			$("#ErrorDate"+numArray[j].id).hide();	
		}
	}
	
	return true;
}

function searchInfoBypageSearch(){

	var typesearch='everything';
	var url="";
	var keyword=document.getElementById('keywordsearch').value;
	keyword=keyword.replace(/''/gi,'"');
	url="search.php?typesearch=everything&keyword="+keyword;
	document.location.href=url;
}
function showPopupConfirmDel(action){
	createPopupAjaxJquery("popups.php",{'popup':'confirmdelete','action':action},null,null);		
}

function showPopupVideoDemo(action){
	createPopupAjaxJquery("popups.php",{'popup':'videodemo','action':action},null,null);
}

function supprimerDoublonTableau(TabInit){

	var NvTab= new Array();
	var q=0;
	var LnChaine= TabInit.length;
 	for(var j=0;j<LnChaine;j++)
    {
	    for(i=0;i<LnChaine;i++)
	    {
	        if(TabInit[j]==  TabInit[i] && j!=i) TabInit[i]='faux';
	    }
	    if(TabInit[j]!='faux'){  NvTab[q] = TabInit[j]; q++}
    }
	return NvTab;

}

// COMPTE A REBOURS DANS agenda.php et past_session.php
function loadPrecSession(){
	
// var data = "action=timeprocsession";
// getDataValueJSON("sscripts/class_controler.php",data, reploadPrecSession);

	var data = {
			action:'timeprocsession'
		};
	
	ajaxJqueryPost("sscripts/class_controler.php",data,reploadPrecSession);    

}
function reploadPrecSession(repJson){
	
	var timeprecsession= repJson;
	
	timeprecsessionarray=timeprecsession.timeprecsessionarray;
	
	if(timeprecsessionarray!=null&&timeprecsessionarray!=""){
		
		StartCompteAReboursPublicSession();
		
	}

}
function StartCompteAReboursPublicSession()
{

	var datestart=timeprecsessionarray[0].datestart;
	var dateend=timeprecsessionarray[0].dateend;
	
	var DateStartCompteARebours=  new Date(datestart);
	var DateEndCompteARebours= new Date(dateend);
	
	if ((DateEndCompteARebours-DateStartCompteARebours>0)){
	
		var diffsec=(DateEndCompteARebours-DateStartCompteARebours)/1000;
		var n = 24 * 3600;
		var day= Math.floor (diffsec / n);
		var hour= Math.floor ((diffsec - (day * n)) / 3600);
		var min= Math.floor ((diffsec - ((day * n + hour * 3600))) / 60);
		var sec = Math.floor (diffsec - ((day * n + hour * 3600 + min * 60)));
	
		document.getElementById("compteurNextSession").innerHTML='';
		clearTimeout(compteurdate);
		CompteAReboursPublicSession(day,hour,min,sec,timeprecsessionarray);
		document.getElementById("compteurNextSession").style.display='block';
	}
	else
	{
		JoinNextSessionPublicIndex();
		document.getElementById("compteurNextSession").innerHTML='';
		document.getElementById("compteurNextSession").style.display='none';
		clearTimeout(compteurdate);
	}
	
}
function CompteAReboursPublicSession(day,hour,min,sec){
	
	sec--;
	if(sec==-1){
		sec=59;
		min--;
	}
	if(min==-1){
		min=59;
		hour--;
	}
	if(hour==-1){
		hour=23;
		day--;
	}
		
	if(day==-1){
		document.getElementById("compteurNextSession").style.display='none';
		JoinNextSessionPublicIndex();
	}
	else{
		document.getElementById("compteurNextSession").innerHTML="<span class='Text'>"+MLJS("txtNextClassStartsIn")+"</span><span class='Time'>"+day+"</span>"+MLJS("txtDay")+"<span class='Time'>"+hour+"</span>"+MLJS("txtHour")+"<span class='Time'>"+min+"</span> min <span class='Time'>"+sec+"</span> sec";
	
		if(day==0)
			document.getElementById("compteurNextSession").innerHTML="<span class='Text'>"+MLJS("txtNextClassStartsIn")+"</span><span class='Time'>"+hour+"</span>"+MLJS("txtHour")+"<span class='Time'>"+min+"</span> min <span class='Time'>"+sec+"</span> sec";
		if(day==0&&hour==0)
			document.getElementById("compteurNextSession").innerHTML="<span class='Text'>"+MLJS("txtNextClassStartsIn")+"</span><span class='Time'>"+min+"</span> min <span class='Time'>"+sec+"</span> sec";
	
		compteurdate= setTimeout("CompteAReboursPublicSession("+day+","+hour+","+min+","+sec+")",1000);
		
	}
}
function JoinNextSessionPublicIndex(){

	var templatedivjoinLiveClass=document.getElementById('templatedivjoinLiveClass').innerHTML;
	templatedivjoinLiveClass=repS(templatedivjoinLiveClass,"Price",timeprecsessionarray[0].price);
	templatedivjoinLiveClass=repS(templatedivjoinLiveClass,"Image",timeprecsessionarray[0].srcimagesession);
	templatedivjoinLiveClass=repS(templatedivjoinLiveClass,"Nbattendees",timeprecsessionarray[0].nbattendee);
	
	if (timeprecsessionarray[0].nbattendee<=1){
		templatedivjoinLiveClass=repS(templatedivjoinLiveClass,"Attendeestext",MLJS("txtAttendee"));
	} else {
		templatedivjoinLiveClass=repS(templatedivjoinLiveClass,"Attendeestext",MLJS("txtAttendees2"));
	}
	
	templatedivjoinLiveClass=repS(templatedivjoinLiveClass,"Pid",timeprecsessionarray[0].pid);
	templatedivjoinLiveClass=repS(templatedivjoinLiveClass,"Title",timeprecsessionarray[0].title);
	templatedivjoinLiveClass=repS(templatedivjoinLiveClass,"Rewriting",timeprecsessionarray[0].titlerewriting);
	
	document.getElementById('divjoinLiveClass').innerHTML=templatedivjoinLiveClass;
	document.getElementById("divjoinLiveClass").style.display='block';
	document.getElementById("checkoutClasses").style.display='none';
}
function disableBtnAddAttendeeEmail(){
	if(document.getElementById('tags_input')!='null'){
		var value =emailinvitee.getValues();
		
		if(value.length >0){
		
			if($("#btnAddInviteesEmail").hasClass('disabled'));
	      		$("#btnAddInviteesEmail").removeClass('disabled');
	  			
	  		}else{
	  			if(!$("#btnAddInviteesEmail").hasClass('disabled'));
	            	$("#btnAddInviteesEmail").addClass('disabled');
	  		}
	}
}
function CloseFancyBox(){
	$.fancybox.close();
}
// création des etoiles non changeables et création du overal rating
function CreateStarsNotChange(iddivstar,type,taille){
	if($("#"+iddivstar).length!=0){
		if(taille=='big'){
			$("#"+iddivstar).nochangestars({
		    	value:$('#score_'+iddivstar).val(),
		    	starClass: 'ui-stars-starbig',
		    	starOnClass: 'ui-stars-star-onpositivebig'
    
		    	
			});
		}else{
			if(type=='negative'){	
				$("#"+iddivstar).nochangestars({
		    	value:$('#score_'+iddivstar).val(),
		    	starOnClass: 'ui-stars-star-onnegative'
			});
			}
			else{
				$("#"+iddivstar).nochangestars({
		    	value:$('#score_'+iddivstar).val()
		    	
			});
			}
		}
	}
}

function onCloseFbConnectLastStep(){
	
	CloseFancyBox();

}
function onShowFbConnectPopupLastStep(){
	
	onloadPopupSignupComplete();	

}
function onValidFbConnectLastStep(){
	
	if(checkFormSignup()){
		
		var isok4newsletter = 0;
		var fbuid = $("#fbuid")[0].value;
		var firstname = $("#firstname_signup")[0].value;
		var lastname = $("#lastname_signup")[0].value;
		var email = $("#email_signup")[0].value;
		var password = $("#password_signup")[0].value;		
		if (document.getElementById('newsletter').checked){
			isok4newsletter = 1;
		}							
		var data = {
				action:'signup',
				id:fbuid,
				email:email,
				password:password,
				firstname:firstname,
				lastname:lastname,
				isok4newsletter:isok4newsletter				
		};
		ajaxJqueryPost("sscripts/fbconnect_controller.php",data,fbconnectLastStepComplete);				
		$("#btnCreateUser")[0].disabled = true;		
		showPopupLoading({'txt':''});
	
	}

}
function fbconnectLastStepComplete(repJson){
	
try{
		var result = repJson;
		if(result.result == 'ok'){
			
			window.location.reload();
		}
		else{
			alert('Oops there was a technical problem. Please try again.');
		}					
	}catch(err){
		alert('Oops there was a technical problem. Please try again.');
	}	

}
function showPopupFbConnectLastStep(action){

	createPopupAjaxJquery("popups.php",{'popup':'fbconnectlaststep','action':action},onShowFbConnectPopupLastStep,onCloseFbConnectLastStep);				
	
}
function checkFbBtMatch(fbuid,fbfirstname,fblastname){
  	
	var data = {
		action:'checkmatch',
		fbuid:fbuid,
		fbfirstname:fbfirstname,
		fblastname:fblastname			
	};
	ajaxJqueryPost("sscripts/fbconnect_controller.php",data,checkFbBtMatchComplete);				      	
	showPopupLoading({'txt':''});
}
function checkFbBtMatchComplete(repJson){

  	try{
		var result = repJson;
		if(result.result == 'match'){
			window.location.reload();	
		}
		else if(result.result == 'nomatch'){
				var id = result.fbuid;
				var firstname = result.fbfirstname;
				var lastname = result.fblastname;
				var action = {'params':{'id':id,'first_name':firstname,'last_name':lastname} };
				showPopupFbConnectLastStep(action);

			}
		else{
			alert('Oops there was a technical problem. Please try again.');
		}					
	}catch(err){
		alert('Oops there was a technical problem. Please try again.');		
	}	      	
  	
}
function showPopupLoading(action){
	
	createPopupAjaxJquery("popups.php",{'popup':'loading','action':action},null,CloseFancyBox);				
}
function fb_login() {
  
      FB.login(function(response) {

 		if (response.session) {
 			
			FB.api('/me', function(response) {
				if(response.id != undefined)
					checkFbBtMatch(response.id,response.first_name,response.last_name);
				else
					// FB.logout(function(response){});
					alert('Oops there was a technical problem. Please try again.');					
			}); 	 		

		}
	});
}  
