function initApp() {

	/*On verifie l'existence d'une session*/
	checkSession();

	/*On récupère l’ancre qui est dans l’url et on retire le 1er caractère (le #)*/
	currentHash = document.location.hash.substring(1);
	
	/*Initialisation de l'historique*/
	initHistory();

	/*Cette fonction va vérifier si l’ancre en cours est différente de l’ancre dans l’URL
	Elle sera exécuter toutes les 0.1 secondes, si c’est le cas on appelle loadPage */
	window.setInterval(function () {
		checkUrl();
	},100)
	
}

function initHistory() {
	//Si l’ancre récupérer est différent de Null, on charge la page en y insérant l’ancre
	if (currentHash != "") {
		loadPage(currentHash,false);
	}
	else {
		loadPage('home',false);
	}
}

function checkUrl() {
	if (currentHash != document.location.hash.substring(1) ) {
		if (document.location.hash != "") {
			loadPage(document.location.hash.substring(1),false);
		}
		else {
			loadPage('home', false);
		}
	}
}

function init() {
jQuery.ajaxSetup ( {
'beforeSend' : function(xhr) {
if(window.ActiveXObject){
return;
}
else{
xhr.overrideMimeType('text/html; charset=ISO-8859-1');
}
}
});
}

function checkSession(){
$.ajax({
  type: "GET",
  url: "php/checkSession.php",
  cache: false,
  complete: function(data){
    var xml = data.responseText;
    var valid;
    var login;
    if ($.browser.msie) {  
	    var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");  
		xmlDoc.loadXML(xml);  
		xml = xmlDoc;
	}
    valid = $(xml).find('valid').text();
    //valid = $('valid', xml).text();
    if(valid == 'true'){
        login = $(xml).find('login').text();
        rank = $(xml).find('rank').text();
        if(rank == 'admin'){
            $("#memberArea").html('<li><a href="page/getMemberList.php" onclick="loadPage(\'getMemberList\', true); return false;">Gestion des membres</a></li><li><a href="page/modifierPage.php" onclick="loadPage(\'modifierPage\', true); return false;">Gestion des fichiers</a></li><li><a href="page/photos.php" onclick="loadPage(\'photos\', true); return false;">Galerie photos</a></li><li><a href="#" onclick="closeSession(); return false;">Fermer la session</a></li>');
        }
        else{
            $("#memberArea").html('<li><a href="page/photos.php" onclick="loadPage(\'photos\', true); return false;">Galerie photos</a></li><li><a href="#" onclick="closeSession(); return false;">Fermer la session</a></li>');
        }
        //loadPage('home');
    }
    else{
        
    }
   }
});
}

function closeSession(){
$.ajax({
  type: "GET",
  url: "php/closeSession.php",
  cache: false,
  success: function(html){
    loadPage('home', true);
    $("#memberArea").html('<li><a href="page/authentification.php" onclick="loadPage(\'authentification\', true); return false;">Se connecter</a></li><li><a href="page/inscription.php" onclick="loadPage(\'inscription\', true); return false;">Inscription</a></li>');
  }
});
}

function updateUrl(pageName, changeHash) {
	pageName = pageName.replace("page=", '');
	currentHash = "page=" + pageName;
	document.location.hash = "page=" + pageName;
	/*if (changeHash){
		document.location.hash = "page=" + pageName;	
	}*/
	return pageName;
}

function loadPage(pageName, changeHash){

pageName = updateUrl(pageName, changeHash);

$.ajax({
  type: "GET",
  url: "page/" + pageName + ".php",
  cache: false,
  success: function(html){
    $("#page").hide("fast").show("slow").html(html); 
  }
});
}

function sendEmail(name, email, object, message){
$.ajax({
  type: "POST",
  url: "php/mail.php",
  data: "name=" + name + "&email=" + email + "&object=" + object + "&message=" + message,
  cache: false,
  success: function(data){
    alert(data); 
  }
});
}

function authentification(login, password){
$.ajax({
  type: "POST",
  url: "php/authentification.php",
  data: "login=" + login + "&password=" + password,
  cache: false,
  complete: function(data){
    var xml = data.responseText;
    var valid;
    var login;
    if ($.browser.msie) {  
	    var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");  
		xmlDoc.loadXML(xml);  
		xml = xmlDoc;
	}
    valid = $(xml).find('valid').text();
    //valid = $('valid', xml).text();
    if(valid == 'true'){
        login = $(xml).find('login').text();
        rank = $(xml).find('rank').text();
        activation = $(xml).find('activation').text();
        if(activation == '1'){
            if(rank == 'admin'){
                $("#memberArea").html('<li><a href="page/getMemberList.php" onclick="loadPage(\'getMemberList\', true); return false;">Gestion des membres</a></li><li><a href="#" onclick="loadPage(\'modifierPage\', true); return false;">Gestion des fichiers</a></li><li><a href="page/photos.php" onclick="loadPage(\'photos\', true); return false;">Galerie photos</a></li><li><a href="#" onclick="closeSession(); return false;">Fermer la session</a></li>');
            }
            else{
                $("#memberArea").html('<li><a href="page/photos.php" onclick="loadPage(\'photos\', true); return false;">Galerie photos</a></li><li><a href="#" onclick="closeSession(); return false;">Fermer la session</a></li>');
            }
            loadPage('home', true);
        }
        else{
            alert("Votre compte utilisateur n'est pas encore activé.");
        }
    }
    else{
        alert("Les données saisies sont incorrectes");    
    }
   }
});
}

function subscription(name, firstName, email, login, password, password2){
$.ajax({
  type: "POST",
  url: "php/subscription.php",
  data: "name=" + name + "&firstName=" + firstName + "&login=" + login + "&password=" + password + "&password2=" + password2 + "&email=" + email,
  cache: false,
  success: function(data){
    alert(data);
    loadPage('home', true);
  }
});
}

function getFileList(path, directory){
$.ajax({
  type: "GET",
  url: "php/getFileList.php",
  data: "path=" + path + "&directory=" + directory,
  cache: false,
  success: function(data){
    $("#result").html(data);
  }
});
}

function modifyFile(filePath){
var exts = ["js","xml","html","php","css"];
var fileExt = filePath.substring(filePath.lastIndexOf(".") + 1);
if (jQuery.inArray(fileExt, exts) != -1){
	$.ajax({
  		type: "GET",
 		url: "php/modifyFile.php",
  		cache: false,
  		data: "filePath=" + filePath,
  		success: function(data){
    		$("#fileContent").html(data);
  		}
	});
}
}

function saveFile(filePath, content){
$.ajax({
  type: "POST",
  url: "php/saveFile.php",
  cache: false,
  data: "filePath=" + filePath + "&content=" + content,
  success: function(data){
    loadPage('home', true);
  }
});
}

function showContent(content){
if ($("#" + content).is(":hidden")){
    $("#"+ content).slideDown("slow");
}
else{
    $("#" + content).slideUp("slow");
}
                     
}

function showMember(id){
$.ajax({
  type: "GET",
  url: "php/showMember.php",
  cache: false,
  data: "id=" + id,
  success: function(data){
    $("#result").html(data);
  }
});
}

function updateMember(id, name, firstName, login, password, email, type, state){
$.ajax({
  type: "POST",
  url: "php/updateMember.php",
  cache: false,
  data: "id=" + id + "&name=" + name + "&firstName=" + firstName + "&login=" + login + "&password=" + password + "&email=" + email + "&type=" + type + "&state=" + state,
  success: function(data){
    alert(data);
	loadPage('home', true);	
  }
});
}

function deleteMember(id){
	if (confirm("Voulez-vous supprimer ce membre ?")) {
		$.ajax({
  			type: "POST",
  			url: "php/deleteMember.php",
  			cache: false,
  			data: "id=" + id,
  			success: function(data){
    			alert(data);
				loadPage('home', true);	
  			}
		});
	}
}
            
function closeForm(){
    $("#messageSent").show("slow");
    setTimeout('$("#messageSent").hide();$("#informations").slideUp("slow")', 2000);
}

function refreshSelect(url, selectId){

	var value = document.getElementById(selectId).value;
	//try with Mozilla, opera, etc. 
	if (window.XMLHttpRequest){
    	req = new XMLHttpRequest();
	}
    //else IE
    else if (window.ActiveXObject){
        req = new ActiveXObject("Microsoft.XMLHTTP");
    }
	req.onreadystatechange = callbackSelect;
    req.open("POST",url,true);
    req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    req.send("value=" + value);
}

function callbackSelect(){
    var div = document.getElementById('searchResult');
	if (req.readyState!=4){
		div.innerHTML = 'chargement en cours...'
	}
    if (req.readyState==4){
        if (req.status == 200){
            //it works:
            div.innerHTML = req.responseText;
            bindThickBoxEvents();
        }
        else{
            //problem:
            div.innerHTML = "refresh failed";
        }
    } 
}

function removeThickBoxEvents() {
    $('.thickbox').each(function(i) {
        $(this).unbind('click');
    });
}

function bindThickBoxEvents() {
    removeThickBoxEvents();
    tb_init('a.thickbox, area.thickbox, input.thickbox');
}

