/*
* Script: cmn.js
* Author: UMG
* Descrpition: Common utilities script.
*/

//set the domain name so that it can talk to map viewer
hostDomain = document.domain;
//document.domain = hostDomain.substring(hostDomain.indexOf(".")+1);

// local variables
var pIsIE  = (navigator.appVersion.indexOf("MSIE")>=0);
var pIsNS  = (navigator.appName.indexOf("Netscape")>=0);
var pIsWin = (navigator.userAgent.indexOf("Win")>=0);
var pDomainPfx = ""; //pDomainPfx = "http://www.geographynetwork.com";
var ArcExplorerWin = null;
var timerId;
var NumOfAttempts = 0;
var initMinx = 67.2314;
var initMiny = 8.0057;
var initMaxx = 94.4215;
var initMaxy = 34.5346;

//the custom id, must in the url for every request call
var origid = "ESRI_World";

// LISER - Giuseppe Matera - 07 luglio 2008: cambio lingua sito it
function cmnChangeLanguage(lang) {
	var oFrm = document.forms.fSubmit;
	if (oFrm != null) {
		oFrm.action = jsWepAppContext+"/ptk";
		oFrm.command.value = 'changeLanguage';
		oFrm.language.value = lang;
		oFrm.method = "post";
		oFrm.action = document.forms.fSubmit.action;
		oFrm.submit();		
	}
	
}
function openMarketplace() {
  var oFrm =  document.forms.fSubmit;
  if (oFrm != null) {
    oFrm.action = jsWepAppContext+"/DiscoveryServlet";
    cmnCmd('marketplace');
  }
}

// execute a command
function cmnCmd(sCmd) {
	var oFrm = null;
	
	if ((sCmd != "viewmetadata") && window.opener && !window.opener.closed && window.opener.cmnCmd) {
		oFrm = window.opener.document.forms.fSubmit;
		if (oFrm != null) {
			oFrm.action = document.forms.fSubmit.action;
		}
		window.opener.cmnCmd(sCmd);
	} else if (sCmd == "forgotpwd") {
		oFrm = document.forms.fSubmit;
		if (oFrm && oFrm.command) {
			self.focus();
			oFrm.command.value = sCmd;
			oFrm.method = "post";
			//oFrm.action = jsWepAppContext+"/forgot_password.do";
			oFrm.action = document.forms.fSubmit.action;
			oFrm.submit();
		}
	} else if (sCmd.toLowerCase().indexOf("usedde") != -1) {
		// LISER - Giuseppe Matera - 06 febbraio 2007: Per aprire una finestra di PopUp che richiama il SIBA
		openPrj (sCmd,"USEDDE");
	} else if (sCmd.toLowerCase().indexOf("geoiffi") != -1) {
		// LISER - Giuseppe Matera - 06 febbraio 2007: Per aprire una finestra di PopUp che richiama GeoIFFI
		openPrj (sCmd,"GeoIFFI");
	} else if (sCmd.toLowerCase().indexOf("login") != -1) {
		oFrm = document.forms.fSubmit;
		if (oFrm && oFrm.command) {
			self.focus();
			oFrm.command.value = sCmd;
			oFrm.target = "_top";
			//oFrm.method = "post";
			//oFrm.action = jsWepAppContext+"/";
			oFrm.submit();
		}
	} else if (sCmd.toLowerCase().indexOf("helphtml") == -1) {
		oFrm = document.forms.fSubmit;
		if (oFrm && oFrm.command) {
			self.focus();
			oFrm.command.value = sCmd;
			oFrm.target = "_top";
			//oFrm.method = "post";
			//oFrm.action = jsWepAppContext+"/";
			oFrm.submit();
		}
	}	else {
		var s2 = "left=10,top=10,width=875,height=500";
		s2 += ",toolbar=0,location=0,directories=0,status=0,resizable=yes,scrollbars=yes";
		var winHelp = window.open(sCmd,"PTK_Help",s2);
		winHelp.focus();
	}
}

//helper function to call cmnCmd without pop up window
/*function cmnCmd(sCmd) {
 doCmnCmd(sCmd,"_top");
}*/

// execute a command
function doCmnCmd(sCmd,target) {
  if ((sCmd != "viewmetadata") && window.opener && !window.opener.closed && window.opener.cmnCmd) {
    window.opener.cmnCmd(sCmd);
  } else {
    if (sCmd.toLowerCase().indexOf("help") == -1) {
      var oFrm = document.forms.fSubmit;
      if (oFrm && oFrm.command) {
        self.focus();
        oFrm.command.value = sCmd;
        oFrm.target = target;
        oFrm.submit();
      }
    } else {
      var s2 = "left=10,top=10,width=770,height=450";
      s2 += ",toolbar=0,location=0,directories=0,status=0,resizable=yes,scrollbars=yes";
      var winHelp = window.open(sCmd,"PTK_Help",s2);
      winHelp.focus();
    }
  }
}

// get search area for viewer
function cmnGetSearchArea() {
  var winMap;
  var sName = "ArcExplorerWeb_" + getCookie('JSESSIONID');
  var sInfo = "toolbar=no,width=800,height=564";
  if (pIsWin)
    sInfo = "toolbar=no,width=800,height=564,left=5,top=5";
  else if (!pIsWin && pIsNS)
    sInfo = "toolbar=no,width=800,height=564,screenX=5,screenY=5";
  else if (!pIsWin && pIsIE)
    sInfo = "toolbar=no,width=784,height=548,left=5,top=5";
  winMap = window.open('',sName,sInfo);
  if (!winMap.closed && winMap.Map && winMap.Hidden4.setMapExtentStatus) {
    winMap.opener = self;
    //winMap.Map.setMapExtentStatus(true);
	winMap.Hidden4.setMapExtentStatus(true);
  } else {
    winMap.close(); alert("The Map Viewer is not currently open.");
  }
}

// LISER - Paolo Milani: funzione creata da Paolo Milani per la creazione di una finestra di PopUp per i Prj
function openPrj (sCmd,nomePrj){
			var s2 = "left=10,top=10,width=785,height=580";
			s2 += ",toolbar=0,location=0,directories=0,status=0,resizable=yes,scrollbars=yes";
			var winHelp = window.open(sCmd,nomePrj,s2);
			winHelp.focus();

}
//helper function to call cmnCmd without pop up window
/*function cmnCmd(sCmd) {
 doCmnCmd(sCmd,"_top");
}*/

// view details
function cmnViewDetails(sUuid) {
  var oFrm = document.forms.fSubmit;
  if (oFrm && oFrm.command && oFrm.uuid) {
    oFrm.action = jsWepAppContext+"/DiscoveryServlet";
    oFrm.command.value = "viewdetails";
    oFrm.uuid.value = sUuid;
    oFrm.target = "_top";
    oFrm.submit();
  }
}

// view a map
function cmnViewMap(sViewer, sUrl, sServer, sService, sServiceType, isDefault, sUUID, sArgs) {
	
	if (typeof(isDefault)=="undefined") {
		isDefault = false;
	}
	
	if (sViewer=="default") {
		return addToArcExplorerWeb(sUrl, sServer, sService, sServiceType, isDefault, sUUID, sArgs);
	}	else if (sViewer=="cartanet") {
		return addToCartanet(sUrl, sServer, sService, sServiceType, isDefault, sUUID, sArgs);
	} else if (sViewer=="liteviewer") {
		if (sServer.toString().indexOf("http")==-1)
			sServer = "http://"+sServer;
	
		return addToLiteViewerWeb(sUrl, sServer, sService, isDefault, sUUID, sArgs);
		
	}
}

function checkArcExplorerOpened(sServer, sService, sServiceType, isDefault, sUUID, sArgs)
{
  //var sExtent = "";
  //alert('MapViewer is starting: ' + (NumOfAttempts + 1) * 0.1 + ' sec.' + '\nServer=' + sServer + '\nService=' + sService + '\nType=' + sServiceType + '\nDefault=' + isDefault + '\nUUID=' + sUUID + '\nArgs=' + sArgs);

  //---------------------------------------------
  // If MapViewer window is opened
  // --------------------------------------------
  if(!ArcExplorerWin.closed) {
    if(ArcExplorerWin.document.title.toLowerCase().indexOf('error') >= 0) {
      clearInterval(timerId);
      NumOfAttempts = 0;
      alert('MapViewer failed to load.\n Please contact portal admin for further support.');
    }else if(ArcExplorerWin.Map && ArcExplorerWin.Map.ready && NumOfAttempts <= 600) {
      NumOfAttempts = 0;
      clearInterval(timerId);
      ArcExplorerWin.focus();
      ArcExplorerWin.opener = self;

      if(!isDefault) {
        if(sServiceType == "feature" || sServiceType == "image")
          ArcExplorerWin.Map.addServiceRemote(sServer, sService, null, sUUID); //sExtent
        else if(sServiceType == "wms")
          ArcExplorerWin.Map.addWMSService(sServer, null, sUUID);
        else if(sServiceType == "wfs")
          ArcExplorerWin.Map.addWFSService(sServer, null, sUUID);
        else if(sServiceType == "wcs")
          ArcExplorerWin.Map.addWCSService(sServer, null, sUUID);
      }
    } else if(NumOfAttempts > 600) {
      clearInterval(timerId);
      NumOfAttempts = 0;
      alert('MapViewer keeps loading for extended period of time.\n Operation is canceled.');
    } else NumOfAttempts++;
  }
}

function ESRIaddToArcExplorerWeb(sServer, sService, sServiceType, isDefault, sUUID, sArgs)
{
  // do not change the window name!
  var windowName = "ArcExplorerWeb_" + getCookie('JSESSIONID');
  //alert(sServer + ', ' + unescape(sServer));
  while(sServer.indexOf('amp;') > 0) sServer = sServer.replace('amp;', '&');
  if(sUUID == undefined) sUUID = '';

  if (pIsWin)
    ArcExplorerWin = window.open('', windowName, "toolbar=no,resizable=yes,width=800,height=564,left=5,top=5");
  else if (!pIsWin && pIsNS)
    ArcExplorerWin = window.open('', windowName, "toolbar=no,resizable=yes,width=800,height=564,screenX=5,screenY=5");
  else if (!pIsWin && pIsIE)
    ArcExplorerWin = window.open('', windowName, "toolbar=no,resizable=yes,width=784,height=548,left=5,top=5");
  else ArcExplorerWin = window.open('', windowName, "toolbar=no,resizable=yes,width=800,height=564");

  if(!ArcExplorerWin.closed && ArcExplorerWin.Map == null)
    ArcExplorerWin = window.open(pDomainPfx + '/arcexplorer/arcexplorer.jsp?origid=&isDefault=' + isDefault, windowName, "toolbar=no,resizable=yes,width=800,height=564");

  NumOfAttempts = 0;
  timerId = setInterval('checkArcExplorerOpened("' + sServer + '", "' + sService + '", "' + sServiceType + '", false, "' + sUUID + '", "' + sArgs + '")', 100);
}

function addToArcExplorerWeb(sUrl, sServer, sService, sServiceType, isDefault, sUUID, sArgs) {
	// do not change the window name!
	var windowName = "GeoPortale_ArcExplorer_" + getCookie('JSESSIONID');
	var parametri;

  mapWidth = 820;
	mapHeight = 600;
	
	//return addToArcExplorerWeb(sUrl, sServer, sService, sServiceType, isDefault, sUUID, sArgs);
	parametri = "'"+'location=1,status=1,scrollbars=1,width='+mapWidth+',height='+mapHeight+"'";
	if (isDefault) {
		// Terraria - Mauro Pomatti - 17 aprile 2007: esecuzione viewer light
		// Originale: window.open("http://www.cartografia.lispa.it/arcexplorer/arcexplorer.jsp?server=http://www.cartografia.lispa.it&service=PortalBaseMap&usesession=true&uuid=", windowName, parametri);
		//window.open("http://www.cartografia.regione.lombardia.it/GPTLiteViewer/html/mapbrowser/init/initMapServices?server=http://www.cartografia.lispa.it&service=PortalBaseMap&usesession=true&uuid=", windowName, parametri);
		// cartanet -  18 Luglio 2007: esecuzione viewer light
		//window.open(sUrl+"?tipo=ArcIms&nomeservizio=PortalBaseMap&versionewms=&nome=PortalBaseMap&indirizzoip=www.cartografia.lispa.it&portaserver=5300&srs=26591&versione=1&http=GET#",windowName, parametri);
		//window.open(sUrl+"?tipo=ArcIms&nomeservizio="+sService+"&versionewms=&nome="+sService+"&indirizzoip="+sServer+"&portaserver=5300&srs=26591&versione=1&http=GET#",windowName, parametri);
		window.open(sUrl+"?tipo=ArcIms&nomeservizio="+sService+"&versionewms=&nome="+sService+"&indirizzoip="+sServer+"&portaserver=5300&srs=26591&versione=1&idraster1=189&http=GET#",windowName, parametri);
	} else {
		// Terraria - Mauro Pomatti - 17 aprile 2007: esecuzione viewer light
		// Originale: window.open("http://www.cartografia.lispa.it/arcexplorer/arcexplorer.jsp?server="+sServer+"&service="+sService+"&usesession=true&uuid=", windowName, parametri);	
		//window.open("http://www.cartografia.regione.lombardia.it/GPTLiteViewer/html/mapbrowser/init/initMapServices?server="+sServer+"&service="+sService+"&usesession=true&uuid=", windowName, parametri);	
		// cartanet -  18 Luglio 2007: esecuzione viewer light
		window.open(sUrl+"?tipo=ArcIms&nomeservizio="+sService+"&versionewms=&nome="+sService+"&indirizzoip="+sServer+"&portaserver=5300&srs=26591&versione=1&idraster1=189&http=GET#",windowName, parametri);
	}
}

function addToLiteViewerWeb(sUrl, sServer, sService, isDefault, sUUID, sArgs) {
	// do not change the window name!
	var windowName = "GeoPortale_Lite_Viewer_" + getCookie('JSESSIONID');
	var commandline;
	var parametri;

  mapWidth = 955;
  mapHeight = 650;

	parametri = "'"+'location=1,status=1,scrollbars=0,width='+mapWidth+',height='+mapHeight+"'";
	
	if (isDefault) {
		// Terraria - Mauro Pomatti - 17 aprile 2007: esecuzione viewer light
		commandline = sUrl+"?server="+sServer+"&service=PortalBaseMap";
	} else {
		// Terraria - Mauro Pomatti - 17 aprile 2007: esecuzione viewer light
		if (sArgs)
			commandline = sUrl+"?server="+sServer;
		else
			commandline = sUrl+"?server="+sServer+"&service="+sService;
	}

	window.open(commandline, windowName, parametri);
}

function addToCartanet(sUrl, sServer, sService, sServiceType, isDefault, sUUID, sArgs)
{
	// do not change the window name!
	var windowName = "GeoPortale_Cartanet_Viewer_" + getCookie('JSESSIONID');
	var parametri;
	var dimensioni;

	mapWidth = 820;
	mapHeight = 600;
	
	if ((sServer != "null") && (sService != "null")) {
		sUrl = sUrl+"?tipo=ArcIms&nomeservizio="+sService+"&versionewms=&nome="+sService+"&indirizzoip="+sServer+"&portaserver=5300&srs=26591&versione=1&idraster1=189&http=GET";
	}
	
	parametri = "location=1,resizable=yes,status=1,scrollbars=1";
	dimensioni = "width="+mapWidth+",height="+mapHeight;
	window.open(sUrl, windowName, parametri+","+dimensioni);
}

function openSavedMap(linkId)
{
   var winMap;
   var sName = "ArcExplorerWeb_" + getCookie('JSESSIONID');
   var ArcExplorerWin;
   var sInfo = "toolbar=no,width=800,height=564";

   if (getCookie("PortalToolKitUserID") == null) {
     alert("User has been disconnected ...");
     return;
   }

   if (pIsWin)
     sInfo = "toolbar=no,width=800,height=564,left=5,top=5,resizable=yes";
   else if (!pIsWin && pIsNS)
     sInfo = "toolbar=no,width=800,height=564,screenX=5,screenY=5,resizable=yes";
   else if (!pIsWin && pIsIE)
     sInfo = "toolbar=no,width=784,height=548,left=5,top=5,resizable=yes";

   var theUrl = pDomainPfx + "/arcexplorer/arcexplorer.jsp?origid=" + origid + "&link=" + linkId;
   winMap =  window.open(theUrl,sName,sInfo);
}

function getCookie(name){
   var cname = name + "=";
   var dc = document.cookie;
   
   if (dc.length > 0) {
        begin = dc.indexOf(cname);
        if (begin != -1) {
            begin += cname.length;
            end = dc.indexOf(";", begin);
            if (end == -1) end = dc.length;
            return unescape(dc.substring(begin, end));
         }
   }
   return null;
}

function setCookie(name, value) {
    var now = new Date();
    var then = "-1"
    document.cookie = name + "=" + escape(value) + "; expires=-1; path=/";
}

function deleteSessionCookies() {
  var expiration_date = new Date();
   expiration_date.setTime(expiration_date.getTime());
   document.cookie = "PortalToolKitUserID=deleted" + "; expires=" + expiration_date.toGMTString() + ";path=/";
   document.cookie = "PortalToolKitUserRole=deleted" + "; expires=" + expiration_date.toGMTString() + ";path=/";
   document.cookie = "PortalToolKitChnMgtRole=deleted" + "; expires=" + expiration_date.toGMTString() + ";path=/";
   document.cookie = "EsriPortalToolKit2004=deleted" + "; expires=" + expiration_date.toGMTString() + ";path=/";
}

function showDiv(whatDiv) {
	var menu = document.getElementById(whatDiv);
	var display = menu.style.display;
	menu.style.display = (display == "block") ? "none" : "block";
}