function stripSlashes(str){
	return str.replace(/\\/g, '');
}


function fOpenWinBis(url,width,height){
	myScreenHeight=(window.screen.availHeight-height)/2;
	myScreenWidth=(window.screen.availWidth-width)/2;
	newWindow=window.open(url,"subWind", "HEIGHT="+height+",WIDTH="+width+",menubar=no,toolbar=no,titlebar=yes,TOP="+myScreenHeight+",LEFT="+myScreenWidth+",scrollbars=yes");
	newWindow.focus();
}

function checkAnswers(){
	var vj=1;
	var quizCount=0;
	var score=0;
	while(typeof(radioGrp=eval("document.forms['quizform'].quiz"+vj++))!="undefined"){
		var correctAnswer=-1;
		var answer=-1;
		for(var vi=0;vi < radioGrp.length;vi++){
			if (radioGrp[vi].checked){
				var answer=radioGrp[vi].value;
			}
			else if ((typeof(radioGrp[vi].type)!=undefined) && (radioGrp[vi].type=="hidden")){
					var correctAnswer=radioGrp[vi].value;
				 }
		}
		quizCount++;
		if(answer===correctAnswer) {
			score++;
			showAnswer(quizCount,answer);		
		}
	}
	alert('Your score is : '+score +'/' +  quizCount);
	fSendAnswers(score,quizCount,document.forms['quizform'].article.value);
}

function showAnswer(quizId, answerId){
	var obj=eval("document.all['quiz"+quizId+'-'+answerId+"']");
	obj.style.background="#00FF00";
	obj.style.color="#FFFFFF";
	obj.innerHTML=obj.innerHTML + ' <b>Correct answer</b>';
}

function fGetXObject(){
	 try {
   		xhr = new ActiveXObject("Microsoft.XMLHTTP");    // essayer Internet Explorer 
	}
	catch(e)   // Echec
	{
  		xhr = new XMLHttpRequest()
	}
	return xhr
}

function fSendAnswers(score,fullScore,article){
	var xhr=fGetXObject();
	// On défini ce qu'on va faire quand on aura la réponse
	xhr.onreadystatechange = function(){
		if(xhr.readyState == 4 && xhr.status == 200){
			//alert(xhr.responseText);
			fGetProgress();
		}
	}
	
	xhr.open("GET","progress_board.php?score="+score+'&fullScore='+fullScore+'&id='+article+'&action=update',true);
	xhr.send(null);
}

function fSaveProgress(article){
	 fSendAnswers(1,1,article);
}

function saveRank(){
	var xhr=fGetXObject();
	xhr.onreadystatechange = function(){
		if(xhr.readyState  == 4)
    	{ if(xhr.status  == 200) alert(xhr.responseText); }
	}
	xhr.open("POST","squelettes/saveArticle.php",true);
	xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");   
	xhr.send("idArticle="+document.getElementById('slideID').value+"&rank="+document.getElementById('slide_rank').value+"&action=rank");
}


function fGetProgress(){
	var xhrProgress=fGetXObject();
	// On défini ce qu'on va faire quand on aura la réponse
	xhrProgress.onreadystatechange = function(){
		if(xhrProgress.readyState == 4 && xhrProgress.status == 200){
			json=xhrProgress.responseText;
			progressObj = null;
			progressObj = eval( '(' + json + ')' ); 

			document.getElementById('inboxCount').innerHTML=progressObj.inbox;
			
			document.getElementById('progress_bar').innerHTML=Math.round(progressObj.slideprogress)+'%';
			document.getElementById('progress_bar').style.width=Math.round(progressObj.slideprogress*700/100);

			document.getElementById('test_progress_bar').innerHTML=Math.round(progressObj.score*100/progressObj.fullscore)+'%';
			document.getElementById('test_progress_bar').style.width=Math.round(progressObj.score*100/progressObj.fullscore*700/100);

		}
	}
	xhrProgress.open("GET","progress_board.php?action=refresh",true);
	xhrProgress.send(null);
	
}

function fGetInboxCount(){
	var xhrProgress=fGetXObject();
	// On défini ce qu'on va faire quand on aura la réponse
	xhrProgress.onreadystatechange = function(){
		if(xhrProgress.readyState == 4 && xhrProgress.status == 200){
			json=xhrProgress.responseText;
			progressObj = null;
			progressObj = eval( '(' + json + ')' ); 
			document.getElementById('inboxCount').innerHTML=progressObj.inbox;
		}
	}
	xhrProgress.open("GET","progress_board.php?action=refresh",true);
	xhrProgress.send(null);
}


function deleteSlide(id){
	if (confirm("Are you sure you want to delete the current slide and/or review?")) {
		var xhr=fGetXObject();
		xhr.onreadystatechange = function(){
			// On ne fait quelque chose que si on a tout reçu et que le if(xhr.readyState == 4 && xhr.status == 200){
			if(xhr.readyState  == 4)
       	  {
       	       if(xhr.status  == 200) 
       	          alert(xhr.responseText); 
       	  }
		}
		xhr.open("POST","squelettes/saveArticle.php",true);
		xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");   
		xhr.send("idArticle="+id+"&action=delete");
	}
}

function openAttachment(id){
	window.open('squelettes/add-doc.php?idArticle='+id,'_blank','toolbar=0, location=0, directories=0, status=1, scrollbars=0, resizable=1, copyhistory=0, menuBar=0, width=300, height=300');
	return;
}


function openSlideEditor(id){
	window.open('squelettes/slideEditor.php?idArticle='+id,'_blank','toolbar=0, location=0, directories=0, status=1, scrollbars=0, resizable=1, copyhistory=0, menuBar=0, width=750, height=700');
	return;
}

function createNewSlide(id_rubrique){
	window.open('squelettes/slideEditor.php?idRubrique='+id_rubrique,'_blank','toolbar=0, location=0, directories=0, status=1, scrollbars=0, resizable=1, copyhistory=0, menuBar=0, width=750, height=700');
	return;
}

function moveUp(id,id2move){
	if((id2move!=null) && (id2move!=-1)){	
		var xhr=fGetXObject();
		xhr.onreadystatechange = function(){
			// On ne fait quelque chose que si on a tout reçu et que le if(xhr.readyState == 4 && xhr.status == 200){
			if(xhr.readyState  == 4)
       	  {
       	       if(xhr.status  == 200) 
       	          alert(xhr.responseText); 
       	  }
		}
		xhr.open("POST","squelettes/saveArticle.php",true);
		xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");   
		xhr.send("idArticle="+id+"&action=moveup"+"&id2move="+id2move);
	}
	else alert("Can't move up this slide!");
}

function moveDown(id,id2move){
	if((id2move!=null) && (id2move!=-1)){	
		var xhr=fGetXObject();
		xhr.onreadystatechange = function(){
			// On ne fait quelque chose que si on a tout reçu et que le if(xhr.readyState == 4 && xhr.status == 200){
			if(xhr.readyState  == 4)
       	  {
       	       if(xhr.status  == 200) 
       	          alert(xhr.responseText); 
       	  }
		}
		xhr.open("POST","squelettes/saveArticle.php",true);
		xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");   
		xhr.send("idArticle="+id+"&action=moveup"+"&id2move="+id2move);
	}
	else alert("Can't move up this slide!");
}


function fHide(object){
	myObj=document.getElementById(object);
	if (myObj.style.height=='40px'){
		myObj.style.height='';
	}
	else myObj.style.height='40px';
}

/*
	Calendar functions
*/
function fRefreshCalendar(calendar_date){
	var xhrCalendar=fGetXObject();
	xhrCalendar.onreadystatechange = function(){
		if(xhrCalendar.readyState == 4 && xhrCalendar.status == 200){
			document.getElementById('calendar').innerHTML=xhrCalendar.responseText;
		}
	}
	if(calendar_date!=null){
		xhrCalendar.open("GET","squelettes/calendar.php?myaction=getcalendar&level="+document.getElementById('level').value +"&calendar_date="+calendar_date,true);
	}
	else xhrCalendar.open("GET","squelettes/calendar.php?myaction=getcalendar&level="+document.getElementById('level').value,true);
	xhrCalendar.send(null);
	document.getElementById('calendar').innerHTML='<h2>Loading...</h2>';
}

function addCalendarEvent(){
	window.open('squelettes/add-event.php','_blank','toolbar=0, location=0, directories=0, status=1, scrollbars=0, resizable=1, copyhistory=0, menuBar=0, width=300, height=220');
	return;
}

function addAnnoucement(){
	window.open('squelettes/add-annoucement.php','_blank','toolbar=0, location=0, directories=0, status=1, scrollbars=0, resizable=1, copyhistory=0, menuBar=0, width=500, height=580');
	return;
}


function updateEvent(id){
	window.open('squelettes/add-event.php?id='+id,'_blank','toolbar=0, location=0, directories=0, status=1, scrollbars=0, resizable=1, copyhistory=0, menuBar=0, width=300, height=220');
	return;
}

function fGetEvents(date){
	var xhr=fGetXObject();
	// On défini ce qu'on va faire quand on aura la réponse
	xhr.onreadystatechange = function(){
		if(xhr.readyState == 4 && xhr.status == 200){
			output='';
			jsonObj = null;
			jsonObj = eval( '(' + xhr.responseText + ')' ); 
			for(vi=0;vi<jsonObj.events.length;vi++){
				myevent=jsonObj.events[vi];
				output+='<div align="left">';
				output+='<a href="#" onclick="fDelEvent('+ myevent.id +')"><img src="squelettes/images/del_event.gif" align="absmiddle"/></a> ';
				output+='<a href="#" onclick="updateEvent('+ myevent.id +')">'+ myevent.description +'</a></div>';
				
			}
			document.getElementById('events').innerHTML=output;
		}
	}
	xhr.open("GET","squelettes/calendar.php?myaction=getevents&date="+date+"&level="+document.getElementById('level').value,true);
	xhr.send(null);
	document.getElementById('events').innerHTML='<h2>Loading...</h2>';
}

function fDelEvent(id){
	var xhr=fGetXObject();
	xhr.onreadystatechange = function(){
		if(xhr.readyState == 4 && xhr.status == 200){
			output='';
			jsonObj = null;
			jsonObj = eval( '(' + xhr.responseText + ')' ); 
			for(vi=0;vi<jsonObj.events.length;vi++){
				myevent=jsonObj.events[vi];
				output+='<div align="left">';
				output+='<a  href="#" onclick="fDelEvent('+ myevent.id +')"><img src="squelettes/images/del_event.gif" align="absmiddle"/></a> ';
				output+='<a href="#" onclick="updateEvent('+ myevent.id +')">'+ myevent.description +'</a></div>';
				
			}
			document.getElementById('events').innerHTML=output;
		}
	}
	xhr.open("GET","squelettes/calendar.php?myaction=delevent&id="+id+"&level="+document.getElementById('level').value,true);
	xhr.send(null);
}

function fDelDoc(id_article, id_document){
	var xhr=fGetXObject();
	xhr.onreadystatechange = function(){
		if(xhr.readyState == 4 && xhr.status == 200){
			json=xhr.responseText;
			jsonObj = null;
			jsonObj = eval( '(' + json + ')' ); 
				
			if (jsonObj.result==true){
				alert('Attached file successfully erased!');
				output='<table cellpadding="0" cellspacing="0" width="98%" border="1">';
				output+='<tr><th>&nbsp;</th><th>Title</th><th>Description</th><th>Size Kb</th></tr>';
	
				for(vi=0;vi<jsonObj.documents.length;vi++){
					doc=jsonObj.documents[vi];
					output+='<tr><td width="70"><a href="'+ doc.fichier +'" target="_blank"><img src="/squelettes/images/download_doc.gif"/></a>';
					output+='<a href="#" onclick="fDelDoc(\''+ doc.id_article + '\',\'' + doc.id_document +'\')"><img src="/squelettes/images/del_doc.gif"/></a></td>';
					output+='<td width="200"><h2>'+ doc.titre + ' </h2></td><td>' + doc.descriptif +  ' </td><td width="80">' + doc.taille+'</td></tr>';
				}
				output+='</table>';
				if(jsonObj.documents.length>0){
					document.getElementById('slide-docs').innerHTML=output;
				}
				else document.getElementById('slide-docs').innerHTML='';	
			}
			else alert('Unable to erase the file');
		}
	}
	xhr.open("GET","squelettes/slide.php?myaction=deldoc&id_article="+id_article+"&id_document="+id_document,true);
	xhr.send(null);
}

function fRefreshDocList(id_article){
	var xhr=fGetXObject();
	xhr.onreadystatechange = function(){
		if(xhr.readyState == 4 && xhr.status == 200){
			json=xhr.responseText;
			jsonObj = null;
			jsonObj = eval( '(' + json + ')' ); 
				
			if (jsonObj.result==true){
				output='<table cellpadding="0" cellspacing="0" width="98%" border="1">';
				output+='<tr><th>&nbsp;</th><th>Title</th><th>Description</th><th>Size Kb</th></tr>';
	
				for(vi=0;vi<jsonObj.documents.length;vi++){
					doc=jsonObj.documents[vi];
					output+='<tr><td width="70"><a href="'+ doc.fichier +'" target="_blank"><img src="/squelettes/images/download_doc.gif"/></a>';
					output+='<a href="#" onclick="fDelDoc(\''+ doc.id_article + '\',\'' + doc.id_document +'\')"><img src="/squelettes/images/del_doc.gif"/></a></td>';
					output+='<td width="200"><h2>'+ doc.titre + ' </h2></td><td>' + doc.descriptif +  ' </td><td width="80">' + doc.taille+'</td></tr>';
				}
				output+='</table>';
				if(jsonObj.documents.length>0){
					document.getElementById('slide-docs').innerHTML=output;
				}
				else document.getElementById('slide-docs').innerHTML='';	
			}
			else alert('Unable to refresh attached documents list');
		}
	}
	xhr.open("GET","squelettes/slide.php?myaction=refreshdocs&id_article="+id_article,true);
	xhr.send(null);
}


function fOpenInIframe(url){
	if(document.getElementById('slideBar')!=null) document.getElementById('slideBar').style.display='none';
	if(document.getElementById('presentation')!=null) document.getElementById('presentation').style.display='none';
	if(document.getElementById('adminbar')!=null) document.getElementById('adminbar').style.display='none';
	
	iframebox=document.getElementById('iframe');
	iframebox.style.display='block';
	iframebox.innerHTML='<iframe name="myiframe" id="myiframe" src="'+url+'" style="border:0px;width:100%;height:1024px;padding:0px;margin:0px;"></iframe>';
}


function fGetSlide(cid, id){
	document.getElementById('slide-title').innerHTML='<strong>Loading...</strong>';
	var xhrSlide=fGetXObject();
	// On défini ce qu'on va faire quand on aura la réponse
	xhrSlide.onreadystatechange = function(){
		if(xhrSlide.readyState == 4 && xhrSlide.status == 200){
			document.getElementById('slideBox').style.visibility='visible';
			json=xhrSlide.responseText;
			in_list = null;
			in_list = eval( '(' + json + ')' ); 
			
			document.getElementById('slideBar').style.display='block';
			document.getElementById('presentation').style.display='block';
			document.getElementById('adminbar').style.display='block';
			document.getElementById('iframe').style.display='none';
			
			document.getElementById('adminbar').innerHTML=in_list.adminbar;
			document.getElementById('navbar').innerHTML=in_list.navbar;
			document.getElementById('module-title').innerHTML=in_list.module;
			document.getElementById('section-title').innerHTML=in_list.section;
			
			document.getElementById('slide-title').innerHTML=in_list.title;
			document.getElementById('slide-content').innerHTML=in_list.content;

			output='<table cellpadding="0" cellspacing="0" width="98%" border="1">';
			output+='<tr><th>&nbsp;</th><th>Title</th><th>Description</th><th>Size Kb</th></tr>';
	
			for(vi=0;vi<in_list.documents.length;vi++){
				doc=in_list.documents[vi];
				output+='<tr><td width="70"><a href="'+ doc.fichier +'" target="_blank"><img src="/squelettes/images/download_doc.gif"/></a>';
				output+='<a href="#" onclick="fDelDoc(\''+ doc.id_article + '\',\'' + doc.id_document +'\')"><img src="/squelettes/images/del_doc.gif"/></a></td>';
				output+='<td width="200"><h2>'+ doc.titre + ' </h2></td><td>' + doc.descriptif +  ' </td><td width="80">' + doc.taille+'</td></tr>';
			}
			output+='</table>';
			if(in_list.documents.length>0){
				document.getElementById('slide-docs').innerHTML=output;
			}
			else document.getElementById('slide-docs').innerHTML='';
			if (in_list.slidetype=='slide')	fSaveProgress(id);
			
		}
	}
	xhrSlide.open("GET","squelettes/slide.php?id="+id,true);
	xhrSlide.send(null);
}


/* Fonction necessaire pour l'execution du carousel */ 
function mycarousel_itemLoadCallback(carousel, state)
{
    // Check if the requested items already exist
    if (carousel.has(carousel.first, carousel.last)) {
        return;
    }

    jQuery.get(
        'squelettes/annoucement.php?action=get',
        {
            first: carousel.first,
            last: carousel.last
        },
        function(xml) {
            mycarousel_itemAddCallback(carousel, carousel.first, carousel.last, xml);
        },
		'xml'
    );
};

function mycarousel_itemAddCallback(carousel, first, last, xml)
{
    // Set the size of the carousel
    carousel.size(parseInt(jQuery('total', xml).text()));

    jQuery('item', xml).each(function(i) {
        carousel.add(first + i, mycarousel_getItemHTML(jQuery(this).text()));
    });
};

/**
 * Item html creation helper.
 */
function mycarousel_getItemHTML(url)
{
	var reg=new RegExp(";", "g");
	var tableau=url.split(reg);
	result='<li style="width:200px;">';
	result+='<p style="margin-bottom:0px;text-align:left;">';
	
	if (tableau[0]=='delete'){
		result+='<a href="#" onclick="fDelAnnoucement(\''+ tableau[1] +'\');"><img src="squelettes/images/del_event.gif" align="absmiddle"></img></a>';
	}
	
	result+='<img src="squelettes/images/news_ico.gif" align="absmiddle"></img><label style="text-style:bold;">'+tableau[2]+'</label><br/><small>'+ tableau[3]+'</small></p>';
	result+='<p style="font-size:0.9em;margin:5px;font-weight:bold;text-align:left;">'+ stripSlashes(tableau[4]) +'</p>';
	result+='<p style="font-size:0.9em;margin:5px;font-weight:bold;text-align:right;">Written by '+ stripSlashes(tableau[5]) +'</p>';
	result+='<p style="text-align:right;margin-top:0px;"><a href="javascript:fOpenWinBis(\'?breve'+ tableau[1] +'\',500,400)">Learn more</a></p>';
	result+='</li>';
	return(result);
};


/* Fin fonction necessaire pour l'execution du carousel */  
 

function fDelAnnoucement(id){
	if (confirm("Are you sure you want to delete this news item?")) {
		xhrNews=fGetXObject();
		xhrNews.onreadystatechange = function(){
			if((xhrNews.readyState  == 4)	&& (xhrNews.status  == 200)) {
				alert(xhrNews.responseText + '\n Please hit F5 to refresh the page');
			}
		}

		xhrNews.open("POST",'squelettes/annoucement.php?action=del',true);
		xhrNews.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");   
		xhrNews.send("id="+id);
		return(false);
	}
 }

function fInitPage(){
	jQuery(document).ready(function() {
    jQuery('#mycarousel').jcarousel({
        // Uncomment the following option if you want items
        // which are outside the visible range to be removed
        // from the DOM.
        // Useful for carousels with MANY items.
        //itemVisibleOutCallback: {onAfterAnimation: function(carousel, item, i, state, evt) { carousel.remove(i); }},
		vertical: true,
        scroll: 2 ,
        itemLoadCallback: mycarousel_itemLoadCallback
    });
	}); 
	fRefreshCalendar();
	fGetSlide(-1,'first');
}
