/*
* 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";

// conterra extension
// global variable for the newly created ArcExplorerOpen-Object
var mArcExplorerOpenTestChecker;

function openMarketplace(){
  var oFrm =  document.forms.fSubmit;
  if (oFrm != null) {
    oFrm.action = jsWepAppContext+"/DiscoveryServlet";
    cmnCmd('marketplace');
  }
}

// execute a command
function cmnCmd(sCmd) {
    if ((sCmd != "viewmetadata") && window.opener && !window.opener.closed && window.opener.cmnCmd) {
        var oFrm = window.opener.document.forms.fSubmit;
		if (oFrm != null) {
			oFrm.action = document.forms.fSubmit.action;
		}
		window.opener.cmnCmd(sCmd);
	}else if (sCmd == "forgotpwd") {

         var 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("help") == -1) {
            var 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=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();
		}
	}
}

//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.");
  }
}

// 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(sServer, sService, sServiceType, isDefault, sUUID, sArgs)
{
  return addToArcExplorerWeb(sServer, sService, sServiceType, isDefault, sUUID, sArgs);
}

//view the default map -- only to be used for the Map Viewer menu link
function cmnViewDefaultMap(sServer, sService, sServiceType, isDefault, sUUID, sArgs)
{
  return addDefaultViewToArcExplorerWeb(sServer, sService, sServiceType, 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 addToArcExplorerWeb(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,status=yes,width=1024,height=768,left=5,top=5");
  else if (!pIsWin && pIsNS)
    ArcExplorerWin = window.open('', windowName, "toolbar=no,resizable=yes,status=yes,width=1024,height=768,screenX=5,screenY=5");
  else if (!pIsWin && pIsIE)
    ArcExplorerWin = window.open('', windowName, "toolbar=no,resizable=yes,status=yes,width=784,height=610,left=5,top=5");
  else ArcExplorerWin = window.open('', windowName, "toolbar=no,resizable=yes,status=yes,width=1024,height=768");

  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");
    ArcExplorerWin = window.open(pDomainPfx + '/arcexplorer/servlet/ISC_ArcExplorerStartup?action=baseMap&origid=&isDefault=' + isDefault, windowName, "toolbar=no,resizable=yes,status=yes,width=800,height=564"); 
  }

    NumOfAttempts = 0;
    // conterra extension
    // use this object instead of the simple function call, as the args param could not used with an identity token
    mArcExplorerOpenTestChecker = new ArcExplorerOpen(sServer, sService, sServiceType, false, sUUID, sArgs);
    // old version follows here
    //timerId = setInterval('checkArcExplorerOpened("' + sServer + '", "' + sService + '", "' + sServiceType + '", false, "' + sUUID + '", "' + sArgs + '")', 100);
    timerId = setInterval('mArcExplorerOpenTestChecker.check()', 100);
}

//This is a modified copy of the addToArcExplorerWeb to be used in the Map Viewer menu item. It should only be used to open the default view. 
function addDefaultViewToArcExplorerWeb(sServer, sService, sServiceType, isDefault, sUUID, sArgs)
{
  if( ArcExplorerWin == null || (ArcExplorerWin != null && ArcExplorerWin.closed) ) // this check works until the user navigates to a different page, because ArcExplorerWin gets reset
  {
	  // 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,status=yes,width=1024,height=768,left=5,top=5");
	  else if (!pIsWin && pIsNS)
	    ArcExplorerWin = window.open('', windowName, "toolbar=no,resizable=yes,status=yes,width=1024,height=768,screenX=5,screenY=5");
	  else if (!pIsWin && pIsIE)
	    ArcExplorerWin = window.open('', windowName, "toolbar=no,resizable=yes,status=yes,width=784,height=610,left=5,top=5");
	  else ArcExplorerWin = window.open('', windowName, "toolbar=no,resizable=yes,status=yes,width=1024,height=768");
	  
	  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");
	    ArcExplorerWin = window.open(pDomainPfx + '/arcexplorer/servlet/ISC_ArcExplorerStartup?action=baseMap&origid=&isDefault=' + isDefault, windowName, "toolbar=no,resizable=yes,status=yes,width=800,height=564"); 
	  }
	
	    NumOfAttempts = 0;
	    // conterra extension
	    // use this object instead of the simple function call, as the args param could not used with an identity token
	    mArcExplorerOpenTestChecker = new ArcExplorerOpen(sServer, sService, sServiceType, false, sUUID, sArgs);
	    // old version follows here
	    //timerId = setInterval('checkArcExplorerOpened("' + sServer + '", "' + sService + '", "' + sServiceType + '", false, "' + sUUID + '", "' + sArgs + '")', 100);
	    timerId = setInterval('mArcExplorerOpenTestChecker.check()', 100);
    }
  else
  {
	  alert('The Map Viewer is already open.');
  }
}

/**
 * This is a conterra extension. It has been necessary to create this function/object because the original call to checkArcExplorerOpened could not handle very large strings with line wraps (issue: dynamic evaluation inside of the timer).
 * @param sServer
 * @param sService
 * @param sServiceType
 * @param isDefault
 * @param sUUID
 * @param sArgs
 */
function ArcExplorerOpen (sServer, sService, sServiceType, isDefault, sUUID, sArgs) {
	//alert(sServer+"\n"+ sService+"\n"+ sServiceType+"\n"+ isDefault+"\n"+ sUUID+"\n"+ sArgs);
	this._server = sServer;
	this._service = sService;
	this._serviceType = sServiceType;
	this._default = isDefault;
	this._UUID = sUUID;
	this._args = sArgs;
	this.check = function() {
		checkArcExplorerOpened(this._server, this._service, this._serviceType, this._default, this._UUID, this._args);
	}
}


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,resizable=yes,status=yes,width=1024,height=768,left=5,top=5";
   else if (!pIsWin && pIsNS)
     sInfo = "toolbar=no,resizable=yes,status=yes,width=1024,height=768,screenX=5,screenY=5";
   else if (!pIsWin && pIsIE)
     sInfo = "toolbar=no,resizable=yes,status=yes,width=784,height=610,left=5,top=5";

   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=/";
}
