var theForm;
var pointPol;
var theBox;
var thePols;
var theLN;
var contCriteria=0;
var contTR =0;
var contCDS=0;
var contPOLY=0;
var polys_section = [];
var polys_tr= [];
var polys_cds= [];
var polys_bf= [];
// instantiate receiver XMLHttpRequest object 
var request = GXmlHttp.create(); 
// For Display of  polygons.
function displayPoly(poly,style,fillStyle,idPoly,pointPol) {
    var theObjForm = window.document.forms[theForm];
    //new GPolygon(polylines, fill?, color?, opacity?, outline?)
    var polObj = new GPolygon(poly,'#3399FF',0,1,'#FF0033', 0.25);
    themap.addOverlay(polObj);
    if (pointPol != null) {
        //map.centerAndZoom(pointPol, 8);
    //if (map.getZoom() < 10) map.setZoom(map.getZoom()+1);
    setZoom(map)
    map.panTo(pointPol);
    
    }               
    if (theForm=="frmLIVEBUFFER") {
        polys_bf[idPoly]= polObj;
    }
    if (theForm=="srcCriteria") {
        polys_section[idPoly]=polObj;
    } 
    if (theForm=="frmTRSECTION"){ 
        polys_tr[idPoly]=polObj;
    }
    if (theForm=="frmCADASTRAL"){ 
        polys_cds[idPoly]=polObj;
    }
}
// Removes layers for some ID polygon.
function eraseThePoly(poly,theForm,idPoly) {
          var theObjForm = window.document.forms[theForm];
          var polyObj=theObjForm.polyObjs;
          
          if (theForm=="frmLIVEBUFFER") {
             map.removeOverlay(polys_bf[idPoly]);
          }
          if (theForm=="srcCriteria") { 
             map.removeOverlay(polys_section[idPoly]);
          } 
          if (theForm=="frmTRSECTION"){ 
             map.removeOverlay(polys_tr[idPoly]);
          }
           if (theForm=="frmCADASTRAL"){ 
             map.removeOverlay(polys_cds[idPoly]);
          }
          contZ=0;
          
}
// Graph the polygons for the results' pages.
function drawResultsPolygons (geopoints,map) {
      var theId_Pol=[];
      if (geopoints.substring(geopoints.length-1, 1) =="|")
            geopoints= geopoints.substring(0, geopoints.length-1);
     if (geopoints !="")  theId_Pol = geopoints.split("|");
     var style = { weight: 1, opacity: .2, color: '#FF0033' };
     var fillStyle = {color: '#FF0033', opacity: .2};
     for (var i=0; i< theId_Pol.length; i++) {  
            var thePoly=[];
            var jID = theId_Pol[i].substring(0,theId_Pol[i].indexOf("~"));
                thePoints=theId_Pol[i].substring(theId_Pol[i].indexOf("~")+1,theId_Pol[i].length).split("@");
                for (var j=0; j < thePoints.length; j++) {
                   geocoords = thePoints[j].split(",");
                   x=parseFloat(geocoords[0]);
                   y=parseFloat(geocoords[1]);
                   np=new GPoint(x,y);
                   thePoly.push (np);
                }
                displayPoly(thePoly,style,fillStyle,0,pointPol,map); 
      } 
      
      
}
// Creates the polygons from receiving a string...
function drawAllPolygons (geopoints) {  // All the geo-points are received with pattern: LOCATION_ID1~long1,lat1@long2,lat2...|LOCATION_ID2~long1,lat1@long2,lat2...| 
         var theId_Pol=[];
         var theObjForm= window.document.forms[theForm];
         var theVal = eval("theObjForm."+idElement+".value");
         var theValObj= eval("theObjForm."+idElement);
         var thePolMem = theObjForm.polyMemory.value;
         var meanC=0; var totX=0; var totY=0;
         var thePoints="";
         var geocoords="";
         var x=0;
         var y=0;
          if (geopoints.substring(geopoints.length-1, 1) =="|")
            geopoints= geopoints.substring(0, geopoints.length-1);
         if (geopoints !="")  theId_Pol = geopoints.split("|");
         var style = { weight: 1, opacity: .2, color: '#FF0033' };
         var fillStyle = {color: '#FF0033', opacity: .2};
         contCriteria=0;
         contTR=0;
         contCDS=0;
          
         for (var i=0; i < theId_Pol.length; i++) {  
            var thePoly=[];
            var jID = theId_Pol[i].substring(0,theId_Pol[i].indexOf("~"));
                thePoints=theId_Pol[i].substring(theId_Pol[i].indexOf("~")+1,theId_Pol[i].length).split("@");
                for (var j=0; j < thePoints.length; j++) {
                   geocoords = thePoints[j].split(",");
                   x=parseFloat(geocoords[0]);
                   y=parseFloat(geocoords[1]);
                   np=new GPoint(x,y);
                   thePoly.push (np);
                }
                       if (theForm=="srcCriteria") { 
                            displayPoly(thePoly,style,fillStyle,contCriteria,pointPol);
                            contCriteria++;
                       }
                       if (theForm=="frmTRSECTION") { 
                            displayPoly(thePoly,style,fillStyle,contTR,pointPol);
                            contTR++;
                       } 
                       if (theForm=="frmCADASTRAL") { 
                            displayPoly(thePoly,style,fillStyle,contCDS,pointPol,themap);
                            contCDS++;
                       }
                //displayPoly(thePoly,style,fillStyle,0,pointPol); 
                
         }
         for (var i=0; i < theId_Pol.length; i++) {
         var jID = theId_Pol[i].substring(0,theId_Pol[i].indexOf("~"));
         if ((theVal.indexOf(jID) < 0 )){
            thePoints=theId_Pol[i].substring(theId_Pol[i].indexOf("~")+1,theId_Pol[i].length).split("@");
            for (var j=0; j < thePoints.length; j++) {
               geocoords = thePoints[j].split(",");
               x=parseFloat(geocoords[0]);
               y=parseFloat(geocoords[1]);
               totX+=Math.abs(x);
               totY+=Math.abs(y);
               meanC++;
               thePoly.push (new GPoint(x,y));
            }
            eraseThePoly(thePoly,theForm,i);     
         }
        }
         
}
// Verify the existence of new elements in the memory of layers.
function checkExistLoc(memory,theArr) {
   var returnval="true";
   for (var i=0; i<theArr.length; i++) {
        if (memory.indexOf(theArr[i].toUpperCase()) < 0 ) returnval="false";
   }
   return returnval;
}
// Creates the polygons using the search criteria box elements and drawing just those that are new. 
function drawLocation (theObj,memory) {
    theForm=activeForm;        
    var theLocs= theObj.value.replace(/(\s+|\n+)/g, "\r\n");
    theLocs = theLocs.split("\r\n");
    var tot="";
    for (var i=0; i<theLocs.length; i++) {
        if (memory.indexOf(theLocs[i].toUpperCase()) < 0 ) {
            var loc="";
            if (theForm=="frmCADASTRAL") {
                loc=/(\D+)\((\d+)-(\d+)\)(\d+)/;
            } else  if (theForm=="frmTRSECTION") {loc=/(\D+)\((\d+)-(\d+)\)$/; }
            var text=theLocs[i].toUpperCase();
            var result=text.match(loc);
            var totLoc="";
            var quad = "";
            var twn = "";
            var rng = "";
            var sec = "";
            var tdir="";
            var rdir="";
            if (result != null) {
                totLoc=result[0];
                quad = result[1];
                twn = result[2];
                rng = result[3];
                if (theForm=="frmCADASTRAL") {  sec = result[4];}
                if (quad=="A") { tdir="N"; rdir="E";} else 
                if (quad=="B") { tdir="N"; rdir="W";} else 
                if (quad=="C") { tdir="S"; rdir="W";} else 
                if (quad=="D") { tdir="S"; rdir="E";} else alert ("The polygon for the location typed is not found.");   
                if (theForm=="frmCADASTRAL") {  tot=tdir+","+rdir+","+twn+","+rng+","+sec;  } else if (theForm=="frmTRSECTION") {tot=tdir+","+rdir+","+twn+","+rng;}
                theLN=tot;
                if (tot !="") {  setTimeout("getTownship('0','0',theForm,theLN)",20); }
            } else {alert ("The polygon for the location typed is not found"); }
        }
   }
   
}
// Decides which polygons have to be removed from the map.
function turnoffPoly (theForm) {
     theForm=activeForm;
     var theObjForm = window.document.forms[theForm];
     var theVal = eval("theObjForm."+idElement+".value");
     var theValObj= eval("theObjForm."+idElement);
     var thePolMem = theObjForm.polyMemory.value;
     var meanC=0; var totX=0; var totY=0;
     var theId_Pol=[];
     var thePoly=[];
     var thePoints="";
     var geocoords="";
     var x=0;
     var y=0;
     theVal=theVal.toUpperCase();
    
     //if (theVal.indexOf("*") >0 )  theVal=theVal.substring(0,theVal.indexOf("*"));
     theId_Pol = thePolMem.split("|");
     for (var i=0; i < theId_Pol.length; i++) {
        var jID = theId_Pol[i].substring(0,theId_Pol[i].indexOf("~"));
        if ((theVal.indexOf(jID) < 0 )){
            thePoints=theId_Pol[i].substring(theId_Pol[i].indexOf("~")+1,theId_Pol[i].length).split("@");
            for (var j=0; j < thePoints.length; j++) {
               geocoords = thePoints[j].split(",");
               y=parseFloat(geocoords[0]);
               x=parseFloat(geocoords[1]);
               totX+=Math.abs(x);
               totY+=Math.abs(y);
               meanC++;
               thePoly.push (new GLatLng(x,y));
            }
            eraseThePoly(thePoly,theForm,i);     
        }
        
     }
      if (meanC > 0 ) { 
         totY=-totY;
         pointPol=new GLatLng(totX/meanC, totY/meanC);
         
      }
     theValObj.value = theValObj.value.replace(/^\s+|\s+$/g,"");
     theValObj.value = theValObj.value.replace(/(\s+|\n+)/g, "\r\n");
     drawLocation(theValObj,thePolMem);
    
  
}         
// Display Data from receiving the Response from GXHtml object.
    function displayTownshipData(reqObj){
                    theForm=activeForm;
                    var thePoly = [];
                    var meanC=0; var totX=0; var totY=0;
                    var theObjForm=window.document.forms[theForm];
                    var x=0;
                    var y=0;
                    var points="";
                    var memPol="";
                    var mdiv;
                    var theElement; 
                    theElement=eval("theObjForm." + idElement);
                    var jsonText=reqObj;   // ### JSON-object is requested with responseText
                    var jsonObj = eval('('+jsonText+')'); //### JSON-object is created
                    var geoloc=jsonObj.geospatial.location; // ### Getting the location 
                    geoloc=(geoloc.replace(/^\W+/,'')).replace(/\W+$[^)]/,'');
                    
                    var theText = theElement.value;
                    theText = theText.replace(/(\s+|\n+)/g, "\r\n");
                    var cExist=checkExistLoc(theObjForm.polyMemory.value,theText.split("\r\n"));
                    if ((verifyRepeats(theText,geoloc) < 0 ) || (cExist=="false"))  { 
                      if (cExist=="true") {
                       if (theText=="") { 
                          theText+= geoloc +"\n"; 
                        } else 
                             { theText+="\n" + geoloc; }
                      }
                      theText = theText.replace(/(\s+|\n+)/g, "\r\n");
                      theElement.value=theText;
                      var geocoord=jsonObj.geospatial.geocoords;  // ### Getting the geo-coords for the polygon 
                      for (var i=0; i< geocoord.length; i++) {
                        points=geocoord[i].split(','); 
                        y=parseFloat(points[0]);
                        x=parseFloat(points[1]);
                        totX+=Math.abs(x);
                        totY+=Math.abs(y);
                        meanC++;
                        thePoly.push(new GLatLng(x,y));
                        if (i+1==geocoord.length) {
                          memPol+=x+","+y; 
                        } else {
                          memPol+=x+","+y+"@";
                        }
                      }
                      if (meanC > 0 ) { 
                            totY=-totY;
                            pointPol=new GLatLng(totX/meanC, totY/meanC);
                       }
                       theObjForm.polyMemory.value+= geoloc + "~" + memPol + "|"; //### Saving values
                       var style = { weight: 1, opacity: .2, color: '#FF0033' };
                       var fillStyle = {color: '#FF0033', opacity: .2};
                       if (theForm=="srcCriteria") { 
                            displayPoly(thePoly,style,fillStyle,contCriteria,pointPol);
                            contCriteria++;
                       }
                       if (theForm=="frmTRSECTION") { 
                             for (j=polys_section.length-1; j>=0; j--) {
                                 map.removeOverlay(polys_section[j]);
                            }
                            displayPoly(thePoly,style,fillStyle,contTR,pointPol);
                            contTR++;
                       } 
                       if (theForm=="frmCADASTRAL") { 
                            
                            displayPoly(thePoly,style,fillStyle,contCDS,pointPol);
                            contCDS++;
                       }
                     } else {  theElement.value= theText.replace(/(\s+|\n+)/g, "\r\n"); alert("The location is already been considered in the the search criteria.");}
        }
// Display Data from receiving the Response from GXHtml object.
    function displayBuffer(reqObj){
                    gd="";
                    var thePoly = [];
                    var thePoly2=[];
                    var meanC=0; var totX=0; var totY=0;
                    var theObjForm=window.document.forms[theForm];
                    var x=0;
                    var y=0;
                    var points="";
                    var memPol="";
                    var mdiv;
                    var theElement; 
                    theElement=eval("theObjForm." + idElement);
                    var jsonText=reqObj;   // ### JSON-object is requested with responseText
                    var jsonObj = eval('('+jsonText+')'); //### JSON-object is created
                    var geoloc=jsonObj.geospatial.location; // ### Getting the location 
                    var geocoord=jsonObj.geospatial.geocoords;  // ### Getting the geo-coords for the polygon 
                      for (var i=0; i< geocoord.length; i++) {
                        points=geocoord[i].split(','); 
                        x=parseFloat(points[0]).toFixed(6);
                        y=parseFloat(points[1]).toFixed(6);
                        totX+=Math.abs(x);
                        totY+=Math.abs(y);
                        meanC++;
                        thePoly.push(new GLatLng(x,y));
                       
                        if (i+1==geocoord.length) {
                          memPol+=x+","+y; 
                        } else {
                          memPol+=x+","+y+"@";
                        }
                      }
                      if (meanC > 0 ) { 
                            totY=-totY;
                            pointPol=new GLatLng(totX/meanC, totY/meanC);
                            //console.log("X= "+pointPol.x+"<=>"+"Y= "+pointPol.y);
                       }
                      // theObjForm.polyMemory.value+= geoloc + "~" + memPol + "|"; //### Saving values
                       var style = { weight: 1, opacity: .2, color: '#FF0033' };
                       var fillStyle = {color: '#FF0033', opacity: .2};
                      
                         
                       if (theForm=="frmLIVEBUFFER") { 
                            
                            for (var i=0; i < thePoly.length; i++) {
                                //console.log("X,Y("+i+")="+thePoly.pop(i).x+","+thePoly.pop(i).y);
                                   //apl=thePoly.pop(i).x;
                                   // bpl=thePoly.pop(i).y;
                                   thePoly.pop();
                            }
                            
                            displayPoly(thePoly,style,fillStyle,0,pointPol);
                            contPOLY++;
                       }

        }         
// Receives lat/long values in order to get the Location and the data geopoints in order to create the polygons.
            function getTownship(y,x,theForm,proid) {
                 var url='resMapping.jsp?lat='+y+'&lon='+x+'&typ='+proid;
                 GDownloadUrl(url, function(dataT, responseCode) {
                    displayTownshipData(dataT);
                 });   
            }
// Receives point values in order to get the buffer polygon.
            function getBuffer(txtPoly,theForm,proid,radius,units) { 
                 var url='resMapping.jsp?txtPoly='+txtPoly+'&typ='+proid+'&radius='+radius+'&units='+units;
                 GDownloadUrl(url, function(dataT, responseCode) {
                   if(responseCode == 200) {
                    displayBuffer(dataT);
                   } else if(responseCode == -1) {
                    alert("Please try again, data loading interrupted.");
                   } else { 
                    alert("Loading data.");
                   } 
                 });   
            } 
