/* Copyright 2007-2008 SCube NewMedia. */

/** ============ GESTIONE API ============= */
var key = "ABQIAAAAUFrppv2oMiwmfR8jhoAHFRQCecenUwhGiRVk6bsTp8zLS8a7BRQQ9NXNSf0cGXW3xhh7-hbVXQ6w9Q";
if (document.domain == "provincia.milano.it" || document.domain == "www.provincia.milano.it") {
	key = "ABQIAAAAUFrppv2oMiwmfR8jhoAHFRQSgGqvl6RUhz24lZYNzdSOobPOeBTidyniuMrfdCPZ024wL4WnoBUAFg";
} else if (document.domain == "provincia.mi.it" || document.domain == "www.provincia.mi.it") {
	key = "ABQIAAAAUFrppv2oMiwmfR8jhoAHFRQMB_pfS2156CQn7Nn7BQhMMt_V3RSrfu79APc4z-wk7uy3-JU-CpgnyA";
}
document.write('<script src="http://web.geocms.it/a/' + ID_NOME_PROGETTO + '?file=api&amp;v=1.04&amp;license=' + LICENSE + '&amp;key=' + key + '"' +' type="text/javascript"></script>');

/** ============ COSTANTI ============= */
/** Constanti per identificare errori sulla query */
var NO_QUERY = "";

/** Operatori per la gestione della query */
var OPERATOR_OR = " OR ";
var OPERATOR_AND = " AND ";
var QUERY_FAILURE = "QUERY_FAILURE";
var QUERY_ABORT = "QUERY_ABORT";

/** Modalità di stampa */
var PRINT_DATA = "2";
var PRINT_DIRECTION = "1";
var PRINT_GRAPHIC = "0";
var PRINT_MODE = "mode";

/** Suggerimenti per il calcolo itinerario qualora non sia possibile individuare le località specificate */
var ERROR_PATH = "Impossibile calcolare il percorso richiesto: da \"ERROR_PATH_FROM\" a \"ERROR_PATH_TO\".\nSuggerimenti:\n - Assicurati che tutti i nomi di strade e citta' siano stati digitati correttamente.\n - L'indirizzo deve comprendere una citta' e una provincia.\n - Prova a inserire un codice postale.";

/** ============ VARIABILI COMUNI ============= */
/** Gestore della mappa */
var gmap = null;

/** Layer da caricare di default */
var LayerConfineProvincia = "ConfineProvincia";
/** temporizzazione caricamento informazioni da URL */
var LOAD_TIMEOUT = 500;
/** Livello di zoom a cui posizionarsi quando si setta il focus su un oggetto */
var FocusLevelZoom = 16;
/** Contiene i parametri ricevuti da URL */
var ParamByURL = {};
var LoadByParam = false;
/** Posizionamento della mappa */
var LAT = 45.463502;
var LNG = 9.188004;
var ZOOM = 10;

/**
 * Gestione ingresso applicazione
 */
window.onload = function() {
	if (SValidateLicense() == true) {
		try {
			// GEO_LOG_ERROR, GEO_LOG_WARNING, GEO_LOG_MESSAGE, GEO_LOG_DEBUG_USER, GEO_LOG_DEBUG_EVENT, GEO_LOG_DEBUG_METHOD, GEO_LOG_DEBUG_ALL
			// GeoLog.enable(GEO_LOG_MESSAGE);
	
			// inizializzo la mappa
			gmap = new GeoMap("map", "overlay");

			// skip the first character, we are not interested in the "?"
			var query = location.search.substring(1);
			// split the rest at each "&" character to give a list of  "argname=value"  pairs
			var pairs = query.split("&");
			// cicliamo su tutti i parametri
			for (var i = 0; i < pairs.length; i++) {
				// break each pair at the first "=" to obtain the argname and value
				var pos = pairs[i].indexOf("=");
				if (pos > -1) {
					// var argname = pairs[i].substring(0, pos).toLowerCase();
					var argname = pairs[i].substring(0, pos);
					var value = pairs[i].substring(pos + 1);
					ParamByURL[argname] = decodeURIComponent(value);
					LoadByParam = true;
				}
			};

			// gestione abilitazione logger
			var debug = ParamByURL["debug"];
			if (debug != null && debug.length > 0) {
				GeoLog.enable(debug);
				// settaggio stato caricmaento da URL
				LoadByParam = (pairs.length > 1);
			}

			// TODO
			// inizializzazione servizio remoto
			gmap.initializeRemoteService(LICENSE, PROGETTO, PUBLISHER, FRONTEND, /*language*/null, /*server*/null);

			// verifico che il servizio remoto sia stato attivato
			if (gmap.isRemoteServicAactivated() == false) {
				alert("Servizio remoto non attivo: impossibile procedere con la richiesta.")
				return;
			}	

			// verifichiamo se è stato definito un gestore specializzato
			if (typeof customOnLoad == "function") {
				// gestione parti specializzate
				customOnLoad();
			}

		} catch(e) {
			toException(e);
		}
	}
}

/** ============ FUNZIONI ============= */
/**
 * Richiamata per efftuuare la ricerca di un indirizzo
 */
function searchAddress(object) {
	try {
		// verifichiamo che l'informazione sia valida
		if (object.q.value == "") {
			// gestioen errore
			alert("Nessun indirizzo inserito");
		} else {
			// ricerchiamo l'indirizzo richiesto
			gmap.searchAddress(object.q.value, null, function(statusCode) {
				if (statusCode != SGEO_SUCCESS) {
					alert("Impossibile individuare l'indirizzo: \"" + object.q.value + "\"");
				}
			});		
		}
	} catch(e) {
		toException(e);
	}
}
/**
 * Naviga su l'oggetto richiesto.
 * @param idPOI identificatore punto da raggiungere.
 * @param idLevel livello di appartenenza [opzionale].
 * @param bZoom true nel caso in cui si vule effetture lo zoom della mappa, false in caso contrario (true by default) [opzionale].
 */
function goToPOI(idPOI, idLevel, bZoom, bSetCenter) {
	// focus su oggetto richiesto
	gmap.setObjectFocus(idPOI, idLevel, ((bZoom == null || bZoom == true)? FocusLevelZoom:null), (bSetCenter == null)?false:bSetCenter);
}
/**
 * Gestisce l'errore nel caso in cui si verifica una eccezione.
 * @param e eccezione da gestire.
 */
function toException(e) {
	var msg = "An exception occurred in the script.\nError name: " + e.name 
	+ ".\nError message: " + e.message;
	if (e.fileName) {msg += ".\nFile name: " + e.fileName;}
	if (e.lineNumber) {msg += ".\nLine number: " + e.lineNumber;	}

	alert(msg);
}

