/*
* 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;
var captchaResponse = "";

//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");
}*/
function openWindow(sCmd) {
  var s2 = "left=150,top=10,width=750,height=600";
  //s2 += ",toolbar=0,location=0,directories=0,status=0,resizable=0,scrollbars=0,menubar=0";
  var winDownload = window.open(sCmd,"PTK_DownloadService",s2);
  winDownload.focus();
}

function openPopUp(sCmd,target) {
  var s2 = "left=10,top=10,width=770,height=250";
  s2 += ",toolbar=0,location=0,directories=0,status=0,resizable=yes,scrollbars=yes";
  var privacy = window.open("jsp/"+sCmd,"Privacy",s2);
  winHelp.focus();
}

// 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();
  }
}

// funzione per utilizzare il viewer20 con le mappe preferite
function cmnViewer20(sViewer, sUrl, sServer, sService, sServiceType, isDefault, sUUID, sType, sLabel, sServiceUrl, sVisible, sAlpha, sArgs, sWkid) {
  var sArgs2Pass;
  
  if (sArgs != "null") {
    var sArgs1 = sArgs.split('&')[0];
    var sArgs2 = sArgs.split('&')[1];

    sArgs2Pass = sArgs1+"&"+sServiceType+"=[{'type':'"+sType+"','label':'"+sLabel+"','url':'"+sServiceUrl+"','visible':'"+sVisible+"','alpha':'"+sAlpha+"'}]&"+sArgs2+"&srsWkid="+sWkid;
  } else
    sArgs2Pass = "[{'type':'"+sType+"','label':'"+sLabel+"','url':'"+sServiceUrl+"','visible':'"+sVisible+"','alpha':'"+sAlpha+"'}]&srsWkid="+sWkid;

  return addToViewer20PM(sUrl, sServer, sService, sServiceType, isDefault, sUUID, sArgs2Pass);
}

// view a map
function cmnViewMap(sViewer, sUrl, sServer, sService, sServiceType, isDefault, sUUID, sArgs, sWkid) {
  if (typeof(isDefault)=="undefined") {
    isDefault = false;
  }

  if (typeof(sWkid)=="undefined") {
    sWkid = "";
  }

  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);
  } else if (sViewer=="viewer20") {
    return addToViewer20(sUrl, sServer, sService, sServiceType, isDefault, sUUID, sArgs, sWkid);
  } else return null;
}

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 addToViewer20PM(sUrl, sServer, sService, sServiceType, isDefault, sUUID, sArgs) {
  /**
   * http://localhost:6060/viewer20/index.jsp
   * ?servicesLV=[{'type':'ESRI:IMS','servicename':'siba2010','label':'SIBA2010',
   * url':'www.cartografia.regione.lombardia.it','visible':'true','linkserver':'http://www.cartografia.regione.lombardia.it/geoportale/DiscoveryServlet','linkrequest':{'command':'viewdetails','uuid':'{809D4ABE-F48B-20E7-EC03-A634C9EFD52C}'}}]
   */

  // do not change the window name!
  //var windowName = "GeoPortale_Viewer_20" + getCookie('JSESSIONID');
  var windowName = "GeoPortale_Viewer_20";
  var parametri;
  var dimensioni;

  mapWidth = 820;
  mapHeight = 600;

  if ((sServer != "null") && (sService != "null") && (sArgs == null)) {
    sArgs = "&widgetVisible=Gestisci contenuto";
    sUrl = sUrl+"?servicesLV=[{'type':'ESRI:IMS','servicename':'"
    +sService+"','label':'"+
    sService.toString().toUpperCase()+"','url':'"
    +sServer+"','visible':'true','linkserver':'http://www.cartografia.regione.lombardia.it/geoportale/DiscoveryServlet','linkrequest':{'command':'viewdetails','uuid':'"
    +sUUID+"'}}]"+sArgs;
  } else if (sArgs != null) {
    //sUrl =sUrl+"?"+sServiceType+"="+sArgs;
    sUrl =sUrl+"?"+sArgs;
  }

  parametri = "location=1,resizable=yes,status=1,scrollbars=1";
  dimensioni = "width="+mapWidth+",height="+mapHeight;

  window.open(sUrl, windowName, parametri+","+dimensioni);
}

function openViewer20(sUrl, sEpsg) {
  var windowName = "GeoPortale_Viewer_20";// + getCookie('JSESSIONID');
  var parametri;
  var dimensioni;
  var mapWidth = 820;
  var mapHeight = 600;
  var sArgs="?serviceBMVisible=Ortofoto&servicesLV=[{'type':'ESRI:AGSD','label':'Inquadramento','url':'http://www.cartografia.regione.lombardia.it/ArcGIS93/rest/services/Generale/locatorUTM32N/MapServer','visible':'true','alpha':'0.5'}]&widgetVisible=Gestisci contenuto&srsWkid="+sEpsg;

  sUrl=sUrl+sArgs;
  parametri = "location=1,resizable=yes,status=1,scrollbars=1";
  dimensioni = "width="+mapWidth+",height="+mapHeight;
  window.open(sUrl, windowName, parametri+","+dimensioni);
}

function addToViewer20(sUrl, sServer, sService, sServiceType, isDefault, sUUID, sArgs, sWkid) {
  /**
   * http://localhost:6060/viewer20/index.jsp
   * ?servicesLV=[{'type':'ESRI:IMS','servicename':'siba2010','label':'SIBA2010',
   * url':'www.cartografia.regione.lombardia.it','visible':'true','linkserver':'http://www.cartografia.regione.lombardia.it/geoportale/DiscoveryServlet','linkrequest':{'command':'viewdetails','uuid':'{809D4ABE-F48B-20E7-EC03-A634C9EFD52C}'}}]
   */

  // do not change the window name!
  var windowName = "GeoPortale_Viewer_20";// + getCookie('JSESSIONID');
  var parametri;
  var dimensioni;

  mapWidth = 820;
  mapHeight = 600;
  // [{'type':'wms','label':'ctr_wms','url':'http://www.cartografia.regione.lombardia.it/ArcGIS93/services/wms/ctr_wms/MapServer/WMSServer','visible':'true','layerid':1}]
  if ((sServer != "null") && (sService != "null") && (sArgs == null)) {
    sArgs = "&widgetVisible=Gestisci contenuto";
    sUrl = sUrl+"?servicesLV=[{'type':'"+sServiceType+"','servicename':'"
    +sService+"','label':'"
    +sService.toString().toUpperCase()+"','url':'"
    +sServer+"','visible':'true','linkserver':'http://www.cartografia.regione.lombardia.it/geoportale/DiscoveryServlet','linkrequest':{'command':'viewdetails','uuid':'"
    +sUUID+"'}}]"+sArgs;
  } else if ((sServer != "null") && (sService != "null") && (sArgs != null)) {
    sArgs = sArgs.replace('(', '');
    sArgs = sArgs.replace(')', '');

    sUrl = sUrl+"?widgetVisible=Gestisci contenuto&servicesLV=[{'type':'"+sServiceType+"','servicename':'"
    +sService+"','label':'"
    +sArgs+"','url':'"
    +sServer+"','visible':'true','linkserver':'http://www.cartografia.regione.lombardia.it/geoportale/DiscoveryServlet','linkrequest':{'command':'viewdetails','uuid':'"
    +sUUID+"'}}]&srsWkid="+sWkid;

  //.replace('(', '')
  //sUrl =sUrl+"?"+sServiceType+"="+sArgs;
  }

  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";
}

function hideDiv(whatDiv) {
  var menu = document.getElementById(whatDiv);
  menu.style.display = "none";
}

function setDivVisibility(whatDiv, display) {
  var menu = document.getElementById(whatDiv);
  menu.style.display = display;
}

function onComplete() {
  if ((this.readyState == 4) && (this.status == 200)) {
    captchaResponse = this.responseText;
  } else {
    captchaResponse = "REQUEST FAILED!";
  }
}

function randomString(length) {
	var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZ";
	var randomstring = '';
	for (var i=0; i<length; i++) {
		var rnum = Math.floor(Math.random() * chars.length);
 		randomstring += chars.substring(rnum,rnum+1);
	}

  var firstWord = Math.round(length / 2);
  randomstring = randomstring.substr(0, firstWord)+' '+randomstring.substr(firstWord);
  
	return randomstring;
}

function addCaptchaRequest(url, type) {
  var request = createRequestObject();
  
  request.open(type, url, true);          //prepare the request

  request.onreadystatechange = onComplete;
  request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  request.send();                        //send it

  return request;                           //return the request
}

function setStatistics(sUrl, sValues) {
  var servletName=sUrl+"/StatisticServlet";
  var servletArguments = "jsoValues="+sValues;
  var req = servletName + "?" + servletArguments; //compiling the request

  var response = addrequest(req, "POST");     //calls the addrequest function
  response.onreadystatechange = function() {  //this is used to listen for changes in the request's status
  //do something with the response
  }
}

function addrequest(req, type) {
  try {
    //create a request for netscape, mozilla, opera, etc.
    var request = new XMLHttpRequest();
  } catch (e) {
    try {
      //create a request for internet explorer
      request = new ActiveXObject("Microsoft.XMLHTTP");
    } catch (e) {
      //do some error-handling
      alert("XMLHttpRequest error: " + e);
    }
  }

  request.open(type, req, true);          //prepare the request
  request.send(null);                       //send it
  return request;                           //return the request
}

function createRequestObject() {
  //creates an httprequest object
  var XHR;

  try {
    //create a request for netscape, mozilla, opera, etc.
    XHR = new XMLHttpRequest();
  } catch (e) {
    try {
      //create a request for internet explorer
      XHR = new ActiveXObject("Microsoft.XMLHTTP");
    } catch (e) {
      //do some error-handling
      alert("XMLHttpRequest error: " + e);
    }
  }

  return XHR;
}
