/*
* 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";

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);
}


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 = '';

//kmp - added status
  if (pIsWin)
    ArcExplorerWin = window.open('', windowName, "toolbar=no,resizable=yes,width=800,height=564,left=5,top=5,status=1");
  else if (!pIsWin && pIsNS)
    ArcExplorerWin = window.open('', windowName, "toolbar=no,resizable=yes,width=800,height=564,screenX=5,screenY=5,status=1");
  else if (!pIsWin && pIsIE)
    ArcExplorerWin = window.open('', windowName, "toolbar=no,resizable=yes,width=784,height=548,left=5,top=5,status=1");
  else 
  	ArcExplorerWin = window.open('', windowName, "toolbar=no,resizable=yes,width=800,height=564,status=1");

  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 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=/";
}
