﻿// JScript File

    //Function to submit the address to Google and then process the return lat/long point.
    function SearchMap() {
        var address = document.getElementById("AddressField").value;
        var ID = "TblResults"
        clearRowsFromResults(ID)
        
                
        if (!(address == "")) {
        
            //Clear all the markers
            map.clearOverlays();
        
            // Create a smaller marker icon
            var blueIcon = new GIcon(G_DEFAULT_ICON);
            blueIcon.image = "http://www.google.com/intl/en_us/mapfiles/ms/micons/blue-dot.png";
            blueIcon.iconSize = new GSize(32, 35);
            blueIcon.shadowSize = new GSize(27, 25);
            blueIcon.printImage="http://www.google.com/intl/en_us/mapfiles/ms/micons/blue-dot.png";
			blueIcon.printShadow=""; //Remove shadow from the print map because it doesn't actually "shadow"
			blueIcon.mozPrintImage="http://www.google.com/intl/en_us/mapfiles/ms/micons/blue-dot.png";

        
            // Set up the GMarkerOptions object
            var markerOptions = { icon:blueIcon };
            geocoder.getLatLng(address, function(point) {
                if (!point) {
                    alert(address + " not found");
                } else {
                	  btSearchPoint=point;
                	  btSearchAddress=address;
                	  btRange=document.getElementById("ddlbRange").value;
                    var marker = createMarker(point,-1,'Address',blueIcon);
                    map.addOverlay(marker);
                    var sAddr = "<p><span style='font-size: 14px;'>Search Address:<br>" + address + "</span></p>"; //+ "x=" + point.x +":y=" + point.y;
                    marker.openInfoWindowHtml(sAddr);
                    GEvent.addListener(marker, "click", function() { marker.openInfoWindowHtml(sAddr);});
                    
                    //Send request to server for the CBO locations.
                    ProcessSearchParms(point.x,point.y);
                                      
                    map.setCenter(point, 14);   
                    drawCircle2();
                    show('pnlResults'); 
                    
                }  //End if (!point
              }  //End function(point)
            ); //End geocoder.getLatLng
        } else {
            btSearchPoint=null;
            map.clearOverlays();
            ProcessSearchParms(0, 0);
            show('pnlResults');
            
        } //End (!(address == ""))   
    } //End function

    function ShowSearchPoint(point){
    	// Create a smaller marker icon
            var blueIcon = new GIcon(G_DEFAULT_ICON);
            blueIcon.image = "http://www.google.com/intl/en_us/mapfiles/ms/micons/blue-dot.png";
            blueIcon.iconSize = new GSize(32, 35);
            blueIcon.shadowSize = new GSize(27, 25);
            blueIcon.printImage="http://www.google.com/intl/en_us/mapfiles/ms/micons/blue-dot.png";
			blueIcon.printShadow=""; //Remove shadow from the print map because it doesn't actually "shadow"
			blueIcon.mozPrintImage="http://www.google.com/intl/en_us/mapfiles/ms/micons/blue-dot.png";

        
            // Set up the GMarkerOptions object
        var markerOptions = { icon:blueIcon };
        var marker = createMarker(point,-1,'Address',blueIcon);
        map.addOverlay(marker);
        var sAddr = "<p><span style='font-size: 14px;'>Search Address:<br>" + btSearchAddress + "</span></p>"
//        marker.openInfoWindowHtml(sAddr);
        GEvent.addListener(marker, "click", function() { marker.openInfoWindowHtml(sAddr);});
        map.setCenter(point, 14);
        drawCircle2()
        }        
        
    function SetupMarkerMgr(rValue, clear, type, startcnt, endcnt, next) {
        //Reset gmarkers variable
        gmarkers = [];
        cbolocarr = [];
        if (clear) {map.clearOverlays();}
				if (btSearchPoint!=null)ShowSearchPoint(btSearchPoint);
        var baseIcon = new GIcon(G_DEFAULT_ICON);
        if (!(type=="LETTER")) {
            // Create a smaller marker icon    
            baseIcon.image = "http://www.google.com/intl/en_us/mapfiles/ms/micons/red-dot.png";
            baseIcon.iconSize = new GSize(20, 20);
            baseIcon.shadowSize = new GSize(25, 23);
        }

        // Now extract the title and lat/long that was passed back from the CallBack.
        var cbolocs = rValue.split("|")
        var j = 0;
        
        if (endcnt==0) endcnt=cbolocs.length-1;
        
        for (var i=startcnt;i<=endcnt;i++) {
          var cbolocs1 = cbolocs[i].split("^")
          
          if (type=="LETTER") {
            var letter = String.fromCharCode("A".charCodeAt(0) + j);
            baseIcon.image="http://www.google.com/mapfiles/marker" + letter + ".png";
            baseIcon.printImage="http://www.google.com/mapfiles/marker" + letter + ".png";
			baseIcon.printShadow=""; //Remove shadow from the print map because it doesn't actually "shadow"
			baseIcon.mozPrintImage="http://www.google.com/mapfiles/marker" + letter + ".png";

           }
          
          // Set up the GMarkerOptions object
          var markerOptions = { icon:baseIcon };
          var posxy = new GLatLng(cbolocs1[1], cbolocs1[2]);              
          
          if (posxy.y>0) {
            var title = cbolocs1[0];
            var overview = cbolocs1[3];
            var desc = cbolocs1[4];
            var marker = createMarker(posxy,j,title,baseIcon,overview,desc);
          if (type!="LETTER"){
          	 map.addOverlay(marker, markerOptions);  
          	}
          else{
            if (i-startcnt<26 ) map.addOverlay(marker, markerOptions);  
          }
            gmarkers[j] = marker;
            j = j + 1;
          }  
        }
                        
        if (type=="LETTER") {
            // ===== Start with an empty GLatLngBounds object =====     
            var bounds = new GLatLngBounds();
      
            for (var i = 0; i < gmarkers.length; i++) {
                var lat = gmarkers[i].getPoint().lat();
                var lng = gmarkers[i].getPoint().lng();
                var pntbnd = new GLatLng(lat,lng);
                // ==== Each time a point is found, extent the bounds ato include it =====
                bounds.extend(pntbnd);
            }
            // ===== determine the zoom level from the bounds =====
            map.setZoom(map.getBoundsZoomLevel(bounds));

            // ===== determine the centre from the bounds ======
            map.setCenter(bounds.getCenter());
        	
        	var ID = "TblResults"
        		
        	var x=document.getElementById(ID).rows[0].cells;	    
		    if ((j>0) && (!(next))) { 
                // If any markers were created, add the results to the TblResults
                x[0].innerHTML="<span><b>The results listed below are within your search radius.</b></span>";
                addRowToResults(rValue, ID, j, 0, j);

            } else {
                // No results found.  Inform the user.
                clearRowsFromResults(ID);
                var tbl = document.getElementById(ID);
                tbl.cellSpacing='5px';
								var row = tbl.insertRow(-1);
            		var td1 = row.insertCell(-1);
            		var td2 = row.insertCell(-1);
            		tbl.rows[0].cells[0].innerHTML="<span><b>No CBO's were found within your search Radius.</b></span>";
 
            }
            if (document.getElementById("AddressField").value=="") {
                //Address search not performed.  Message invalid.
                x[0].innerHTML="";
            }
        }    
      }  
       
    //Create the actual marker with all the parameters.
    function createMarker(posn, i, title, icon, overview, desc) {

      if (i>=0) {
        // The info window version with the "to here" form open
        to_htmls[i] = overview + '<span style="font-size: 12px;">Directions:<br></span><span style="font-size: 11px;"><b>To here</b> - <a href="javascript:fromhere(' + i + ')">From here</a>' +
           '<p><span style="font-size: 12px; font-weight: bold;">Start address:</span><br>' +
           '<input type="text" SIZE=30 MAXLENGTH=40 onkeydown="javascript:if(event.keyCode==13) {getDirections()};" name="saddr" id="saddr" value="'+document.getElementById("AddressField").value+'" /><br>' +
           '<INPUT style="font-size: 10pt" onclick="javascript:getDirections()" value="Get Directions" TYPE="BUTTON">' +
           '<input type="hidden" id="daddr" value="'+title+"@"+ posn.lat() + ',' + posn.lng() + 
           '"/>';
        // The info window version with the "to here" form open
        from_htmls[i] = overview + '<span style="font-size: 12px;">Directions:<br></span><span style="font-size: 11px;"><a href="javascript:tohere(' + i + ')">To here</a> - <b>From here</b>' +
           '<p><span style="font-size: 12px; font-weight: bold;">End address:</span><br>' +
           '<input type="text" SIZE=30 MAXLENGTH=40 onkeydown="javascript:if(event.keyCode==13) {getDirections()};" name="daddr" id="daddr" value="'+document.getElementById("AddressField").value+'" /><br>' +
           '<INPUT style="font-size: 10pt" onclick="javascript:getDirections()" value="Get Directions" TYPE="BUTTON">' +
           '<input type="hidden" id="saddr" value="'+title+"@"+ posn.lat() + ',' + posn.lng() + '">';
        
        ovrTblDes[i] = overview;
        // The inactive version of the direction info
        overview = overview + '<span style="font-size: 12px;">Directions:<br><span style="font-size: 11px;"><a href="javascript:tohere('+i+')">To here</a> - <a href="javascript:fromhere('+i+')">From here</a>';
        
        ovrtab[i] = overview;
        dsctab[i] = desc;
        
      
         var infoTabs = [
             new GInfoWindowTab("Overview", overview),
             new GInfoWindowTab("Details", desc)
         ];
      }    
      
      var marker = new GMarker(posn, {title: title, icon: icon});
      
      //New "mouseover" method will allow you to popup the window without clicking.
      if (!(desc="")) GEvent.addListener(marker, "click", function() { marker.openInfoWindowTabsHtml(infoTabs); PopulateDesTbl(ovrTblDes[i], dsctab[i]);});
      return marker;
    }
    function clearRowsFromResults(ID){
    	var tbl = document.getElementById(ID);
            
        //Delete any rows we've previously added.
        while(tbl.rows.length>1) {
            tbl.deleteRow(tbl.rows.length - 1);
        }
        gdir.clear()
      }
    //Create the sidebar results list.
    function addRowToResults(rValue, ID, reccnt, fromcnt, tocnt) {

        var tbl = document.getElementById(ID);
        clearRowsFromResults(ID)
        
        var cbolocs = rValue.split("|");
        var j = 0;
        var tbl = document.getElementById(ID);
        tbl.cellSpacing='5px';
    
        if (reccnt>25) {
            cboloclst = rValue;
            var row = tbl.insertRow(-1);
            var td1 = row.insertCell(-1);
            var td2 = row.insertCell(-1);
            var nextcnt;
            
            if (fromcnt==0) {
                tocnt = fromcnt+26;
                if (tocnt>reccnt) tocnt=reccnt;
            }
            
            if (fromcnt>1) {
                nextcnt = fromcnt-26;
                if (nextcnt<0) nextcnt=0;
                td1.innerHTML = '<A href="javascript:NextRowSet('+nextcnt+','+(fromcnt-1)+','+reccnt+')">Previous</A>';
                td1.vAlign = 'Center';
            }
            
            if (tocnt<reccnt) {
                nextcnt = tocnt+26;
                if (reccnt<nextcnt) nextcnt=reccnt;
                td2.innerHTML = '<A href="javascript:NextRowSet('+(tocnt+1)+','+nextcnt+','+reccnt+')">Next</A>';
                td2.vAlign = 'Center';
            }
            var row = tbl.insertRow(-1);
            var td1 = row.insertCell(-1);
            td1.colSpan="2";
            td1.innerHTML = '<HR>';

        }
           
          for (var i=fromcnt;i<=tocnt;i++) {
            var cbolocs1 = cbolocs[i].split("^")
            var posy = cbolocs1[1];
            if (posy>0) {
              var letter = String.fromCharCode("A".charCodeAt(0) + j);
              var iconimg = "http://www.google.com/mapfiles/marker" + letter + ".png";              
              var overview = cbolocs1[3];
        
              var row = tbl.insertRow(-1);
              var td1 = row.insertCell(-1);
              td1.innerHTML = '<A href="javascript:ClickMarker('+j+')"><img src="'+iconimg+'" style="border-style: none"></A>';
              td1.vAlign = 'Top';
              var td2 = row.insertCell(-1);
              td2.innerHTML = overview;
              td2.vAlign = 'Top';
                
              j = j + 1;
            }  
          }
        
          if (reccnt>25) {
             var row = tbl.insertRow(-1);
             var td1 = row.insertCell(-1);
             td1.colSpan="2";
             td1.innerHTML = '<HR>';

             var row = tbl.insertRow(-1);
             var td1 = row.insertCell(-1);
             var td2 = row.insertCell(-1);
             var nextcnt;
                
             if (fromcnt>0) {
                 nextcnt = fromcnt-26;
                 if (nextcnt<0) nextcnt=0;
                 td1.innerHTML = '<A href="javascript:NextRowSet('+nextcnt+','+(fromcnt-1)+','+reccnt+')">Previous</A>';
                 td1.vAlign = 'Center';
             }
            
             if (tocnt<reccnt) {
                 nextcnt = tocnt+26;
                 if (reccnt<nextcnt) nextcnt=reccnt;
                 td2.innerHTML = '<A href="javascript:NextRowSet('+(tocnt+1)+','+nextcnt+','+reccnt+')">Next</A>';
                 td2.vAlign = 'Center';
             }
           }
    }
    
      // ===== request the directions =====
      function getDirections() {

        show('pnlResults'); 
        
        //Delete all the rows from the results table so the directions aren't offset.
        var ID = "TblResults";
        var tbl = document.getElementById(ID);    
        while(tbl.rows.length>1) {
            tbl.deleteRow(tbl.rows.length - 1);
        }
        //and clear out the header row.
        var x=document.getElementById('TblResults').rows[0].cells;
        x[0].innerHTML="";
            
        var saddr = document.getElementById("saddr").value
        var daddr = document.getElementById("daddr").value
        gdir.load("from: "+saddr+" to: "+daddr);
      }

      // This function picks up the click and opens the corresponding info window
      function ClickMarker(i) {
         var infoTabs = [
             new GInfoWindowTab("Overview", ovrtab[i]),
             new GInfoWindowTab("Details", dsctab[i])
         ];
        gmarkers[i].openInfoWindowTabsHtml(infoTabs);
        
        PopulateDesTbl(ovrTblDes[i],dsctab[i]);
        
      }
      
      //Populate the table below the map with the overview and description of the selected CBO.
      function PopulateDesTbl(ovr, desc) {
        var tbl = document.getElementById("tblDatalist");
//        //Delete any rows we've previously added.
//        while(tbl.rows.length>1) {
//            tbl.deleteRow(tbl.rows.length - 1);
//        }
//        while(tbl.cols.length>1) {
//            tbl.deleteCell(tbl.cols.length - 1);
//        }
            
        //var row = tbl.insertRow(-1);
        //btaylor - don't show undefined
        var row = tbl.rows[0];
        var td1 = row.cells[1];
        var td2 = row.cells[2];
        td1.innerHTML="<b><u>Overview</u></b>";
        td2.innerHTML="<b><u>Description</u></b>";
        var row = tbl.rows[1];
        var td1 = row.cells[1];
        var td2 = row.cells[2];
        td1.vAlign="Top";
        td2.vAlign="Top";
        td1.innerHTML=ovr;
        td2.innerHTML=desc;
        if (td1.innerHTML=="undefined")
            td1.innerHTML="";
        if (td2.innerHTML=="undefined")
            td2.innerHTML="";
//        td1.style.height="100px"
//        td2.style.height="100px"
      }

      // functions that open the directions forms
      function tohere(i) {
         var infoTabs = [
             new GInfoWindowTab("Overview", to_htmls[i]),
             new GInfoWindowTab("Details", dsctab[i])
         ];
        gmarkers[i].openInfoWindowTabsHtml(infoTabs);
      }
      function fromhere(i) {
        var infoTabs = [
             new GInfoWindowTab("Overview", from_htmls[i]),
             new GInfoWindowTab("Details", dsctab[i])
         ];
        gmarkers[i].openInfoWindowTabsHtml(infoTabs);
      }

    function NextRowSet(cnt1, cnt2, reccnt) {
       SetupMarkerMgr(cboloclst, true, "LETTER", cnt1, cnt2, true);
       addRowToResults(cboloclst, "TblResults", reccnt, cnt1, cnt2);
    }

    function drawCircle(){
	var centerPt = btSearchPoint;
	var circlePoints = Array();

	with (Math) {
	    var radius=(.015*btRange)

		for (var a = 0 ; a < 361 ; a+=10) {
		
			var aRad = a*(PI/180);
			y = centerPt.y + radius * sin(aRad)
			x = centerPt.x + radius * cos(aRad)
			var p = new GPoint(x,y);
			circlePoints.push(p);
		}

//		map.removeOverlay(circleLine);
		circleLine = new GPolygon(circlePoints,'#0000ff',4,1);
		map.addOverlay(circleLine);
	}
}


function drawCircle2(){
  // Calculate the DIV coordinates of the centre point of our circle
  var centerPt = btSearchPoint;
  
  //get the map size for pixels and kms
  var sz = map.getSize();
  var bnds = map.getBounds();
  var pxDiag = Math.sqrt((sz.width*sz.width) + (sz.height*sz.height));
  var mDiagMi = bnds.getNorthEast().distanceFrom(bnds.getSouthWest()) / 1600.0;//1600 meters/mile
  var pxPerMi = pxDiag/mDiagMi;
  var radius = btRange*pxPerMi;
  var circlePoints = Array();
  for (var a = 0 ; a < 361 ; a+=10) {
	    var aRad = a*(Math.PI/180);
	    y = map.fromLatLngToDivPixel(centerPt).y + (radius * Math.sin(aRad));
	    x = map.fromLatLngToDivPixel(centerPt).x + (radius * Math.cos(aRad));
	    var p = new GPoint(x,y);
    	circlePoints.push(map.fromDivPixelToLatLng(p));
	}

//		map.removeOverlay(circleLine);
	circleLine = new GPolygon(circlePoints,'#0000ff',4,1);
	map.addOverlay(circleLine);
}