//Global vars

var check_loc= /^([0-9]{1,4}|)$/;
var check_number = /^[0-9]{1,4}$/;
var not_null_spaced_alphastring = /^[A-Z0-9.\-_ ]+$/i;
var not_null_path_string = /^[A-Z0-9\/.\-_@ ]+$/i;

var bad_string = "Immettere una stringa valida";
var bad_email = "L'indirizzo email non e' corretto";
var bad_region = "Devi selezionare la Regione";
var bad_province = "Devi selezionare la Provincia";
var bad_commune = "Devi selezionare il Comune";
var bad_loc = "Le coordinate inserite non sono esatte";
var bad_loc_coor = "Latitudine e Longitudine inserite non sono esatte";
var bad_observatory = "Devi selezionare il Luogo di Osservazione";
var bad_floor = "Devi selezionare il Piano a cui ti trovavi";
var bad_date = "La data del terremoto non e' corretta";
var bad_earthquake = "Devi selezionare il terremoto";

function init(form){
	//Hide alert
	$('alert').style.display = "none";

	//Show questionnaire
	$('content').style.display = "block";

	var module = $(form);
	if(undefined != module){ //If we are in Quest|Stat|List Page
		//Lock not present earthquake (manual)
		if(undefined != $('dd') && undefined == $('start')){ //If we are in Quest page
			module.dd.disabled = true;
			module.mm.disabled = true;
			module.yyyy.disabled = true;
			module.hh.disabled = true;
			module.nn.disabled = true;
		}
	}
}

function lock_place(form){	
	var module = document.getElementById(form);
	var place = module.obs_place.value;
	
	switch(place){
		case "100":
			module.street.disabled = false;
			module.home_num.disabled = false;
			module.floor.disabled = false;
			module.tot_floors.disabled = false;
			module.description.disabled = false;
			break;
		case "-99":
			module.street.disabled = false;
			module.home_num.disabled = false;
			module.floor.disabled = false;
			module.tot_floors.disabled = false;
			module.description.disabled = true;
			break;
		case "0":
			module.street.disabled = false;
			module.home_num.disabled = false;
			module.floor.disabled = true;
			module.tot_floors.disabled = true;
			module.description.disabled = true;
			break;
		case "1":
			module.street.disabled = true;
			module.home_num.disabled = true;
			module.floor.disabled = true;
			module.tot_floors.disabled = true;
			module.description.disabled = false;
			break;
		default:
			alert("Caso non contemplato");
			break;
	}
}

function lock_manual_earthquake(form, source){
	var module = document.getElementById(form);
	var manual_add = document.getElementById("manual_add");
	var list_add = document.getElementById("list_add");

	var NOT_IN_LIST = 0;
	var NULL_EVENT = "-1";

	var quake_ref = module.id_quake;

	switch(source){
		case 'l': //By LIST-Radio button
			quake_ref.value = NULL_EVENT;
			break;
		case 'm': //By MANUAL-Radio button
			quake_ref.value = NOT_IN_LIST;
			break;
		case 's': //By selecting quake
			if(0 == quake_ref.value){
				manual_add.checked = true;
			}
			else{
				list_add.checked = true;
			}
			break;
	}

	quake = quake_ref.value;

	switch(quake){
		case "0":
			module.dd.disabled = false;
			module.mm.disabled = false;
			module.yyyy.disabled = false;
			module.hh.disabled = false;
			module.nn.disabled = false;
			break;
		default:
			module.dd.disabled = true;
			module.mm.disabled = true;
			module.yyyy.disabled = true;
			module.hh.disabled = true;
			module.nn.disabled = true;
			break;
	}
}

function lock_acustic(form){
	var module = document.getElementById(form);
	var acustic = module.acous_effect.value;

	switch(acustic){
		case "202":
			module.when_acous.disabled = true;
			module.where_acous.disabled = true;
			break;
		default:
			module.when_acous.disabled = false;
			module.where_acous.disabled = false;
			break;		
	}
}

function lock_quest(form){
	var module = document.getElementById(form);
	var lock = $('adverted').checked;

	var to_hide = [ "happen", "damage", "describe_experience", "damage_title" ];
	var hide_len = to_hide.length;

	for (i = 0; i< hide_len; i++){
		elem = to_hide[i];
		$(elem).style.display = (true == lock) ? 'none' : 'block';
	}
}

function check_stat(module){
	return true;
}

function check_syntax(module, checks){
	len = checks.length;
	
	for (i = 0; i < len; i++){
		var item = checks[i];
		var value = document.getElementById(item[0]).value;
		
		if (null == value.match(item[1])){
			alert(item[2]);
			return false;
		}
	}

	return true;
}

function check_value(module, checks){
	var len = checks.length;
	var num_radix = 10;

	for (i = 0; i < len; i++){
		var item = checks[i];
		var str_value = document.getElementById(item[0]).value;
		var int_value = parseInt(str_value, num_radix);

		if(null == str_value.match(item[1])){
			return false;
		}

		if(item[2] > int_value || item[3] < int_value){
			return false;
		}
	}

	return true;
}

function check_date(module){
	var to_check = new Array();

	//array: field, reg_exp, min_value, max_value
	to_check = [	["dd",		check_number, 1, 31 ],
			["mm",		check_number, 1, 12 ],
			["yyyy",	check_number, 1970, 2050 ],
			["hh",		check_number, 0, 23 ],
			["nn",		check_number, 0, 59 ] ];

	if(false == check_value(module, to_check)){
		return false;
	}

	var months_len = new Array(31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);

	var day = parseInt(document.getElementById("dd").value);
	var month = parseInt(document.getElementById("mm").value);
	var year = parseInt(document.getElementById("yyyy").value);

	//If day if 0< o >max_days_for_month ERROR...
	if(0 > day || day > months_len[month-1]){
		return false;
	}

	if(2 == month){ //February
		var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
		if (29 == day && !isleap) {
			return false;
		}
	}

	return true;
}

function check_floor(field_floor, field_tot_floor){

	//if we are out we don't have a floor :-)
	if(true == field_floor.disabled && true == field_tot_floor.disabled)
		return true;

	var floor = parseInt(field_floor.value);
	var tot_floor = parseInt(field_tot_floor.value);

	var NO_FLOOR = 500;
	var BASE_FLOOR = 501;
	var FLOOR_1_2 = 502;
	var FLOOR_3_4 = 503;
	var FLOOR_5_6 = 504;
	var FLOOR_7 = 505;
	
	var NO_TOT_FLOOR = 510;
	var TOT_FLOOR_1_2 = 511;
	var TOT_FLOOR_3_5 = 512;
	var TOT_FLOOR_6_10 = 513;
	var TOT_FLOOR_11 = 514;

	var res = false;

	switch(floor){
		case NO_FLOOR: //No floor set
		case BASE_FLOOR: //Ground floor
		case FLOOR_1_2: //1st or 2nd floor
			res = true;
			break;
		case FLOOR_3_4: //3rd or 4th floor
		case FLOOR_5_6: //5th or 6th floor
			if(TOT_FLOOR_1_2 != tot_floor)
				res = true;
			break;
		case FLOOR_7: //7th or more
			if(TOT_FLOOR_1_2 != tot_floor && TOT_FLOOR_3_5 != tot_floor)
				res = true;
			break;
		default:
			res = false;
			break;
	}
	
	return res;
}

function check_quest(form){
	var module = document.getElementById(form);
	var when = false;

	//Region can't be null
	//Check region
	if(0 == module.id_region.value){
		alert(bad_region);
		return false;
	}

	//Check province
	if("" == module.id_province.value || 0 == module.id_province.value){
		alert(bad_province);
		return false;
	}

	//Check commune
	if("" == module.id_commune.value || 0 == module.id_commune.value){
		alert(bad_commune);
		return false;
	}

	//Check "Observatory place"
	switch(module.obs_place.value){
		case "100":
			alert(bad_observatory);
			return false;
			break;
		case "-99":
			if("500" == module.floor.value){
				alert(bad_floor);
				return false;
			}
			break;
	}

	//Check earthquake
	if("-1" == module.id_quake.value){
		alert(bad_earthquake);
		return false;
	}
	
	if("0" == module.id_quake.value){
		if(false == check_date(module)){
			alert(bad_date);
			return false;
		}
	}

	//Check floor
	if(false == check_floor(module.floor, module.tot_floors)){
		alert(bad_floor);
		return false;
	}

	module.submit();
}

function check_subscribe(form){
	var to_check = new Array();
	var module = document.getElementById(form);

	//array: field, reg_exp, min_value, max_value
	to_check = [	["name",	not_null_spaced_alphastring, bad_string ],
			["surname",	not_null_spaced_alphastring, bad_string ],
			["email",	not_null_path_string, bad_email] ];

	if(false == check_syntax(module, to_check)){
		return false;
	}

	//Region can't be null
	//Check region
	var region = document.getElementById('id_region');
	if(0 == region.value){
		alert(bad_region);
		return false;
	}

	//Check province
	var province = document.getElementById('id_province');
	if(0 == province.value){
		alert(bad_province);
		return false;
	}

	//Check commune
	var commune = document.getElementById('id_commune');
	if(0 == commune.value){
		alert(bad_commune);
		return false;
	}

	module.submit();
}

//Ajax Wrappers
function update_select(select, res){
	var split_options = /\|/;
	var split_values = /\~/;
	var rows = res.split(split_options);
	var options = new Array();

	var num = rows.length;
	//Automatically i add a null value at the top
	var null_option = new Option("--", 0);
	select.options[0] = null_option;

	for(i = 0; i < num; i++){
		var opt = rows[i].split(split_values);
		var opt_res = opt[1].replace(/&quot;/g,"'");
		var options = new Option(opt_res, opt[0]);
		
		select.options[i+1] = options;
	}
}

function resetSearch(formId){
	
	$('start').value = 0;
	
	$(formId).submit();
}


//Permit questionnaires browsing (in event-list)
function sendForm(value, formId){

	$('start').value = parseInt($('start').value) + value;
	if(0 > parseInt($('start').value))
		$('start').value = 0;

	$(formId).submit();
}

//Ajax code starts here
function $(id){
	return document.getElementById(id);
}

function createXMLHttpRequest(){
try{ return new ActiveXObject("Msxml2.XMLHTTP"); } catch(e) {}
try{ return new ActiveXObject("Microsoft.XMLHTTP"); } catch(e) {}
	try{ return new XMLHttpRequest(); } catch(e) {}

	alert("XMLHttpRequest non supportata");
	return null;
}

function doAjaxRequest(elem, id_elem, to_update){
	var ajax_elem = createXMLHttpRequest();
	ajax_elem.onreadystatechange = function(){
		if(4 == ajax_elem.readyState){
			if(200 == ajax_elem.status){
				update_select(to_update, ajax_elem.responseText);
			}
			else{
				alert("Aggiornamento informazioni fallito");
			}
		}
	}

	var url = "get_data.php?what=" + elem + "&id=" + id_elem;
	ajax_elem.open("GET", url, true);
	ajax_elem.send(null);
}


//Regions uses those
function list_provinces(id_region){
	//Changing Regions i must reset provinces, comunes, fractions
	
	$('id_province').options.length = 0;
	$('id_commune').options.length = 0;
	$('id_fraction').options.length = 0;
	
	doAjaxRequest("provinces", id_region, $('id_province'));
}

//Provinces uses those
function list_comunes(id_province){
	
	$('id_commune').options.length = 0;
	$('id_fraction').options.length = 0;
	
	doAjaxRequest("comunes", id_province, $('id_commune'));
}

//Comunes uses those
function list_fractions(id_commune){
	try{
		$('id_fraction').options.length = 0;
		doAjaxRequest("fractions", id_commune, $('id_fraction'));
	}
	catch(e){
		alert(e);
	}
}

// #### Subcribe section
//Regions uses those
function list_provinces_subscribe(id_region){
	//Changing Regions i must reset provinces, comunes, fractions
	
	$('id_province').options.length = 0;
	$('id_commune').options.length = 0;
	
	doAjaxRequest("provinces", id_region, $('id_province'));
}

//Provinces uses those
function list_comunes_subcribe(id_province){
	
	$('id_commune').options.length = 0;
	
	doAjaxRequest("comunes", id_province, $('id_commune'));
}

