

// Fonction d'initialisation
window.onload = function() {

	var communeSelect = $('commune');
	if (communeSelect != undefined) {
		communeSelect.focus();
	}

	var loginForm = $('loginform');
	if (loginForm != undefined) {
		loginForm.setAttribute('autocomplete', 'off');
	}

	manageCityCombo();
	addOnSubmitHandler();
	if ($('password')) {
		$('password').value = '';
	}

	timeoutRefresh(TIMEOUT_DELAY);
};

// ============ Time out refresh ===============================================
var alarmID = null;
var countDownID = null;
var countDownCp = COUNTDOWN_START;
function timeoutRefresh(secondDelay) {
	if ($('timeout_alarm_div')) {
		alarmID = setTimeout(alertRefresh, secondDelay * 1000);
	}
}

function alertRefresh() {
	clearTimeout(alarmID);

	$('timeout_alarm_div').style.display = 'block';
	countDownID = setTimeout(countDown, 1000);
}

function countDown() {
	countDownCp--;

	if (countDownCp == 0) {
		$('countdown_span').innerHTML = 'maintenant';
		window.location = REFRESH_URL;
	} else {
		var str = 'dans <big>' + countDownCp + '</big> seconde';
		if (countDownCp > 1) {
			str += 's';
		}
		$('countdown_span').innerHTML = str;
		countDownID = setTimeout(countDown, 1000);
	}
}

// ============ Gestion des cookies ============================================
function setCookie (name, value, lifespan, access_path) {
      
  var cookietext = name + "=" + escape(value)  
    if (lifespan != null) {  
      var today=new Date()     
      var expiredate = new Date()      
      expiredate.setTime(today.getTime() + 1000*60*60*24*lifespan)
      cookietext += "; expires=" + expiredate.toGMTString()
    }
    if (access_path != null) { 
      cookietext += "; PATH="+access_path 
    }
   document.cookie = cookietext 
   return null  
}

function getCookie(Name) {
  var search = Name + "="                       
  var CookieString = document.cookie            
  var result = null                               
  if (CookieString.length > 0) {                
    offset = CookieString.indexOf(search)       
    if (offset != -1) {                         
      offset += search.length                   
      end = CookieString.indexOf(";", offset)   
      if (end == -1)                            
        end = CookieString.length               
      result = unescape(CookieString.substring(offset, end))         
                                                
      } 
    }
   return result                                
}



// ============ Gestion du formulaire d'identification =========================
var SCHOOLS = new Array();
var CITIES = new Array();
var DEBUG = false;

function reportFailure(request, obj) {
	if (DEBUG) {
		alert("An error occured: [" + obj + "]");
	}
}
function reportException(request, ex) {
	if (DEBUG) {
		alert("An exception occurred: [" + ex + "]");
	}
}

function manageCityCombo() {
	if ($('school') == undefined) {
		return;
	}

	var url = '/cas/loadSchoolAction';
	new Ajax.Request(url,
		{
			parameters: '',
			method: 'get',
			onComplete: fillCityCombo,
			onFailure: reportFailure,
			onException: reportException
		});
}

	function fillCityCombo(request) {

		// R?cup?re toutes les valeurs
		var dom = request.responseXML;
		if (dom == undefined) {
			alert('Erreur de réception du fichier XML des structures\nRechargez la page pour tenter de corriger l\'erreur.');
			return;
		}
		var etabs = dom.getElementsByTagName('etablissement');
		for (var i=0; i<etabs.length; i++) {
			var etab = etabs[i];
			var siren = etab.getAttribute('siren');
			var city = etab.getAttribute('ville');
			var name = etab.firstChild.nodeValue;
			
			if (SCHOOLS[city] == undefined) {
				SCHOOLS[city] = new Array();
				CITIES.push(city);
			}
			SCHOOLS[city].push(siren + '|' + name);
		}

		// Remplit la combo des villes
		var cityCombo = $('commune');
		emptyCombo(cityCombo);

		var previousSelectedCity = getCookie('authenticationCity') || DEFAULT_CITY;
		cityCombo.appendChild(createOption("Sélectionner une ville", "", false));
		for (var i=0; i<CITIES.length; i++) {
			cityCombo.appendChild(createOption(CITIES[i], CITIES[i], CITIES[i] == previousSelectedCity));
		}
		cityCombo.onchange = updateSchoolList;

		// Et met à jour la liste des établissements
		updateSchoolList();

		var previousSelectedSchool = getCookie('authenticationSchoolSiren') || DEFAULT_SIREN;
		if (previousSelectedSchool != null) {
			var schoolCombo = $('school');
			$A(schoolCombo.getElementsByTagName('option')).each(function(item) {
				if (item.value == previousSelectedSchool) {
					item.selected = 'selected';
				}
			});
		}
	}

	function updateSchoolList() {
		var cityid = $F('commune');

		if (cityid != '' && SCHOOLS[cityid] == undefined) {
			alert("Code de ville inconnu : " + cityid);
		}

		var schoolCombo = $('school');
		emptyCombo(schoolCombo);

		schoolCombo.appendChild(createOption("Sélectionner un établissement", "", false));

		if (cityid == '') {
			return;
		}

		for (var i=0; i<SCHOOLS[cityid].length; i++) {
			var school = SCHOOLS[cityid][i];

			var pidx = school.indexOf('|');
			var siren = school.substr(0,pidx);
			var schoolLabel = school.substr(pidx+1);

			schoolCombo.appendChild(createOption(schoolLabel, siren, false));
		}
	}

	function createOption(label, value, selected) {
		var opt = document.createElement("option");
		opt.value = value;
		opt.appendChild(document.createTextNode(label));
		if (selected) {
			opt.selected = 'selected';
			opt.defaultSelected = true;
		}
		return opt;
	}

	function emptyCombo(combo) {
		while (combo.length > 0) {
			combo.remove(0);
		}
	}

	function addOnSubmitHandler() {
		var form = $('loginform');
		if (form == undefined) {
			return;

		}
		
		form.onsubmit = function() {

			var codeCommune = $F('commune');
			var siren = $F('school');
			var shortLogin = $F('shortlogin');
			var password = $F('password');

			// Alertes
			if (codeCommune == '') {
				alert("Vous devez choisir une ville ou une localisation !");
				return false;
			}
			if (siren == '') {
				alert("Vous devez choisir un établissement !");
				return false;
			}
			if (shortLogin == '') {
				alert("Vous devez entrer votre identifiant !");
				return false;
			}
			if (password == '') {
				alert("Vous devez entrer votre mot de passe !");
				return false;
			}

			$('username').value = siren + shortLogin;
			setCookie('authenticationCity', codeCommune);
			setCookie('authenticationSchoolSiren', siren);
		}
	}

