/********************************
	commonFunctions.js
	
	Author: Vito Rifino
********************************/

var charEncoding = "UTF-8";
var localeEncoding = 'encoding="' + charEncoding + '" ';

// delimitatore da usare tra le coordinate nelle richieste ArcXml
var coordsDelimiter = " ";

// delimitatore da usare tra le coppie di coordinate nelle richieste ArcXml
var pairsDelimiter = ";";

// delimitatore da usare tra le coppie di coordinate nelle richieste ArcXml
var pairsDelimiterNew = "*";

// charset for dynamic HTML pages
var charSet = "ISO-8859-1"

var okToSend = true;

var serviceAvailable = true;

// character used by browser in decimals - either point or comma
var decimalChar = ((("theChar is" + (10/100)).indexOf("."))==-1) ? "," : ".";

//carattere separatore utilizzato da arcims
var decimalCharArcIms = ",";

var sQuote = "'";
var dQuote = '"';


// invio richiesta XML
// la richiesta viene inviata al server web
// il server web la inoltra ad arcims
// il server web riceve la risposta da ArcIms
// il server web la invia al client
// Questo meccanismo si è reso necessario in quanto
// non è possibile effettuare richieste AJAX cross-server:
// su Mozilla le richieste cross-server vengono bloccate senza scampo
// su IE compare un messaggio per far decidere all'utente se accettare o meno qualcosa di potenzialmente dannoso
function sendToServer(URLString,XMLRequest,theType){
	//alert(URLString);
	
	//TG
	//prompt("TEST TG",XMLRequest);
	
	if (okToSend) {	
		okToSend = false;
		XMLMode = theType;
	
		var formRoutingGeocoding = document.getElementById("formRoutingGeocoding");	    
		var xmlHeader = '<?xml version="1.0" ' + localeEncoding + '?>';
	        
		formRoutingGeocoding.URLString.value = URLString;
	//	formRoutingGeocoding.URLString.value = "http://sauron.planetek.it/servlet/com.esri.esrimap.Esrimap?ServiceName=pkt219_RouteServer";    
		formRoutingGeocoding.functionToProcessResponce.value = "processXML";
		formRoutingGeocoding.XMLRequest.value = xmlHeader + XMLRequest;
		//prompt ("URLString",URLString);
		//prompt ("richiesta",XMLRequest);
		formRoutingGeocoding.parentWindowToProcessResponce.value = "parent";         
		formRoutingGeocoding.action = "RoutingGeocoding/ArcImsPost.asp";    
		formRoutingGeocoding.target = "ifrmRoutingGeocoding";	
    formRoutingGeocoding.submit();
	}
	else {
	//	alert("Attendere" );
	}
}

// processa la risposta
function processXML(theReply) {
	okToSend = true;
	errorOccurred = false;
  //prompt("",theReply)
	switch(XMLMode) {
		//Parsing parametri di geocode e popola select
		case 5001:
			if (serviceRunning(theReply)) {		
			 	//prompt("risposta",theReply)	
   				parseGeocodeLayers(theReply);
   			//	alert(GCLayerCount)
   				for (var intI = 0; intI < GCLayerCount; intI++){
					  parseGeocodeParams(theReply, GCLayers[intI].layerName ,intI);
					
				}
				
				populateSelectGcService();
				changeGcSelect();
			}
			else{
				errorOccurred = true;
			}							
			break;
		//Parsing risultati di routing
		case 5002:	
		       // prompt("risposta",theReply)	
			if (serviceRunning( theReply )) {					
				parseRoutingResults(theReply);								
			}
			else{
				errorOccurred = true;
			}
			break;				
		//Parsing risultati di geocode		
		case 5004:
		// prompt("risposta",theReply)		
			if (serviceRunning( theReply )) {					
				parseGeocodeResults(theReply);								
			}
			else{
				errorOccurred = true;
			}
			break;	
				
	}
	if (errorOccurred){
		//alert("Si è verificato un errore durante una richiesta di Routing-Geocoding");
		alert(GCLang[RTLang][3])
		okToSend = true;
	}	
	return true;
}

// prendi i parametri per il geocoding
function getParamsGC() {	
	var theString = '<ARCXML VERSION="1.1">\n<REQUEST>\n<GET_SERVICE_INFO extensions="true" />\n</REQUEST>\n</ARCXML>';
    sendToServer( imsGeoCoderURL, theString, 5001 );
}

// controlla la risposta
function serviceRunning( theReply ) {
    str = '<ERROR>';
    var startpos = theReply.indexOf(str, 0);
    if ( startpos != -1 ) return false; // errore segnalato nella risposta	
	return true;
}


// elimina i 5 problemi del server parser XML
function makeXMLsafe(oldString) {
	oldString = oldString.replace(/&/g, "&amp;");
	oldString = oldString.replace(/'/g, "&apos;");
	oldString = oldString.replace(/>/g, "&gt;");
	oldString = oldString.replace(/</g, "&lt;");
	oldString = oldString.replace(/"/g, "&quot;");

	return oldString;
}

// elimina i problemi del post di un form
function makeStrSafeForPost(oldString) {
	oldString = oldString.replace(/&/g, "");
	//oldString = oldString.replace(/'/g, "");
	oldString = oldString.replace(/>/g, "");
	oldString = oldString.replace(/</g, "");
	oldString = oldString.replace(/"/g, "");

	return oldString;
}

//  
function makeStrFromXML(strXML)
{    
	   strXML = strXML.replace("''", "'");
    strXML = strXML.replace(/&apos;/g, "'");
    return (strXML);
}
//mc

function getimage(perc){
	extent_view=map.getExtent()
	envMINX= extent_view.left;
	envMAXY=extent_view.top;
	envMAXX=extent_view.right;
	envMINY=extent_view.bottom;
	imgwidth=(map.getSize()).w
	imgheight=(map.getSize()).h
	
	str = ""
	str = str + "<ARCXML version='1.1'>"
	str = str + "<REQUEST>"
	
	str = str + "<GET_IMAGE>"
	str = str + "<PROPERTIES>"
	str = str + "<ENVELOPE minx='" + envMINX + "' miny='" + envMINY + "' maxx='" + envMAXX + "' maxy='" + envMAXY + "' />"
	str = str + "<IMAGESIZE width='" + imgwidth + "' height='" + imgheight + "' dpi='150' />"
	/*str = str + "<LAYERLIST order='false'>" 
	str = str + Layerlist
	str = str + "</LAYERLIST>"*/
	str = str + "</PROPERTIES>"
	str = str + perc
	str = str + "</GET_IMAGE>"
	str = str + "</REQUEST>"
	str = str + "</ARCXML>"
	return str
}
//Parsing di envelope
function parseEnvelope( theReply, start ) {
    var str = '<ENVELOPE';
    var pos = theReply.indexOf(str, start);
    var reDot = /,/ig;
    
    if ( pos != -1 ) {
        var startpos = pos + str.length;
        str = '/>';
        var endpos = theReply.indexOf(str, startpos);
        if ( endpos != -1 ) {
            endpos += str.length;
            var strTag = theReply.substring(pos, endpos); // get <ENVELOPE.../> tag
            strTag = strTag.toUpperCase();
            var minx = parseAttrib( strTag, 'MINX' );
            var miny = parseAttrib( strTag, 'MINY' );
            var maxx = parseAttrib( strTag, 'MAXX' );
            var maxy = parseAttrib( strTag, 'MAXY' );

            minx     = setDecimalString(minx);
            miny     = setDecimalString(miny);
            maxx     = setDecimalString(maxx);
            maxy     = setDecimalString(maxy);
            
            if ( (minx != null) && (miny != null) && (maxx != null) && (maxy != null) ) {
                var envelope = new Envelope(parseFloat(minx), parseFloat(miny), parseFloat(maxx), parseFloat(maxy));
                return envelope;
            }
        }
    }
    return null;
}


//Parsing di attributi
function parseAttrib( Tag, Attr ) {
    var Attr1 = Attr + '=';
    var pos = Tag.indexOf( Attr1, 0 );
    if ( pos != -1 ) {
        pos += Attr1.length;
        var endpos = Tag.indexOf( ' ', pos );
        if ( endpos == -1 )
            endpos = Tag.indexOf( '/>', pos );
        if ( endpos == -1 )
            endpos = Tag.indexOf( '>', pos );
            
        if ( endpos != -1 ) {
            var str = Tag.substring( pos, endpos );
            str = str.replace(/"/g, ''); // remove "
            str = clearLeadingSpace( str );

            return str;
        }
    }
    return null;
}

// pulisce gli spazi vuoti
function clearLeadingSpace(inText) {
	var pos=9;
	while (pos != -1) {
		pos = inText.indexOf('=" ');
		if (pos!=-1) {
			var lastpos = inText.length;
			var midend = pos + 2;
			var midstart = pos + 3;
			var leftSide = inText.substring(0,midend);
			var rightSide = inText.substring(midstart,lastpos);
			inText = leftSide + rightSide;
		}
	}
	return inText;
}

// costruttore dell'oggetto envelope
function Envelope( minx, miny, maxx, maxy ) {
    this.minx = minx;
    this.miny = miny;
    this.maxx = maxx;
    this.maxy = maxy;
}


// replace di , con . o di . con , in base al browser
function setDecimalString(numberString) {
    if (decimalChar==".") {
        numberString = numberString.replace(/,/g, ".");
    } else {
		for (var intI = 0; intI<numberString.length - 1;intI++){
			numberString = numberString.replace(".", ",");
		}       
    }
    return numberString;
}

// replace con il delimitatore giusto di coordinate per arcims
function coordForArcIms(number){	
	if (decimalCharArcIms==".") {
        number = number.replace(/,/g, ".");
    } else if (decimalCharArcIms==",") {
		for (var intI = 0; intI<number.length - 1;intI++){
			number = number.replace(".", ",");
		}
    }
    return number;

}

// replace con il delimitatore giusto di coppie di coordinate per arcims
function coordPairForArcIms(number){	
	if (pairsDelimiterNew=="*") {        
		for (var intI = 0; intI<number.length - 1;intI++){
			number = number.replace(";", "*");
		}
    }
    return number;
}

// Calcola la precisione
function calcScale() {
	var iWidth = document.ECWView1.GetViewWidth();
	var iHeight = document.ECWView1.GetViewHeight();
	var viewWidthW = document.ECWView1.GetBottomRightWorldCoordinateX() -  document.ECWView1.GetTopLeftWorldCoordinateX();
	var viewHeightW = document.ECWView1.GetTopLeftWorldCoordinateY() - document.ECWView1.GetBottomRightWorldCoordinateY();
	var dx = viewWidthW / iWidth;
    var dy = viewHeightW / iHeight;    
    return Math.min( dx, dy );    
}

// Funzione per la creazione e il submit di un form con il metodo post
// Parametri:	stringaUrl -> url a cui postare il form
//				stringaParametri -> stringa contenente nomi dei parametri e dei loro valori
//									separati dal carattere &
//				nomeForm -> nome del form
//				nomeFinestra -> nome della finestra a cui postare il form
//								passare '_blank' per aprire una nuova finestra
function createAndSubmitFormPost(stringaUrl,stringaParametri,nomeForm,nomeFinestra){
	action=stringaUrl;
	arrParametri=new Array();
	formConDati='';
	metodo='POST';	

	if (stringaParametri!=''){
		arrParametri=stringaParametri.split('&');
		for (indiceArrParametri=0;indiceArrParametri<arrParametri.length-1;indiceArrParametri=indiceArrParametri+2){					
			formConDati+='<input type="hidden" name="' + arrParametri[indiceArrParametri] + '" id="' + arrParametri[indiceArrParametri] + '" value="' + arrParametri[indiceArrParametri+1] + '">';
		}
	}				
	//prompt("",stringaParametri)
	document.getElementById(nomeForm).innerHTML=formConDati;
	document.getElementById(nomeForm).method=metodo;	
	document.getElementById(nomeForm).action=action;	
	document.getElementById(nomeForm).target=nomeFinestra;
	document.getElementById(nomeForm).submit();		
}

//Richiesta di una mappa ad ArcIms
function writeXmlMapRequest(mode){
	theString = "";
		
	if (mode == 5002){				
		theString += strInitializeRoutingMap();		
	}
	
	return theString;    
}

function tooltipOnRG(ev,objSlc) {
	var objTooltip = document.getElementById("tooltipTxtRG");
	var objDivTip = document.getElementById("tipRG");
	var strSlc = objSlc[objSlc.selectedIndex].text;
	
	objDivTip.style.display = "inline";
	objDivTip.style.top = ev.y-45;
	objDivTip.style.left = ev.x;
	objTooltip.innerHTML = strSlc;
	return true;
}

function tooltipOffRG() {
	document.getElementById("tipRG").style.display = "none";
	document.getElementById("tooltipTxtRG").innerHTML = "";
	return false;
}


function HideShowMenuGeocoding() {

	var nomeMenu = "ricerca indirizzi";
	var objMenu = document.getElementById("MenuGeocoding");
	var objButtOpenClose = document.getElementById("ButtOpenCloseMenuGeocoding");
	var objButtOpenCloseHref = document.getElementById("ButtOpenCloseMenuGeocodingHref");
		
	switch (objMenu.style.display) {
		case "":
			objButtOpenClose.src = "RoutingGeocoding/images/butt_box_open.gif";
			objButtOpenClose.alt = "Apri menu " + nomeMenu;
			objButtOpenCloseHref.title= "Apri menu " + nomeMenu;
			objMenu.style.display = "none";
		break;
		case "none":
			objButtOpenClose.src = "RoutingGeocoding/images/butt_box_close.gif"
			objButtOpenClose.alt = "Chiudi menu " + nomeMenu;
			objButtOpenCloseHref.title= "Chiudi menu " + nomeMenu;
			objMenu.style.display = "";	
		break;
	}
}
function chiudi_routing(){
	  document.getElementById("MenuRouting2").style.display="none";
		document.getElementById("MenuRouting").style.display="none";
		
		obj_route=document.getElementById("menu_route").contentWindow;
		if (obj_route.document.getElementById("avanzate").style.display=="")
				mostra_opzioni();
		
		richiesta_percorso="";
		id_itinerario=0;
		check_itinerario=0;
		document.getElementById("divWaitPlease").style.display = "none";
	//MC 08/10/07 bisogna ricaricare il boxricerca per eliminare la riga degli itinerari
	if (document.getElementById("Ricerca").src!="") {
		url_box=(document.getElementById("Ricerca").src).split("&itin=")
		url_box=url_box[0]+"&itin="+check_itinerario+"&tom="+checkbox+"&n_pagina="+act_npag //MDe Santis 12/10/2007 aggiunta "&tom="+checkbox+
		if (url_box.search("tlx")==-1){
		 		extent_view=map.getExtent()
	
				extent_tlx=parseInt(extent_view.left);
				extent_tly=parseInt(extent_view.top);
				extent_brx=parseInt(extent_view.right);
				extent_bry=parseInt(extent_view.bottom);
				width=map.getSize().w;
				url_box=url_box+"&width="+width+"&tlx="+extent_tlx+"&tly="+extent_tly+"&brx="+extent_brx+"&bry="+extent_bry
		}		
		document.getElementById("Ricerca").src=url_box
	 }
	
	clearAll();
	n_eliminati=0
	for (var k=1;k<map.events.listeners["click"].length;k++){
  			 
  	 			map.events.unregister("click",map,map.events.listeners["click"][k].func);
 	       
 }
 for (obj in index_click){
  			 
  	 			index_click[obj]=null
 	       
 }
  		
	rimuovi_icone("ALL") 
}
function HideShowMenuRouting() {

	var nomeMenu = "calcolo percorsi";
	var objMenu = document.getElementById("MenuRouting");
	var objButtOpenClose = document.getElementById("ButtOpenCloseMenuRouting");
	var objButtOpenCloseHref = document.getElementById("ButtOpenCloseMenuRoutingHref");
	
	switch (objMenu.style.display) {
		case "":
			objButtOpenClose.src = "RoutingGeocoding/images/butt_box_open.gif";
			objButtOpenClose.alt = "Apri menu " + nomeMenu;
			objButtOpenCloseHref.title= "Apri menu " + nomeMenu;
		  objMenu.style.display = "none";
		  document.getElementById("MenuRouting2").style.display=""
			
		break;
		case "none":
			objButtOpenClose.src = "RoutingGeocoding/images/butt_box_close.gif"
			objButtOpenClose.alt = "Chiudi menu " + nomeMenu;
			objButtOpenCloseHref.title= "Chiudi menu " + nomeMenu;
			objMenu.style.display = "";	
			document.getElementById("MenuRouting2").style.display="none"				
		break;
	}
}

function tooltipOnMode(ev,strSlc) {
	var objTooltip = document.getElementById("tipModeTxt");
	var objDivTip = document.getElementById("tipMode");	
	
	objDivTip.style.display = "inline";
	objDivTip.style.top = ev.y+20;
	objDivTip.style.left = ev.x;
	objTooltip.innerHTML = strSlc;
	return true;
}

function tooltipOffMode() {
	try{
		document.getElementById("tipMode").style.display = "none";
		document.getElementById("tipModeTxt").innerHTML = "";
	}catch(e){}
	return false;
}

function HideShowPercorso(){	
	var objDiv = document.getElementById("divResultRouting");
	var objMenu = document.getElementById("ifrmResultRouting");
	var objMenu_row = document.getElementById("ifrmResultRouting_row");
	var objButtOpenClose = document.getElementById("ButtOpenClosePercorso");
	var objButtOpenCloseHref = document.getElementById("ButtOpenClosePercorsoHref");
		
	switch (objMenu.style.display) {
		case "":
			objButtOpenClose.src = "RoutingGeocoding/images/butt_box_open.gif";
			objButtOpenClose.title =GCLang[RTLang][14];
		//	objButtOpenCloseHref.title= GCLang[RTLang][12];
			objMenu.style.display = "none";
			objMenu_row.style.height="25"
			objDiv.style.height="25px";
			objDiv.style.width="310px";
		break;
		case "none":
			objButtOpenClose.src = "RoutingGeocoding/images/butt_box_close.gif"
			objButtOpenClose.title =GCLang[RTLang][13];
			//objButtOpenCloseHref.title= "1"+GCLang[RTLang][14];
			objMenu.style.display = "";	
				objMenu_row.style.height="190"
			objDiv.style.height="190px";
			objDiv.style.width="310px";			
		break;
	}
}

function ChiudiPercorso(){
	var objDiv = document.getElementById("divResultRouting");
	objDiv.style.height="300px";
	objDiv.style.width="250px";
	objDiv.style.display = "none";
	/*richiesta_percorso="";
	id_itinerario=0;*/
}

function HideShowGeocodifica(){	
	var objDiv = document.getElementById("divResultGeocoding");
	var objMenu = document.getElementById("ifrmResultGeocoding");
	var objButtOpenClose = document.getElementById("ButtOpenCloseGeocodifica");
	var objButtOpenCloseHref = document.getElementById("ButtOpenCloseGeocodificaHref");
		
	switch (objMenu.style.display) {
		case "":
			objButtOpenClose.src = "RoutingGeocoding/images/butt_box_open.gif";
			objButtOpenClose.alt = "Apri";
			objButtOpenCloseHref.title= "Apri";
			objMenu.style.display = "none";
			objDiv.style.height="0px";
			objDiv.style.width="0px";
		break;
		case "none":
			objButtOpenClose.src = "RoutingGeocoding/images/butt_box_close.gif"
			objButtOpenClose.alt = "Riduci a icona";
			objButtOpenCloseHref.title= "Riduci a icona";
			objMenu.style.display = "";	
			objDiv.style.height="300px";
			objDiv.style.width="250px";			
		break;
	}
}

function ChiudiGeocodifica(){
	var objDiv = document.getElementById("divResultGeocoding");
	objDiv.style.height="300px";
	objDiv.style.width="250px";
	objDiv.style.display = "none";
}

function HideShowCapAndVia(){	
	var objDiv = document.getElementById("divResultCapAndVia");
	var objMenu = document.getElementById("ifrmResultCapAndVia");
	var objButtOpenClose = document.getElementById("ButtOpenCloseCapAndVia");
	var objButtOpenCloseHref = document.getElementById("ButtOpenCloseCapAndViaHref");
		
	switch (objMenu.style.display) {
		case "":
			objButtOpenClose.src = "RoutingGeocoding/images/butt_box_open.gif";
			objButtOpenClose.alt = "Apri";
			objButtOpenCloseHref.title= "Apri";
			objMenu.style.display = "none";
			objDiv.style.height="0px";
			objDiv.style.width="0px";
		break;
		case "none":
			objButtOpenClose.src = "RoutingGeocoding/images/butt_box_close.gif"
			objButtOpenClose.alt = "Riduci a icona";
			objButtOpenCloseHref.title= "Riduci a icona";
			objMenu.style.display = "";	
			objDiv.style.height="150px";
			objDiv.style.width="250px";			
		break;
	}
}

function ChiudiCapAndVia(){
	var objDiv = document.getElementById("divResultCapAndVia");
	objDiv.style.height="150px";
	objDiv.style.width="250px";

	objDiv.style.display = "none";
}


