// JScript File

//Global variables
var K_TagError = '<error>';
var K_TagInfo = '<info>'; 

var K_ItemSep = 'ZYAMP';   //..ItemSeperator.
var K_KVSep = 'ZYEQ';      //..Key/Value seperator
var K_AT = '@';            //..ItemSep.
var K_PP = '|';            //..Rec sep.
var K_Sep2= '~'; 
            //..First level seperator on Multiple Stations Selection. CheckAvailability. 
var winMultiple;
var winDataCart;
var winDownload;
var winChart;
var DDWin;

var ActiveNetworkName;

var iDiffX = 0;
var iDiffY = 0;

var iShowMsgDiffX = 0;
var iShowMsgDiffY = 0;

var tsDiffX =0;
var tsDiffY =0;

var hspc = 0;
var vspc = 0;
var mouseX=0;
var mouseY=0;

var showWinFirst = true;
var originalDivHTML = "";
var calendarDivHTML = "";
var showMsgDivHTML = "";
var DivID = "";
var over = false;
var _result=null;
var stationFeedIntevalId = "";

var _stationId;

// current station id
var currentStationId;

// variable that will be populated by results from callback
var siteInfoData = "";

var siteAvailabilityMsg;

var varFound = -1;

// array of site codes that match selected variable
var matchingVariableSiteCodes;

// //varcode~begDate~endDate~siteCode1|siteCode2|siteCode3|
var matchingVariableSiteInfo;

//array of variables for multiple stations
var siteVarArrayM;

// array of variables
var siteVarArray;
// array of matching variables in intellisense.
var siteVarArrayMatch;

// array with new and old indexes of variables in intellisense.
var matchingListRaw="";

var matchingListRawM="";

var idWin,printWin,helpWin,nwisWin;
var sessionId;

// list of variables in MultiSelect.aspx form
var vaiableList;


function showDataDownloadCartPage(rtnUrl) {
  var today = new Date();
  var rand = today.getTime();
  var winId = "DCartWindow_" + sessionId;
  var url = "DownloadCart.aspx";
  if(DDWin){
    DDWin.close();
  }
  DDWin = window.open(url, winId, "toolbar=0,location=0,directiories=0,menubar=0,scrollbars=0,resizable=0,status=1,height=50,width=200");
  //DDWin = OpenWin(url, winId, 250, 700);
  return false;
}

function showDataDownloadPage(rtnUrl) {
  var today = new Date();
  var rand = today.getTime();
  var winId = "DWindow_" + sessionId;
  var url = "DownloadDB.aspx";
  if(DDWin){
    DDwin.close();
  }
  DDWin = window.open(url, winId, "toolbar=0,location=0,directiories=0,menubar=0,scrollbars=0,resizable=0,status=1,height=50,width=200");
  //DDWin = OpenWin(url, winId, 250, 700);
  return false;
}

function doDownload(_count){	   
  var today = new Date();
  var rand = today.getTime();
  var winId = "DDWindow_" + sessionId;
  var url = "DownloadCSV.aspx?valueCount=" + _count;
  if(winDownload){
    winDownload.close();
  }
  winDownload = window.open(url, winId, "toolbar=0,location=0,directiories=0,menubar=0,scrollbars=0,resizable=0,status=1,height=40,width=300");
  //DDWin = OpenWin(url, winId, 250, 700);
  return false;
} 

function LoadVariable2List(mArray, ListName){
  var ddlList = document.getElementById(ListName);
  var varName;
  var varCode;
  var oVM;
  ddlList.options.length=0;
  for(i=0;i<mArray.length;i++){
    oVM=mArray[i];
    varCode = oVM.siteVarCode;
    varName = oVM.siteVarName;
    ddlList.options[i]=new Option(varName, varCode, false, false);
    //ddlList.options[i].title = varName;
  }
  window.clearTimeout(variableLadTimeOutId);
  return false;
}
function loadVariableDDList(matchVarList_) {
  var matchVarListArr_ = matchVarList_.split(K_PP);     
  if (matchVarListArr_!=null && matchVarListArr_.length >0 ) {
    // document.form2.ddlVariables.options.length=0;
    for (i=0; i < matchVarListArr_.length -1; i++ ) {
    var matchVarArr_ = matchVarListArr_[i];  
    var variableArr =  matchVarArr_.split(K_Sep2);
    var count3 = parseInt(variableArr[0]);
    var siteVarCodeMLocal = variableArr[1];
    var siteVarNameMLocal = variableArr[2];
    document.form2.ddlVariables.options[count3]=new Option(siteVarNameMLocal, siteVarCodeMLocal, false, false);
    document.form2.ddlVariables.options[count3].title = siteVarNameMLocal;
    }      
  }
  window.clearTimeout(variableLadTimeOutId);
  return false;
}
	  		  
function selectVarMatch(_varNameIdd) {
  var selectIdx;       
  var selectIdxArray;
  var matchIndex;
    // matchingListRaw= 0#2#Var1 |  1#5#Var2 |
  if (matchingListRaw !=null && matchingListRaw.length >0) { 
    var matchingListArray = matchingListRaw.split(K_PP);
    for (i=0;i < matchingListArray.length-1;i++) {
    //  matchingListArray[0] = 0#2#Var1 
        selectIdxArray = matchingListArray[i].split("#");
        selectIdx = selectIdxArray[0];
        if (selectIdx == _varNameIdd) {
          matchIndex = selectIdxArray[1];
        }
    }
  //  alert(matchIndex);
  // tokenizer datetime YYYY-MM-DDTHH:MM:SS  -->  YYYY-MM-DD   and  HH  MM  for display
     //document.getElementById('StartDate').value = siteVarArray[matchIndex].siteVarStartDt;
    if (matchIndex!=undefined ) {
        var _dtTimeRaw1 = siteVarArray[matchIndex].siteVarStartDt;         
        var  _dtVal1="";
        if (_dtTimeRaw1!=null  && _dtTimeRaw1.length > 0)  {
          if (_dtTimeRaw1 == "P31D") {
               var today = new Date();
               var month = today.getMonth()+1;
               var year = today.getYear();
               var day = today.getDate();
               if(day<10) day = "0" + day;
               if(month<10) month= "0" + month ;
               if(year<1000) year+=1900;
          
               document.getElementById('StartDate').value = year + "-" +  month + "-" + day;
           } else {
               var _dtTimeArr1 = _dtTimeRaw1.split("T");
               _dtVal1 = _dtTimeArr1[0]; // YYYY-MM-DD
               //var _timeVal1 =_dtTimeArr1[1]; // HH:MM:SS
               document.getElementById('StartDate').value = _dtVal1;
               
               // modified 9:40 AM 3/21/2007
               //var _timeValArr1 = _timeVal1.split(":");
               //var _timeHr1 = _timeValArr1[0];
               //var _timeMin1 = _timeValArr1[1];
               
               //var startHr =  document.getElementById('startHour');
               //var startMin =  document.getElementById('startMin');
               //startHr.options.value = _timeHr1;
               //startMin.options.value = _timeMin1;
          }
        }
   
      // document.getElementById('EndDate').value = siteVarArray[matchIndex].siteVarEndDt;
       var _dtTimeRaw2 =  siteVarArray[matchIndex].siteVarEndDt;
         if (_dtTimeRaw2!=null  && _dtTimeRaw2.length > 0)  {
           if (_dtTimeRaw2 == "P31D") {
                   var today = new Date();
                   var month = today.getMonth()+1;
                   var year = today.getYear();
                    var day = today.getDate();
                    if(day<10) day = "0" + day;
                    if(month<10) month= "0" + month ;
                    if(year<1000) year+=1900;
                document.getElementById('EndDate').value = year + "-" +  month + "-" + day;
           } else {
          
            var _dtTimeArr2 = _dtTimeRaw2.split("T");
            var  _dtVal2 = _dtTimeArr2[0]; // YYYY-MM-DD
            //var _timeVal2 =_dtTimeArr2[1]; // HH:MM:SS
            document.getElementById('EndDate').value = _dtVal2;
           //modified 9:40 AM 3/21/2007
            //var _timeValArr2 = _timeVal2.split(":");
           // var _timeHr2 = _timeValArr2[0];
           // var _timeMin2 = _timeValArr2[1];
            
           // var  endHr =  document.getElementById('endHour');
           // var  endMin =  document.getElementById('endMin');
           // endHr.options.value = _timeHr2;
           // endMin.options.value = _timeMin2;
          }
        }else{
          document.getElementById('EndDate').value = _dtVal1;
        }
       //document.getElementById('stationVariable').value = siteVarArray[matchIndex].siteVarName;
       document.getElementById('varCodeHidden').value = siteVarArray[matchIndex].siteVarCode;
       document.getElementById('valueCount').value = siteVarArray[matchIndex].siteVarObCount;
       document.getElementById('stationId').value = currentStationId;
       document.getElementById('stationIdHidden').value =currentStationId;
       SetStatusMsg("["+ siteVarArray[matchIndex].siteVarCode+"] "+siteVarArray[matchIndex].siteVarName);
      }
    }
 }   

//siteVarArray-array containing the strings to be filtered using RegExp
//sKey-string used to construct RegExp
//targetID-ID of the control to send the selected strings (strings passing the RegExp)
//number of chars of the sKey before the function start to act. eg nKey=2, start to filter only when sKey.length > 2
//showAll-if to show all values in siteVarArray when blank or invalid key "[\\^$.|?*+()", is entered 
//Script2Run - name of the script to run when done searching, enter blank if nothing needs to run. otherwise, enter something like 'selectVarMatch(0)'
//bMakeMatchingList - true, construct MatchingListRaw, else not. rec delimited by "|", fld delimited by "#".
//  format of MatchingListRaw=count + "#" + vId + "#" + variableStr + "|" . eg, "0#0#Discharge, cubic feet per second|"
function getMatchingList3(siteVarArray, sKey, targetID, nKeys, showAll, Script2Run, bMakeMatchingList){
  var _userInput = sKey;
  var nLength=sKey.length;
  if((siteVarArray.length > 2000) && (showAll==true)){
    showAll=false;
  }
  //ShowLoading(true);
  if((nLength>=nKeys) || (nLength==0)){
    var displayStr = ""; 
    var _input2 = ""
    var displayStrArrayRaw="";
    var displayStrArrayData = "";
    var displayStrArray = "";
    var variableStr = ""; 
    var matchingListData;
    var matchingListArray;
    var  myArray;
    var re1;  // = '^(' +_userInput+ ')';
    var re2;  // = new RegExp(re1 ,"i");
    var count = -1;
    var selectMatch = document.getElementById(targetID);  
    var vId;
    var variableCode;
    var bCharOk=true;

    selectMatch.options.length=0;
    if(nLength>0){
      bCharOk=(!IsRegExpChar(_userInput));
      if(bCharOk){
        re1= '^(' +_userInput+ ')';
        re2= new RegExp(re1 ,"i");
      }
    }
    
    //..Replacing the old code/logic listed after this block below
    if(siteVarArray!=undefined){
      SetStatusMsg("Searching variables whose name starts with "+_userInput);
      for(i=0;i<siteVarArray.length;i++){  
        if(siteVarArray[i]!=null){
          variableStr = siteVarArray[i].siteVarName;
          vId=siteVarArray[i].id;
          variableCode = siteVarArray[i].siteVarCode;
          if((nLength>0) && (bCharOk==true)){
            myArray = variableStr.match(re2);
          } 
          if(((nLength==0) && (showAll==true)) || ((bCharOk==false) && (showAll==true)) || ((myArray !=null) && (myArray.length>0))){
            count = count + 1;
            selectMatch.options[count]=new Option(variableStr, variableCode, false, false);
            selectMatch.options[count].title = variableStr;
            if(bMakeMatchingList==true){
              matchingListRaw += count + "#" + vId + "#" + variableStr + K_PP; 
            }
          }  
        }
      }
      if((Script2Run.length>0) && (count>=0)){
        eval(Script2Run);
      }
      SetStatusMsg(selectMatch.options.length + " of " +siteVarArray.length + " variable(s) returned.");    
    }
  }
}		  



function loadVariablesM(){
var master=document.form2.ddlVariables;
var variableInfo_ = "";
for (i=0; i<master.options.length; i++){
   var _varName = master.options[i].text;
   var _varCode = master.options[i].value;
   variableInfo_ += _varCode + K_Sep2 + _varName + K_PP;
}
InitVariableInfoM(variableInfo_);
}


function InitMatchingSiteInfo(siteInfoRawData) {
//network~varcode~varname~begDate~endDate~siteCode1@name1@count1|siteCode2@name2@count2|siteCode3@name3@count3
  var matchSiteInfoArrayData = siteInfoRawData.split(K_Sep2);
 //var _varCode = matchSiteInfoArrayData[0];
 var  _beginDate = matchSiteInfoArrayData[3];
 var _endDate = matchSiteInfoArrayData[4];
 matchingVariableSiteCodes = matchSiteInfoArrayData[5];
 
 document.getElementById('startDateM').value = _beginDate;
 document.getElementById('endDateM').value = _endDate;
}


function InitVariableInfo(siteVarRawData){
  // alert("rawdata: "+ siteVarRawData);
  //00060,cubic feet per second,9131,1958-10-01T00:00:00,1983-09-30T00:00:00,1983-09-30T00:00:00|
  var siteVarArrayData = siteVarRawData.split(K_PP);
  var baseData;  
  var ik=0; 
  siteVarArray = new Array(siteVarArrayData.length-1);
  for(k=0; k < siteVarArrayData.length-1; k++) {
    baseData = siteVarArrayData[k].split(K_Sep2);
    if(baseData.length>=5){
      siteVarArray[ik] = new VariableInfo(siteVarArrayData[k],ik);
      ik++;      
      //siteVarArray[k] = new VariableInfo(siteVarArrayData[k],k);
    }
  }
  SetStatusMsg(ik + " variable(s) returned.");
  //SetStatusMsg(siteVarArray.length + " variable(s) returned.");
}

function InitVariableInfoM(siteRawDataM) {
  var siteVarArrayDataM = siteRawDataM.split(K_PP);
  siteVarArrayM = new Array(siteVarArrayDataM.length);
  for(k=0; k < siteVarArrayDataM.length; k++) {
    // alert(siteVarArrayData[k]);
    siteVarArrayM[k] = new VariableInfoM(siteVarArrayDataM[k],k);
  } 
  SetStatusMsg(siteVarArrayM.length + " variable(s) returned."); 
}

function VariableInfoM(basedataM,nIdM) {
  this.idM = parseInt(nIdM);
  var _baseDataM = basedataM.split(K_Sep2);
  this.siteVarCode = _baseDataM[0];
  this.siteVarName = _baseDataM[1];
  this.id=nIdM;
}

function VariableInfo(basedata, nId) {
    //alert("basedata : " + basedata);
   var baseData = basedata.split(K_Sep2);
   this.id = parseInt(nId);
   this.siteVarCode =  baseData[0];
   this.siteVarName = baseData[1]  ;
   this.siteVarObCount=parseInt(baseData[2]);
   this.siteVarStartDt= baseData[3];
   this.siteVarEndDt= baseData[4];

}

//function selectVariableM(variableTextM) {

//}

function getMatchingListMultiple() {
  var _userInput = document.getElementById('stationVariableM').value;         
  var displayStr = ""; 
  //alert("input : "+ _userInput);
  var _input2 = ""
  var displayStrArrayRaw="";
  var displayStrArrayData = "";
  var displayStrArray = "";
  var variableStr = ""; 
  var matchingListData;
  var matchingListArray;
  var  myArray;
  var re1 = '^(' +_userInput+ ')';
  var  re2  = new  RegExp(re1 ,"i");
  var count2 = -1;
  document.form2.ddlVariables.options.length=0;                         
  for (i=0; i < siteVarArrayM.length;i++) {
    var idMLocal = siteVarArrayM[i].idM;
    var siteVarNameMLocal = siteVarArrayM[i].varNameM;
    var siteVarCodeMLocal = siteVarArrayM[i].varCodeM;
    myArray = siteVarNameMLocal.match(re2);
    if(myArray !=null && myArray.length>0){
      count2 = count2 + 1;
      document.form2.ddlVariables.options[count2]=new Option(siteVarNameMLocal, siteVarCodeMLocal, false, false);
      document.form2.ddlVariables.options[count2].title = siteVarNameMLocal;
      matchingListRawM += count2 + "#" + idMLocal + "#" + siteVarNameMLocal + K_PP; 
    } // if
  } //for 
}
   
   


function displayFloatingDiv(divId, title, width, height, left, top, res) 
{
  DivID = divId;
  document.getElementById(divId).style.width = width + 'px';
  document.getElementById(divId).style.height = height + 'px'
  pwindow = document.getElementById(divId);

  if(pwindow!=undefined){
    if(pwindow.style.visibility=='visible'){
      showWinFirst=false;
      pwindow.style.left=0 + 'px';
      pwindow.style.top=0 + 'px';
    }
  }
  //left:300px; top:320px
  if (showWinFirst) {
    //document.getElementById(divId).style.left = 200 + 'px'; // mouseX - 250+ 'px';
    //document.getElementById(divId).style.top =350 + 'px' ; // mouseY + 100+ 'px';
    showWinFirst=false;
  }
//document.getElementById('stationVariable').value = res;

 
var addHeader;
var NetworkInfo;
if (originalDivHTML == "")
  originalDivHTML = document.getElementById(divId).innerHTML;
  //addHeader = '<table style="width:' + width + 'px" class="floatingHeader">' +
  //            '<tr><td ondblclick="void(0);" onmouseover="over=true;" onmousedown="dragVarFormDivStart(event)" onmouseout="over=false;" style="cursor:move;height:18px">' + siteNetworkStr + " " + title + '</td>' + 
  //            '<td style="width:18px" align="right"><a href="javascript:hiddenFloatingDiv(\'' + divId + '\');void(0);">' + 
  //            '<img alt="Close..." title="Close..." src="Images/close.jpg" border="0"></a></td></tr></table>';
    // add to your div an header	
  NetworkInfo = "<Center><font Color=blue bold=true>"+siteNetworkStr + " Network </font></Center>";
  document.getElementById(divId).innerHTML = NetworkInfo+' '+originalDivHTML;
  document.getElementById('stationId').value = currentStationId;
  document.getElementById('stationName').value = siteNameStr;
  document.getElementById('network').value = siteNetworkStr;
  document.getElementById(divId).style.visibility = "visible";
}

function hiddenFloatingDiv(divId) 
{
  document.getElementById(divId).innerHTML = originalDivHTML;
  document.getElementById(divId).style.visibility='hidden';	
  DivID = "";
}

function displayWindow(_siteVars)  {
  var w, h, l, t;
  w = 240;
  h = 180;
  l = screen.width/8;
  t = screen.height/8;	         
  if (siteInfoData !=null && siteInfoData.length >0) {
    if (siteInfoData.indexOf(K_TagError) > -1) {
      alert(siteInfoData);
    }else {
      //alert(siteInfoData);
      var cbSiteInfoStr = siteInfoData.split("#");
      var siteNameRawArray = cbSiteInfoStr[0];
      
     var siteNameStrArray = siteNameRawArray.split("$");
      siteNameStr = siteNameStrArray[0];
      siteNetworkStr = siteNameStrArray[1];
      _stationId = siteNameStrArray[2];
      //alert(siteNameStr); alert(siteNetworkStr);
      groupNameStr = cbSiteInfoStr[1];
      if (siteNameStr !=null && siteNameStr.length >0) {
        //alert(siteNameStr);
        document.getElementById('stationName').value = siteNameStr;
        document.getElementById('stationId').value = _stationId;   
        currentStationId = _stationId;                                                                      
        var siteVarArrayRawData =  cbSiteInfoStr[1];                                     
        InitVariableInfo(siteVarArrayRawData); 
        //alert(document.getElementById('windowcontent').style.visibility);
        displayFloatingDiv('windowcontent', 'Site Variables Select', w, h, l, t,siteVarArray);
      } //end if       
    } //end if
  } //end if    
         
} // end function


function GetSiteInfo(siteCode,network) {
 // alert(stationId + "," + network)
 currentStationId = siteCode;
  //document.getElementById('loadingDiv').style.visibility = "visible";
  //var fpBody = document.getElementById('SiteSelect_Panel');
  //var html = fpBody.innerHTML;
  //fpBody.innerHTML = "<div><img src='images/callbackActivityIndicator.gif' align='middle'/> Getting Information. . .</div>" ;
  showFloatingPanel('SiteSelect_Panel'); 
  // send callback request for siteInfo
  SetStatusMsg( "Requesting site information") ;
  TriggerCallback("SiteInfo","ControlType=CUAHSI&EventArg=getSiteInfo&EventVal=" + siteCode + ","+ network);
  //cbGetSiteInfo("ControlType=CUAHSI&EventArg=getSiteInfo&EventVal=" + siteCode + ","+ network ,"SiteInfo");
}

function addToCartMultiple() {
//network~varcode~varname~begDate~endDate~siteCode1@name1@count1|siteCode2@name2@count2|siteCode3@name3@count3
  if(matchingVariableSiteInfo==null){
    ShowMsg("Run [Check Availability] function first.");
  }else{
    var varSiteInfoArr = matchingVariableSiteInfo.split(K_Sep2);
    if(varSiteInfoArr.length!=6){
      ShowMsg("Incorrect: matchingVariableSiteInfo\n" + matchingVariableSiteInfo);
    }else{
      var network = varSiteInfoArr[0];  
      var varCode = varSiteInfoArr[1];   
      var varName = varSiteInfoArr[2];
      var begDtM1 =  varSiteInfoArr[3];   
      var endDtM1 = varSiteInfoArr[4];
      var endInfo =varSiteInfoArr[5];
      
      var begDtM = document.getElementById('startDateM').value;
      var endDtM = document.getElementById('endDateM').value;
      var finalBegDt =begDtM;
      var finalEndDt = endDtM;

//      var startT1 = "T" + document.form2.startHourM.options.value + ":"+ document.form2.startMinM.options.value + ":00";
//      
//      //input date  / or -
//      var finalBegDt ="";
//      if (begDtM.indexOf("/") > -1) {
//         // mm/dd/yyyy  ->  to yyyy-mm-dd
//          var begDtArr = begDtM.split("/")
//          var begDtmm = begDtArr[0];    var begDtdd = begDtArr[1]; var begDtyy = begDtArr[2];
//          if (begDtmm.length <2) {
//           begDtmm = "0" + begDtmm;  }
//          if (begDtdd.length <2) {
//           begDtdd = "0" + begDtdd;
//          }
//          finalBegDt = begDtyy + "-" + begDtmm + "-" + begDtdd + startT1;
//         
//      }else {  //  yyyy-mm-dd format
//       // check for single digit days and months
//       var begDtArr2 =  begDtM.split("-");
//        var begDtmm2 = begDtArr2[0];    var begDtdd2 = begDtArr2[1]; var begDtyy2 = begDtArr2[2];
//          if (begDtmm2.length <2) {
//           begDtmm2 = "0" + begDtmm2;  }
//          if (begDtdd2.length <2) {
//           begDtdd2 = "0" + begDtdd2;
//          }
//          finalBegDt = begDtyy2 + "-" + begDtmm2 + "-" + begDtdd2 + startT1;
//      }
      
//      var finalEndDt = "";
//      var endT1 = "T" + document.form2.endHourM.options.value + ":"+ document.form2.endMinM.options.value + ":00";
//      // same procedure for end date
//      if (endDtM.indexOf("/") >-1)  {
//      
//      var endDtArr = endDtM.split("/");
//      var endDtmm = endDtArr[0]; var endDtdd =endDtArr[1]; var endDtyy = endDtArr[2];
//      
//         if (endDtmm.length <2) { 
//         endDtmm = "0" + endDtmm;   }
//         
//         if (endDtdd.length <2) {
//           endDtdd = "0" + endDtdd; }
//           
//           finalEndDt = endDtyy + "-" + endDtmm + "-" + endDtdd + endT1;
//         
//      } else { 
//        var endDtArr2 = endDtM.split("-");
//         var endDtmm2 = endDtArr2[0]; var endDtdd2 =endDtArr2[1]; var endDtyy2 = endDtArr2[2];
//      
//         if (endDtmm2.length <2) { 
//         endDtmm2 = "0" + endDtmm2;   }
//         
//         if (endDtdd2.length <2) {
//           endDtdd2 = "0" + endDtdd2; }
//         finalEndDt =   endDtyy2 + "-" + endDtmm2 + "-" + endDtdd2 + endT1;
//      }
      
      // reconstruct input string
      //network~varcode~varname~begDate~endDate~siteCode1@name1@count1|siteCode2@name2@count2|siteCode3@name3@count3
      var add2CartStr = network + K_Sep2 + varCode + K_Sep2 + varName + K_Sep2 +  finalBegDt + K_Sep2 + finalEndDt + K_Sep2 + endInfo;
      TriggerCallback("AddToCartMultiple","ControlType=CUAHSI&EventArg=addToCartMultiple&EventVal=" + add2CartStr);
      //cbAddToCartMultiple("ControlType=CUAHSI&EventArg=addToCartMultiple&EventVal=" + add2CartStr, "AddToCartMultiple");     
    }  //if(varSiteInfoArr.length!=6
  }  //if(matchingVariableSiteInfo==null)
}

function addToCart() {
  var bOk = VariableCodeSelected();
  if(bOk==true){
    var oSelect = document.getElementById('match');
    var  _siteName = document.getElementById('stationName').value;
    var  _siteCode  = document.getElementById('stationId').value;
    var _varCode = oSelect.value;   //document.getElementById('varCodeHidden').value;
    var _varName = GetSelectedText(oSelect);
    var _valueCount = document.getElementById('valueCount').value;
    var dtRaw1 =  document.getElementById('StartDate').value;
    var _varStartDt = dtRaw1;
    //var dtArrray = dtRaw1.split("-");
    //var dt1MM = dtArrray[1];  var dt1DD = dtArrray[2]; var dt1YY= dtArrray[0];

    //if (dt1MM !=null && dt1MM.length <2) {
    //dt1MM = "0" + dt1MM;  //append zero
    //}

    //if (dt1DD != null  && dt1DD.length < 2) {
    //    dt1DD = "0" + dt1DD;
    //}
    //var dt1Final = dt1YY + "-" + dt1MM + "-" + dt1DD;
    //var startHr_ = document.getElementById('startHour');
    //var startMin_ = document.getElementById('startMin');
    //var dtStr1 =dt1Final + "T" + startHr_.options.value + ":"+ startMin_.options.value + ":00";
    //var _varStartDt = dtStr1;

    var dtRaw2 = document.getElementById('EndDate').value; 
    var _varEndDt = dtRaw2;
    
    //var dt2Array = dtRaw2.split("-");
    //var dt2MM = dt2Array[1]; var dt2DD = dt2Array[2]; var dt2YY = dt2Array[0];

    //if (dt2MM !=null && dt2MM.length < 2) {
    //  dt2MM = "0" + dt2MM;
    //}

    //if (dt2DD!=null && dt2DD.length < 2) {
    //dt2DD = "0" + dt2DD;
    //}

    //var dt2Final = dt2YY + "-" +  dt2MM + "-" + dt2DD;
    //var endHr_ = document.getElementById('endHour');
    //var endMin_ =  document.getElementById('endMin');
    //var dtStr2 = dt2Final + "T" + endHr_.options.value + ":"+ endMin_.options.value + ":00";
    //var _varEndDt = dtStr2;
    var _network = document.getElementById('network').value;
    ShowLoadingActivity('activityImg',true);
    //document.getElementById('activityImg').style.visibility = "visible";
    TriggerCallback("AddToCart","ControlType=CUAHSI&EventArg=addToCart&EventVal="+_siteCode+K_Sep2+_siteName+K_Sep2+_varName+K_Sep2+_varCode +K_Sep2+ _varStartDt +K_Sep2+ _varEndDt +K_Sep2+ _network + K_Sep2 + _valueCount);
    //cbAddToCart("ControlType=CUAHSI&EventArg=addToCart&EventVal="+_siteCode+"~"+_siteName+"~"+_varName+"~"+_varCode +"~"+ _varStartDt +"~"+ _varEndDt +"~"+ _network + "~" + _valueCount,"AddToCart");   
  }
}

function showChartInfoPage(numOfRecs) {
  var today = new Date();
  var rand = today.getTime();
  var winId = "ChartInfo" + sessionId;
  var url = "Plot.aspx?numofRecs="+ numOfRecs;
   //var idWin = window.open(url,"","width=600,height=450,status=0");
  if(winChart!=null){
    winChart.close();
  }
  winChart = window.open(url,winId,"height=500,width=785,location=no,toolbar=no,menubar=no,resizable=no,status=yes,scrollbars=no"); 
  return  false;
}

function ShowCartM(){
  showCartInfo();
}
function showCartInfo() {
   var today = new Date();
   var rand = today.getTime();
   var winId = "DataDownloadList"  + sessionId;
   var url = "Cart.aspx";
   //var idWin = window.open(url,"","width=600,height=450,status=1");
   if(winDataCart!=null){
     winDataCart.close();
   }
   winDataCart = window.open(url, winId,"height=350,width=1100,location=no,toolbar=no,menubar=no,resizable=yes,scrollbars=no, status=1"); 
   return  false;
}


function getCSV() {
   var bOk = VariableCodeSelected();
   if(bOk==true){
     var tsInputInfo = "";
     var _network = document.getElementById('network').value;
     var _siteCode = document.getElementById('stationId').value
     var _varCode = document.getElementById('varCodeHidden').value;
     var _varStartDt = document.getElementById('StartDate').value;
     var _varEndDt = document.getElementById('EndDate').value;   
     var finalStDt = "";  var finalEndDt = ""; 
     if (_varStartDt != null && _varStartDt.length > 0) {
        var stDtArr = _varStartDt.split("-");
        var stDtyy = stDtArr[0];
        var stDtmm = stDtArr[1];  var stDtdd = stDtArr[2];
        if (stDtmm!=null &&  stDtmm.length <2)  stDtmm = "0" + stDtmm;
        if (stDtdd!= null && stDtdd.length <2) stDtdd = "0" + stDtdd;
        
        finalStDt = stDtyy + "-" + stDtmm + "-"+ stDtdd;
     }
       
     if (_varEndDt!=null && _varEndDt.length>0) {
       var endDtArr = _varEndDt.split("-");
       var endDtyy = endDtArr[0]; var endDtmm = endDtArr[1];  var endDtdd = endDtArr[2];
       if (endDtmm!=null && endDtmm.length <2)  endDtmm = "0" + endDtmm;
       if (endDtdd!= null && endDtdd.length<2) endDtdd = "0" + endDtdd;
       
       finalEndDt = endDtyy + "-" + endDtmm + "-"+ endDtdd;
     }
        
     tsInputInfo += _network + K_Sep2  + _siteCode + K_Sep2 + _varCode + K_Sep2 + finalStDt + K_Sep2 +  finalEndDt;
     ShowLoadingActivity('activityImg',true);
     //document.getElementById('activityImg').style.visibility = "visible" ;
     TriggerCallback("getCSV","ControlType=CUAHSI&EventArg=getCSV&EventVal="+tsInputInfo);
     //cbGetCSVInfo("ControlType=CUAHSI&EventArg=getCSV&EventVal="+tsInputInfo,"getCSV");     
   } 
}

function VariableCodeSelected(){
  var oMatch = document.getElementById('match');
  var _varCode = document.getElementById('varCodeHidden').value;
  var bOk=true;
  if((oMatch.value==-1) || (_varCode=='') || (oMatch.value=='')){
    ShowMsg("Please select a variable before continuing.");
    bOk=false;
  }
  return bOk;
}

function showCartInfoValue(cartResult,context) {
//  alert(cartResult);
}

function showCalender1() {
//alert('calendar');

	if (calendarDivHTML == "")
    calendarDivHTML = document.getElementById('calDiv1').innerHTML;

  var width = 191;
  var  calHeader = '<table style="width:' + width + 'px" class="floatingHeader">' +
              '<tr><td ondblclick="void(0);" onmouseover="over=true;" onmousedown="dragVarFormDivStart(event)" onmouseout="over=false;" style="cursor:move;height:18px">Check Variable</td>' + 
              '<td style="width:18px" align="right"><a href="javascript:hideCalendar();void(0);">' + 
              '<img alt="Close..." title="Close..." src="Images/close.jpg" border="0"></a></td></tr></table>';
  // add to your div an header	
  document.getElementById('calDiv1').innerHTML = calHeader + calendarDivHTML;
  document.getElementById('calDiv1').left = (mouseX + 191) + "px";
  document.getElementById('calDiv1').top = (mouseY - 168) + "px";
  document.getElementById('calDiv1').style.visibility = "visible" ;
}

function hideCalendar() {
  document.getElementById('calDiv1').style.visibility = "hidden" ;
}

function ActiveLayerUpdate(s){ 
  var  ss= "ControlType=CUAHSI&EventArg=ActiveLayer&EventVal=" + s;
  ActiveNetworkName=s;
  TriggerCallback('ActiveLayerUpdate',ss);
}

function ShowVariableStations(){
  //Showing the stations with the selected variable.
  if(matchingVariableSiteInfo==null){
    ShowMsg("Run [Check Availability] function first.");
  }else{
    var varSiteInfoArr = matchingVariableSiteInfo.split(K_Sep2);
    if(varSiteInfoArr.length!=6){
      ShowMsg("Incorrect: matchingVariableSiteInfo\n" + matchingVariableSiteInfo);
    }else{
      var vStations =varSiteInfoArr[5];
      var ss="ControlType=CUAHSI&EventArg=ShowStationsWithVariable&EventVal="+vStations; 
      if(opener){
        opener.TriggerCallback('ShowVariableStations',ss);
      }  
    }  
  } 
}
function  getSelectedStations() {
  //alert("getSelectedStations");
  cbGetSelectedStations("ControlType=CUAHSI&EventArg=getSelectedStations","getSelectedStations")
}

function drawPreviousSelectedExtent() {
  cbDrawPreviewSelectedExtent("ControlType=CUAHSI&EventArg=PreviousSelectedExtent","PreviousSelectedExtent");
}

function ClearSelection() {
  var i = confirm("Confirm to clear the selected features (apply to all layers)");
  if(i==true){
    TriggerCallback("ClearSelection","ControlType=CUAHSI&EventArg=ClearSelection");
  }  
}

function ToggleSelection(){
  TriggerCallback("ToggleSelection","ControlType=CUAHSI&EventArg=ToggleSelection");
}

function checkAvailability(selectedVariableCode) {
  ShowLoading(true);
  hideShowMsg();
  TriggerCallback("CheckAvailability","ControlType=CUAHSI&EventArg=CheckAvailability&EventVal=" +  selectedVariableCode);
}

function showChart() {
  var bOk = VariableCodeSelected();
  if(bOk==true){
    var chartInputInfo = "";
    var _network = document.getElementById('network').value;
    var _siteCode = document.getElementById('stationIdHidden').value
    var _varCode = document.getElementById('varCodeHidden').value;
    //YYYY-MM-DD
    var _varStartDt = document.getElementById('StartDate').value;
    var _varEndDt = document.getElementById('EndDate').value;
    var finalStDt = "";  var finalEndDt = "";
    if (_varStartDt != null && _varStartDt.length > 0) {
      var stDtArr = _varStartDt.split("-");
      var stDtyy = stDtArr[0];
      var stDtmm = stDtArr[1];  var stDtdd = stDtArr[2];
      if (stDtmm!=null &&  stDtmm.length <2)  stDtmm = "0" + stDtmm;
      if (stDtdd!= null && stDtdd.length <2) stDtdd = "0" + stDtdd;    
      finalStDt = stDtyy + "-" + stDtmm + "-"+ stDtdd;
    }
    if (_varEndDt!=null && _varEndDt.length>0) {
      var endDtArr = _varEndDt.split("-");
      var endDtyy = endDtArr[0]; var endDtmm = endDtArr[1];  var endDtdd = endDtArr[2];
      if (endDtmm!=null && endDtmm.length <2)  endDtmm = "0" + endDtmm;
      if (endDtdd!= null && endDtdd.length<2) endDtdd = "0" + endDtdd;
      finalEndDt = endDtyy + "-" + endDtmm + "-"+ endDtdd;
    }
    var oChart=document.getElementById('ChartType');
    var iChart=1;
    if(oChart!=undefined){
      iChart=oChart.value;
    }
    chartInputInfo += _network+K_Sep2+_siteCode+K_Sep2+_varCode+K_Sep2+finalStDt+K_Sep2+finalEndDt+K_Sep2+iChart;
   
    ShowLoadingActivity('activityImg',true);
    //document.getElementById('activityImg').style.visibility = "visible"; 
    TriggerCallback("getChart","ControlType=CUAHSI&EventArg=getChart&EventVal="+chartInputInfo);
    //cbGetChart("ControlType=CUAHSI&EventArg=getChart&EventVal=" +  chartInputInfo,"getChart");  
  }
}


function ShowMultipleSelectForm(sMsg) {
  var today = new Date();
  var rand = today.getTime();
  var winId = "MutipleStationSelect" + sessionId;
  var url = "MultiSelect.aspx?Msg=" + sMsg;
  //var idWin = window.open(url,"","width=600,height=450,status=0");
  if(winMultiple!=null){
    winMultiple.close();
  }
  winMultiple = window.open(url,winId,"width=530,height=310,status=yes,scrollbars=no"); 
  return  false;
}

function ShowMultipleSelect() {
  TriggerCallback("ShowMultipleSelect","ControlType=CUAHSI&EventArg=ShowMultipleSelect&EventVal=ShowMultipleSelect");
  return  false;
}

function hideShowMsg() {
  document.getElementById('checkVariableDiv').style.visibility = "hidden" ;
}

function showMsgBox(msg_) {
  if (showMsgDivHTML == "")
    showMsgDivHTML = document.getElementById('checkVariableDiv').innerHTML;
  var width = 473;
  var  showMsgHeader = '<table style="width:' + width + 'px" class="floatingHeader">' +
            '<tr><td ondblclick="void(0);" onmouseover="over=true;"  onmouseout="over=false;" style="cursor:move;height:18px"></td>' + 
            '<td style="width:18px" align="right"><a href="javascript:hideShowMsg();void(0);">' + 
            '<img alt="Close..." title="Close..." src="Images/close.jpg" border="0"></a></td></tr></table>';

  // add to your div an header	
  document.getElementById('checkVariableDiv').innerHTML = showMsgHeader + showMsgDivHTML;
  document.getElementById('checkVariableDiv').style.left = 24 + "px";
  document.getElementById('checkVariableDiv').style.top = 230 + "px";
  document.getElementById('msg').value = msg_;
  document.getElementById('checkVariableDiv').style.visibility = "visible" ;
}



function populateKeywords() {
  if (document.form2.ddlVariables.options.length > 0) {
  }
}

//this function is replaced by getMatchingList3
//function getMatchingListMultipleCB() {
//  var _userInput = document.getElementById('stationVarName2').value;         
//  if (_userInput!=null && _userInput.length > 0) {
//  cbGetVariableList("ControlType=CUAHSI&EventArg=getVariableMatchList&EventVal=" +  _userInput,"GetVariableRequest");
//  }
  // else alert("Minimum 3 characters.");
//}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////
////  window dragging functions////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////



function dragShowMsgDivMove(e) {
  getImageXY(e);
  document.getElementById('checkVariableDiv').style.left = (mouseX-iShowMsgDiffX) + "px";
  document.getElementById('checkVariableDiv').style.top = (mouseY-iShowMsgDiffX) + "px";
  return false;
}

function dragShowMsgDivEnd(e) {
//	document.getElementById('windowcontent').onmousemove = null;
//	document.getElementById('windowcontent').onmouseup = null;

  document.onmousemove = null;
  document.onmouseup = null;
//  document.onmousemove = getImageXY;
  return false;
}

function dragShowMsgDivStart(e) {
  if(document.all) e = event;
    getImageXY(e);		
    document.onmousemove = dragShowMsgDivMove;
    document.onmouseup = dragShowMsgDivEnd;
    iShowMsgDiffX = event.clientX - document.getElementById('checkVariableDiv').offsetLeft;
    iShowMsgDiffY = event.clientY - document.getElementById('checkVariableDiv').offsetTop;
   return false;
}


function dragVarFormDivMove(e) {
  getImageXY(e);
  document.getElementById('windowcontent').style.left = (mouseX-iDiffX) + "px";
  document.getElementById('windowcontent').style.top = (mouseY-iDiffY) + "px";
  return false;
}

function dragVarFormDivEnd(e) {
//	document.getElementById('windowcontent').onmousemove = null;
//	document.getElementById('windowcontent').onmouseup = null;
  document.onmousemove = null;
  document.onmouseup = null;
//document.onmousemove = getImageXY;
  return false;
}

function dragVarFormDivStart(e) {
 if (document.all) e = event;
getImageXY(e);		
//document.getElementById('windowcontent').onmousemove = dragVarFormDivMove;
//document.getElementById('windowcontent').onmouseup = dragVarFormDivEnd;

document.onmousemove = dragVarFormDivMove;
  document.onmouseup = dragVarFormDivEnd;
  iDiffX = event.clientX - document.getElementById('windowcontent').offsetLeft;
  iDiffY = event.clientY - document.getElementById('windowcontent').offsetTop;
  return false;
}

function getImageXY(e) {
	mouseX=event.clientX + document.body.scrollLeft;
	mouseY=event.clientY + document.body.scrollTop;

// subtract offsets from page left and right
mouseX = mouseX-hspc ;
mouseY = mouseY-vspc;
	//window.status = mouseX+ "," + mouseY;
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
function TriggerCallback(ctx, msg){
  var loadingelem = document.getElementById('loadingDiv');
  if(loadingelem!=null){
    loadingelem.style.visibility = "visible";
  }

  switch (ctx) {
    case 'CB4RefreshMap':
       window.setTimeout("CB2Server('"+msg+"','"+ctx+"');",100);
       break;
    default:
       window.setTimeout("CB2Server('"+msg+"','"+ctx+"');",100);
       break;
   }
}

function HandleResponse(returnvalue, ctx){  
  ShowLoading(false);
  switch (ctx) {
   
    case 'DeleteFeatureNotConfirmed':
      if (IsDeleteConfirmed(returnvalue))
      {
          ctx = 'DeleteFeatureConfirmed';
          window.setTimeout("TriggerCallback('" + ctx + "', '" + returnvalue + "');", 1);
      }
      break;
    case 'ActiveLayerUpdate':
      //ActiveNetworkName=returnvalue;
      break;          
    case 'SiteInfo':
	    SetStatusMsg("Done");
      // process the response
      if (returnvalue!=null && returnvalue.length>0) {
         fpBody = document.getElementById('SiteSelect_Panel');
         if(FloatingPanels[fpBody.id].docked==true){
           if(IsFloatingPanelExpanded(fpBody.id)==false){
	           //toggleFloatingPanelState('HISIDResults','images/collapse.gif','images/expand.gif');
             undockFloatingPanel(fpBody.id);
             expandFloatingPanel(fpBody.id);
           }  
         }
         //showWinFirst=false;
         siteInfoData = returnvalue; //kvpairs[0];
         //showFloatingPanel('SiteSelect_Panel');
         displayWindow(returnvalue);
         var oTxt=document.getElementById('stationVariable');
//         if((oTxt!=undefined) && (oTxt.visible==true)){
//           oTxt.focus();
//         }
         window.setTimeout("getMatchingList3(siteVarArray,'','match',1,true,'selectVarMatch(0)',true);",1);
       } else alert("Error accessing data. Please try again later.");
       break;  
    case 'AddToCart':
      ShowLoadingActivity('activityImg',false);
      if((returnvalue!=undefined) && (returnvalue.length>0)){
        ShowMsg(returnvalue);
      }
      //document.getElementById('activityImg').style.visibility = "hidden";
      break;             
    case 'getCSV' :
      ShowLoadingActivity('activityImg',false);
      //document.getElementById('activityImg').style.visibility = "hidden";
      if(returnvalue.indexOf(K_TagError) > -1) {
        ShowMsg(returnvalue);
      } else {
         //document.getElementById('activityImg').style.visibility = "hidden";
         doDownload(returnvalue); 
      }          
      break;      
    //case 'getSelectedStations':
    //  break;        
    case 'PreviousSelectedExtent':
      break;    
//    case 'ClearSelection' :
//      break;    
    case 'GetVariableRequest' :
      if(returnvalue.indexOf(K_TagError) > -1) {
        alert(returnvalue);
      }else{
        //loadVariableDDList(returnvalue)
        variableLadTimeOutId =  window.setTimeout("loadVariableDDList('"+returnvalue+"');",10);
      }
      break;  
    case 'LoadVariablesM':
      if(returnvalue.indexOf(K_TagError) > -1) {
        ShowMsg(returnvalue);
      }else{
        InitVariableInfoM(returnvalue);
        window.setTimeout("getMatchingList3(siteVarArrayM,'','ddlVariables',1,true,'',false);",1);
        //variableLadTimeOutId =  window.setTimeout("LoadVariable2List(siteVarArrayM,'ddlVariables');",10);
        //alert("len="+returnvalue.length+" rec="+siteVarArrayM.length);
        //loadVariableDDList(returnvalue)
        //variableLadTimeOutId =  window.setTimeout("loadVariableDDList('"+returnvalue+"');",10);
      }
      break;    
    case 'CheckAvailability':
      if(returnvalue!=null){
        //var arr = StringSplit(returnvalue, '&');
        var arr = StringSplit(returnvalue, K_ItemSep);
        var action;
        var msg;
        var subarr;
        var element;
        for (element in arr) {
          //subarr = StringSplit(arr[element], "=");
          subarr = StringSplit(arr[element], K_KVSep);
          switch(subarr[0]) {
            case 'ShowMsg':
              ShowMsg(subarr[1]);
              //alert(subarr[1]);
              break;
            case 'Confirm':
              var startstr = "Confirm";
              var endstr = "EOCSign";
              var stemp = returnvalue.substr(returnvalue.indexOf(startstr)+startstr.length+1);
              stemp = stemp.substr(0, stemp.indexOf(endstr));
              ProcessConfirm(stemp);
              break;
            case 'CallAGSP':
              processCallbackResult(subarr[1]);
              break;  
            case 'DOEVAL' :
              eval(subarr[1]); 
              break;   
            case 'FUNCTIONRETURN':
              if((returnvalue.indexOf(K_TagError) > -1) || (returnvalue.indexOf(K_TagInfo)>-1)){
                ShowMsg(returnvalue);
              }else{
                // 2,5???network~varcode~begDate~endDate~siteCode1|siteCode2|siteCode3|
                returnvalue = subarr[1];
                var strOutputRaw = returnvalue.split("???");
                var stnCountArr = strOutputRaw[0].split(",");
                var totalCount = stnCountArr[1];
                if (totalCount == "0") { 
                  siteAvailabilityMsg =parseInt(stnCountArr[0]) +  " sites have the selected variable.";
                } else {
                  siteAvailabilityMsg =parseInt(stnCountArr[0]) + " out of " + parseInt(stnCountArr[1]) + " sites have the selected variable.";
                }
                matchingVariableSiteInfo = strOutputRaw[1]; // assign global variable
                InitMatchingSiteInfo(strOutputRaw[1]);
                showMsgBox(siteAvailabilityMsg);
                //alert (siteAvailabilityMsg);
              }            
              break;
            default:
              break;    
          }
        }
      }        
      break;         
    case 'getChart' : 
      ShowLoadingActivity('activityImg',false);
      if((returnvalue.indexOf(K_TagError) > -1) || (returnvalue.indexOf(K_TagInfo)>-1)){
        alert(returnvalue);
      }else{
        if(returnvalue==''){
          ShowMsg("No data to plot.");
        }else{
          showChartInfoPage(returnvalue);
        }
      }
      break;        
    //case 'AddToCartMultiple' : 
    //  break;       
    case 'downloadData2' :
      if((returnvalue.indexOf(K_TagError) > -1) || (returnvalue.indexOf(K_TagInfo)>-1)){
        alert(returnvalue);
      }else showDataDownloadPage(returnvalue);
        break;   
    case 'downloadCart' :
      if((returnvalue.indexOf(K_TagError) > -1) || (returnvalue.indexOf(K_TagInfo)>-1)){
        alert(returnvalue);
      } else    showDataDownloadCartPage(returnvalue);
      break;   
    case 'HISID':
      var fpBody = document.getElementById('HISIDResults_TaskResults2');
      fpBody.innerHTML = returnvalue;
      break;
    //case 'ShowMultipleSelect':
    //  ShowMultipleSelectForm();
    //  break;
    default:
      if(returnvalue!=null){
        //var arr = StringSplit(returnvalue, '&');
        var arr = StringSplit(returnvalue, K_ItemSep);
        var action;
        var msg;
        var subarr;
        var element;
        for (element in arr) {
          //subarr = StringSplit(arr[element], "=");
          subarr = StringSplit(arr[element], K_KVSep);
          switch(subarr[0]) {
            case 'ShowMsg':
              ShowMsg(subarr[1]);
              break;
            case 'Confirm':
              var startstr = "Confirm";
              var endstr = "EOCSign";
              var stemp = returnvalue.substr(returnvalue.indexOf(startstr)+startstr.length+1);
              stemp = stemp.substr(0, stemp.indexOf(endstr));
              ProcessConfirm(stemp);
              break;
            case 'DOEVAL':
              eval(subarr[1]); 
              break; 
            case 'CallAGSP':
              processCallbackResult(subarr[1]);
              break;
            //case 'ShowMultipleSelect':
            //  ShowMultipleSelectForm();
            //  break;      
            default:
              break;
          }
        }      
      }
      break;  
  }  //switch (ctx) {
}

function StringSplit(strValue, strSep){
	var strArray=strValue.split(strSep);
	return strArray;
}

function ProcessConfirm(sValue){
  // sValue has the format of message:eq:confirmed javascipt action:eq:unconfirmed javascript action
  // for example, sValue can be "Do you want to confirm this?:eq:alert('Confirmed');:eq:processNotConfirm('Not confirmed');
  var arr = StringSplit(sValue, ':eq:');
  if (confirm(arr[0])) {
    eval(arr[1]);
  }
  else {
    eval(arr[2]);
  }
}

function HIS_ID(divid) {
  map = Maps[divid];
  MapPoint(map.controlName, "MapIdentify", false);
  map.divObject.onmousedown = HIS_IDClick;
 }
 
function HIS_IDClick(e) {
  map.cursor = map.divObject.style.cursor;
  //map.divObject.style.cursor = "wait";
  getXY(e);
  var box = calcElementPosition(map.containerDivId);
  zleft = mouseX - box.left;
  ztop = mouseY - box.top;

  map.xMin=zleft;
  map.yMin=ztop;
  var div = document.getElementById("IdentifyLocation");
  if (div==null) {
      addIdentifyLocation();
  }
  map.getTopLeftTile();
  var fpBody = document.getElementById('HISIDResults_TaskResults2');
  var html = fpBody.innerHTML;
  fpBody.innerHTML = "<div><img src='images/callbackActivityIndicator.gif' align='middle'/> Getting Information. . .</div>" ;
  showFloatingPanel('HISIDResults');
  fpBody=document.getElementById('HISIDResults_BodyRow');
  if (fpBody.style.display=="none")
      toggleFloatingPanelState('HISIDResults','images/collapse.gif','images/expand.gif');
  //Need to change the message.  zye 
  var message = "ControlID=Map1&ControlType=CUAHSI&EventArg=HISID&Map1_mode=MapIdentify&minx=" + zleft + "&miny=" + ztop;
  var context = "HISID";   //map.controlName;
  eval(HISIDCallbackFunctionString);
  var div = document.getElementById("IdentifyLocation");
  // point is bottom center... 2 pixels up for shadow
  var cWidth = Math.floor(div.clientWidth / 2);
  var cHeight = div.clientHeight;
  //alert(cWidth + " x " + cHeight); // width and height might not be available on first time.... if so, approximate size needed
  if (cWidth==0) cWidth = 12;
  if (cHeight==0) cHeight = 29;
  var idLeft = zleft - parseInt(map.divObject.style.left) - cWidth;
  var idTop = ztop - parseInt(map.divObject.style.top) - cHeight + 2; // add two back for icon bottom
  //	if (isIE) {
  //	    idTop+=2; 
  //	    //idLeft+=2;
  //	}
  window.setTimeout('moveLayer("IdentifyLocation", ' + idLeft + ', ' + idTop + '); showLayer("IdentifyLocation");', 0);
  map.mode = map.tempMode;
  map.actionType = map.tempAction;
  map.cursor = map.tempCursor;
  //fpBody = document.getElementById('HISIDResults_TaskResults2');
  //var html = fpBody.innerHTML;
  //fpBody.innerHTML = "<div><A href='http://www.esri.com' align='middle'/> Completed. . .</div>"+html;
  return false;
}
//Chk to see if a char is one of 11 reserved chars of RegExp
  function IsRegExpChar(sToCheck){
    var bRet=false;
    var sValues = "[\\^$.|?*+()";
    var l = sToCheck.length;
    var s;
    if(l>0){
      for(i=0;i<l;i++){
        s=sToCheck.substr(i,1);
        if(sValues.indexOf(s)>=0){
          bRet=true;
          break;
        }
      } 
    }
    return bRet;
  }

  function LoadVariablesM(){
    if((ActiveNetworkName==undefined) || (ActiveNetworkName=='')){
      if(opener){
        ActiveNetworkName=opener.GetActiveNetworkName();
      }
    }
    //var ActiveNetwork = ActiveNetworkName;
    //if(opener){
    // ActiveNetwork=(opener.GetActiveNetwork());
    //}
    TriggerCallback('LoadVariablesM','ControlType=CUAHSI&EventArg=LoadVariablesM&EventVal=' + ActiveNetworkName);
  }
  
  function ShowLoading(bShow){
    oLoading=document.getElementById('loadingDiv')
    if(oLoading!=undefined){
      if(bShow==true){
        oLoading.style.visibility = "visible"; 
      }else{
        oLoading.style.visibility = "hidden";
      }
    }
  }
  
  function ShowLoadingActivity(sID, bShow){
    oLoading=document.getElementById(sID)
    if(oLoading!=undefined){
      if(bShow==true){
        oLoading.style.visibility = "visible"; 
      }else{
        oLoading.style.visibility = "hidden";
      }
    }  
  }
  
function IsFloatingPanelExpanded(fpID){        
  var floatingPanel = document.getElementById(fpID);
  var fpBody=document.getElementById(fpID+'_BodyRow');
  var bReturn = true;
  if (fpBody.style.display=='none'){
    bReturn=false;
  } else {
    bReturn=true;
  }        
  return bReturn;
}

function ShowMsg(sMsg){
  var s = replaceString(sMsg, 'Z6834','\n');
  s = replaceString(s,':eq:','=');
  alert(s);
}

function replaceString(strValue,strOld,strNew){
  var sReturn="";    
  if(strOld==""){
    strOld=";";
  }
  if(strNew==""){
    strNew=",";
  }
  var strArray=strValue.split(strOld);
  var sb = new StringBuilder();
  for(var i=0;i<strArray.length;i++){  
    if(i==0){ 
      sb.append(strArray[i]);  
    }else{
      sb.append(strNew+strArray[i]);
    }
  }
  sReturn = sb.toString();
  return sReturn;
}

function SetStatusMsg(sMsg){
  if(window!=null){
    window.status = sMsg;  // + " " + Date() + ".";
  }
}

function GetSelectedText(oSelect){
  var nCnt=oSelect.options.length;
  var sText='';
  if(nCnt>=0){
   for(var i=0;i<nCnt;i++){
     var o = oSelect.options[i];
     if(o.selected){
       if(o.title!=''){
         sText=o.title;
       }else{
         sText=o.text;
       }
       break;
     }
   }
  }
  return sText;
}

function ShowOptionText(oSelect, value, ValuePrefix, NamePrefix){
  var nCnt=oSelect.options.length;
  var sText='';
  
  if(nCnt>=0){
   SetStatusMsg('Searching '+ValuePrefix+value+' in '+nCnt+' elements...'); 
   for(var i=0;i<nCnt;i++){
     var o = oSelect.options[i];
     if(o.value==value){
       if(o.title!=''){
         sText=o.title;
       }else{
         sText=o.text;
       }
       SetStatusMsg(ValuePrefix+value+NamePrefix+sText);
       break;
     }
   }
  }
}

function init()
{
  // check browser
  isMozilla = (document.all) ? 0 : 1;


  if (isMozilla) 
  {
      document.captureEvents(Event.MOUSEDOWN | Event.MOUSEMOVE | Event.MOUSEUP);
  }

  //document.onmousedown = MouseDown;
  document.onmousemove = getImageXY;
  //document.onmouseup = getImageXY;
 
  //buildDimmerDiv();      

 // var topdiv = document.getElementById("Map1");
  //if (topdiv!=null) document.topdiv.onmousemove = MapIdClick;
}

//
// dinamically add a div to 
// dim all the page
//
function buildDimmerDiv()
{
  document.write('<div id="dimmer" class="dimmer" style="width:'+ window.screen.width + 'px; height:' + window.screen.height +'px"></div>');
}

// Start of the StringBuilder class
function StringBuilder(value){
	this.strings = new Array("");
	this.append(value);
}
StringBuilder.prototype.append = function (value){
	if (value){
		this.strings.push(value);
	}
}
StringBuilder.prototype.clear = function (){
	this.strings.length = 1;
}
StringBuilder.prototype.toString = function (){
	return this.strings.join("");
}

function GetLastExtent(){
  var sCallback = 'ControlType=CUAHSI&EventArg=LastExtent&EventVal=1';
  TriggerCallback('LastExtent',sCallback);
}

// End of the StringBuilder class

init();
