// XMLUtil.js
//
// Functions for processing AXL communicatins with the AXL Server.
//
// Mostly modified versions of stuff from aimsXML.js
//
// Loaded by mainFrame.htm
//
// David Nulph, 8/01
//jburka, induscorp 10/03 updated for rad extract

//master function used to handle the process of validating and submitting the form
function submitXML() {

   var validateResult = validateForm();

   if (validateResult != '') {
      alert('Error, please check the form for the following:\n\n'+validateResult);
      return;
   }

   //open the popup window
   updateDownloadWin();

   //generate the axl request
   var theAXLRequest = writeExtractXML();

   if (!theAXLRequest) {
      alert('ERROR building ArcXML request!');
   }

   //grab a reference to the posting form (named "theForm") in the PostForm frame
   var theForm = parent.PostFrame.document.forms["theForm"];

   if (!theForm) {
      alert('ERROR in primary form (theForm) attachment!');
   }

   //update the hidden inputs on theForm
   theForm.ArcXMLRequest.value = theAXLRequest;

   if (!imsRedirectURL) {
      alert('ERROR no value for redirected URL');
   }

   theForm.RedirectURL.value = imsRedirectURL;

   // This setting ensures that the function showExtractURL() in this js file will be run on
   // the doLoad event when PostFrame is reloaded via the AIMserver
   theForm.JavaScriptFunction.value = "parent.MainFrame.showExtractURL";

   if (!imsExtractURL) {
      alert('ERROR no value for ArcIMS Extracted URL');
   }

   theForm.action = imsExtractURL;
   theForm.submit();
}

//function to generate the AXL request from the details in the form
function writeExtractXML() {

   //grab a reference to the form frmExtract in MainFrame (part of radExtract.asp)
   var theForm = document.forms["frmExtract"];
   
   if (!theForm) {
      alert('ERROR cannot attached to the frmExtract form!');
   }

   // figure out the level
   els = theForm.elements;  //array of elements in the form
   cnt = els.length;      //number of elements

   // get the select object for the level and set the field/formula for the where clause
   //  variables are initialized for state
   var selName = "selState";

   //{table} is a placeholder which will be replaced with the table's actual USER.NAME
   var fieldName = "{table}.GEOGSTATE";   //all SDE for radExtract layers have a state field

   //   his was done with a switch in case we add other levels, e.g. region
   switch (dlevel) {
      case "1" :
         selName = "selCU";
         fieldName = "SUBSTR({table}.REACHCODE, 0, 8)"; //REACHCODE's first 8 characters contain the HUC id
         break;
   }

   //get the list of requested polygons from the appropriate list in frmExtract
   var thePolyList = getPolyList(els[selName]);

   //jburka 10/23/03  pad values if we're using HUC (need to be 8 characters, so some need a leading 0)
   if (dlevel=="1") {
      cnt = thePolyList.length;
      for (i=0;i<cnt;i++) {
         str = thePolyList[i];
         if (str.length!=8) {
            str = "0" + str;
            thePolyList[i] = str;
         }
      }
   }

   //create the where clause, based around an IN() containing a list of values to select
   var theWhereClause = fieldName + " IN (";

   if (thePolyList!="") {
      theWhereClause += joinAsSingleQuotedString(",", thePolyList);
   }

   theWhereClause += ")";

   //array of values used to build table names
   var typeAbbrev = new Array("P", "A", "L");

   //array of values used to determine correct layer names
   var typeList = new Array("pt", "poly", "ln");

   //associative array of table names keyed to their layer ID prefixes
   var tableNames = new Array();
   tableNames["WQS_"] = "RAD_NHD.VW_WQS_";
   tableNames["305B_"] = "RAD_NHD.VW_305B_";
   tableNames["303D_"] = "RAD_NHD.VW_303D_";
   tableNames["GRTS_"] = "RAD_NHD.VW_GRTS_";
   tableNames["NDZ_"] = "RAD_NHD.VW_NDZ_";
   tableNames["PCS_"] = "RAD_NHD.VW_PCS_";
   tableNames["BEACH_"] = "RAD_NHD.VW_BEACH_";
   tableNames["CSO_"] = "RAD_NHD.VW_CSO_";
   tableNames["FISH_"] = "RAD_NHD.VW_FISH_"
   tableNames["CWNS_"] = "RAD_NHD.VW_CWNS_"
   tableNames["TMDL_"] = "RAD_NHD.VW_TMDL_"

   // axl request header
   var theAXL  = '<?xml version="1.0" encoding="UTF-8"?>\n'
      + '<ARCXML version="1.1">\n'
      + '<REQUEST>\n'
      + '<GET_EXTRACT>\n'
      + '<PROPERTIES>\n'
      + '<ENVELOPE minx="-188.0" miny="5.0" maxx="-57.0" maxy="78.0" />\n'
      + '<FILTERCOORDSYS id="4269" />\n'
      + '<FEATURECOORDSYS id="4269" />\n'
      + '<LAYERLIST>\n';

   // figure out which layers are requested from the form and set the necessary
   // layers (with the appropriate featuretype suffix appended) visible and give them queries
   for(var i = 0; i < theForm.length; i++) {

      var e = theForm.elements[i];

      if ((e.type == "checkbox") ||(e.type=="radio" && e.name=="lyroption")) {
         if (e.checked){
            //insert a layer def for each of the three geometry types
            cnt = typeList.length;

            //  based on the layer id (e.value), get the table name

            //get the value
            val = e.value;
            
            //use a regexp to get the value up to the _
            nameReg = new RegExp("(.*_).*", "g");
            tmpArray = nameReg.exec(val + "_");
            var tableName =  tableNames[tmpArray[1]];
            var regx = new RegExp ('{table}', 'g') ;
            for (var x=0;x<cnt;x++) {
               theAXL += '<LAYERDEF id="'+ val + '_' + typeList[x] + '" visible="' + e.checked+'" >';

               //  tack on the end of the table name (typeabbrev + _sde)
               tmpTable = tableName + typeAbbrev[x] + "_SDE";

               tmpWhereClause = theWhereClause;
               tmpWhereClause = tmpWhereClause.replace(regx, tmpTable);

               if (thePolyList!="") {
                  theAXL +=  '<SPATIALQUERY where="' + tmpWhereClause + '" searchorder="attributefirst" subfields="#ALL#"  />\n';  //
               }

               theAXL +=  '</LAYERDEF>\n';
            } 
         } 
      }
   } 

   //close out the get_extract request
   theAXL  += '</LAYERLIST>\n'
      +  '</PROPERTIES>\n'
      +  '</GET_EXTRACT>\n'
      +  '</REQUEST>\n'
      +  '</ARCXML>\n';
      
   //alert(theAXL); 
   return theAXL;
}

// make an array of all selected states fips codes, from mainFrame
function getPolyList(sel) {

   var theForm = document.forms["frmExtract"];

   var thePolyList = new Array();

   var cnt = sel.options.length;

   for(var j = 0; j < cnt; j++) {

      if (sel.options[j].selected == true) {
         thePolyList.push(sel.options[j].value);
      }
   }

    return thePolyList;
}

//process the ArcIMS response to retrive the URL of the zip file and pass
// that along to showExtractURL.asp in the popup window
function showExtractURL(theReply) {

   // ASP version adds download filesize to the dialog
   // pops a window with a download button to get the zip file...
   var pos = theReply.indexOf("OUTPUT");
   var theZipFile = getInsideString(theReply,'output/',dQuote,pos,0,false);
   var theURL = getInsideString(theReply,'url="',dQuote,pos,0,false);

   // Added bogus opener page, waiting.html to avoid IE 6 access denied error, pdziemiela 20081223
   var Win1 = window.open("waiting.html", "ExtractWindow","width=575,height=120,scrollbars=yes,resizable=yes");
   
   if (!Win1) {
      alert('ERROR submission form window will not open');   
   }
   
   with (Win1.document) {
      close();
      open();
      write('<HTML><BODY onLoad="document.frmExtract.submit();">');
      write("<FORM name='frmExtract' method='post' action='" + "http://" + hostName + showExtractURLASP + "' target='_self'>");

      var extractForm = "<input type='hidden' name='theZipFile' value='" + theZipFile +"'>";
      extractForm += "<input type='hidden' name='charSet' value='" + charSet + "'>";
      extractForm += "<input type='hidden' name='textFrameBackColor' value='" + textFrameBackColor + "'>";
      extractForm += "<input type='hidden' name='textFrameTextColor' value='" + textFrameTextColor + "'>";
      extractForm += "<input type='hidden' name='textFrameLinkColor' value='" + textFrameLinkColor + "'>";
      extractForm += "<input type='hidden' name='theURL' value='" + theURL + "'>";
      extractForm += getLayerValues();

      write(extractForm);

      write('</FORM></BODY></HTML>');
      close();
   }
}

// get the substring between beforeString and afterString, starting at startpos
//       must be found before limitpos (0 for no limit)
//       caseSensitive = true or false
function getInsideString(inString,beforeString,afterString,startpos,limitpos,caseSensitive) {
   var returnString = "";
   var ucInString = inString;
   var ucBefore = beforeString;
   var ucAfter = afterString;
   if (limitpos==0) limitpos = inString.length;
   if (!caseSensitive) {
      ucInString = inString.toUpperCase();
      ucBefore = beforeString.toUpperCase();;
      ucAfter = afterString.toUpperCase();;
   }
   pos = ucInString.indexOf(ucBefore,startpos);
   //alert(startpos);
   if ((pos != -1) && (pos<limitpos)) {
      pos = pos + ucBefore.length;
      var endpos = ucInString.indexOf(ucAfter,pos);
      returnString = inString.substring(pos,endpos);
   }

   return returnString;

}

// validate the entries on the selection form to make sure that at least one state and layer are selected
function validateForm() {

/* jburka 10/22/03

   1) check level.
   2) if it's state, make sure just one state is selected
      it it's cu, make sure at least one is selected
   3) make sure at least one data type is selected

   jburka 10/29/03
   1) if state, only one layer type may be selected
   2) if CU, up to 10 (?) may be selected
*/

   theForm = document.forms["frmExtract"];
   var validateResult = '';
   var elCount = theForm.elements.length;
   var theForm = document.forms["frmExtract"];
   //var level = '';
   var checkCount = 0;
   var i = 0;

   var optLevel;
   if ( document.getElementById("dzform").optLevelState.checked == true ) {
      optLevel = document.getElementById("dzform").optLevelState;
      dlevel   = "0";

   } else {
      optLevel = document.getElementById("dzform").optLevelCU;
      dlevel   = "1";
   }

   switch (dlevel) {
      case "0":
         var lyroption = new Array(10);
         // THIS IS SOME CLUDGY CRAP
         lyroption[0]=document.getElementById("dzform").chk303D;
         lyroption[1]=document.getElementById("dzform").chk305B;
         lyroption[2]=document.getElementById("dzform").chkWQS;
         lyroption[3]=document.getElementById("dzform").chkFISH;
         lyroption[4]=document.getElementById("dzform").chkNDZ;
         lyroption[5]=document.getElementById("dzform").chkPCS;
         lyroption[6]=document.getElementById("dzform").chkGRTS;
         lyroption[7]=document.getElementById("dzform").chkBEACH;
         lyroption[8]=document.getElementById("dzform").chkTMDL;
         //
         //lyroption[9]=document.getElementById("dzform").chkNEP;
         //

         for (i=0; i<lyroption.length;i++) {

            if ( lyroption[i].checked == true ) {
               checkCount=1;
               break;
            }
         }
      break;
      case "1":
         for(i = 0; i < elCount; i++) {
            var e = theForm.elements[i];
            if (e.type == "checkbox") {
               if (e.checked) {
                  checkCount++;
               }
            }
         }
      break;
   }
   switch (dlevel) {
      case "0" :
          if (theForm.elements["selState"].selectedIndex==0)
          {
            selCnt=0;
          }
          else
          {
            selCnt = selCount(theForm.elements["selState"]);
          }

         if (!selCnt) {
            validateResult= extractList[17];
         } else if (selCnt > 1) {
            validateResult= extractList[16];
         }
         if (selCnt==1 && checkCount > 1) {
            validateResult=extractList[15];
         }
         break;
      case "1" :
         selCnt = selCount(theForm.elements["selCU"])
         if (!selCnt) {
            validateResult= extractList[13];
         } else if (selCnt > 10) {
            validateResult=extractList[14];
         }

         break;
   }

   if (validateResult=='') {
      if (checkCount == 0) {
         validateResult = validateResult + extractList[18] + '\n';

      }
   }

   return validateResult;

}


//jburka 10/22/03  return a boolean any options selected in passed-in select
function selCount(aSelect){
   cnt = aSelect.options.length;
   selCnt = 0;
   for (i=0;i<cnt;i++){
      if (aSelect.options[i].selected) {
         selCnt++;
      }
   }
   return selCnt;

}

// Open and display a message into the popup download window
function updateDownloadWin() {

   // Added bogus opener page, waiting.html to avoid IE 6 access denied error, pdziemiela 20081223
   var Win1 = window.open("waiting.html","ExtractWindow","width=575,height=160,scrollbars=yes,resizable=yes");
   
   if (!Win1) {
      alert('ERROR creating the submission window!');   
   }
   Win1.document.writeln('<html>');
   Win1.document.writeln('   <meta http-equiv="Content-Type" content="text/html; charset=' + charSet + '">');
   Win1.document.writeln('   <head>');
   Win1.document.writeln('      <title>' + extractList[0] + '</title>');
   Win1.document.writeln('   </head>');
   Win1.document.writeln('   <body bgcolor="' + textFrameBackColor + '" text="' + textFrameTextColor + '" link="' + textFrameLinkColor + '" vlink="' + textFrameLinkColor + '" LEFTMARGIN=10 TOPMARGIN=5 onload="window.focus()">');
   Win1.document.writeln('<FONT FACE="Arial" SIZE="-1"><b>');
   Win1.document.writeln(extractList[11]+'<br><br>');
   Win1.document.writeln(extractList[12]);
   Win1.document.writeln('   </body>');
   Win1.document.writeln('</html>')
   Win1.document.close();
}


//jburka 11/26/01
//  get the list of layer names so we can include their metadata files in the zip files

// jburka 11/4/03  not currently used, but might be later
function getLayerValues(){
   var theForm = document.forms["frmExtract"];
   var checkCount = 0;
   var theString = "";

   for(var i = 0; i < theForm.length; i++) {
      var e = theForm.elements[i];
      if (e.type == "checkbox") {
         if (e.checked == true) {
            tmpVals = e.value.split("|");
            theString+="<input type='hidden' name='metadata[]' value='" + tmpVals[0] + "'>";
            checkCount++;
         }
      }
   }
   if (theString=="") {
      theString = "<input type='hidden' name='metadata[]' value=''>";
   }

   return theString;
}

//jburka 10/23/03
//  do a join on an array but wrap elements in single quotes before concatenating them
function joinAsSingleQuotedString(delim, srcArray) {
   tmpArray =    new Array();
   cnt = srcArray.length;
   for (var i=0;i<cnt;i++){
      tmpArray.push("&apos;" + srcArray[i] + "&apos;");
   }
   outString = tmpArray.join(delim);
   return outString;
}