/* movingtargets map.js */




var COLORS = [["red", "#ff0000"], ["orange", "#ff8800"], ["green","#008000"],

              ["blue", "#000080"], ["purple", "#800080"]];

var options = {};

var lineCounter_ = 0;

var shapeCounter_ = 0;

var markerCounter_ = 0;

var colorIndex_ = 0;

var featureTable_;

var map;

var circle_lines = [];

var circle_cells = [];

var circles   = [];

var polygons  = [];

var polylines = [];

var points    = [];

var mapTool        = null;

var lastOverlay    = null;

var markerListener = null;



var tool_hints =  {

		'hand_b'       : 'Use the Grabber Tool to move the map around.',

		'placemark_b'  : 'Use the Marker Tool to mark a location or address.',

		'line_b'       : 'Use the Line Tool to draw a line.<br /><strong>Step 1.</strong> Click the map to choose the points of your line.<br /><strong>Step 2.</strong> Double click the map to end drawing.',

		'shape_b'      : 'Use Shape Tool to create the boundaries of your mailing area.<br /><strong>Step 1.</strong> Click the map to choose the edges of your shape.<br /><strong>Step 2.</strong> Double click the map -or- click the first point, to end drawing.',

		'circle_b'     : 'The Circle Tool allows you to create the boundaries of your mailing area.<br /><strong>Step 1.</strong> Click the map to choose the center of the circle.<br /><strong>Step 2.</strong> Click again to choose the edge.',

		'clear_b'      : 'Use the clear map button to start over.'

                 };



function select(buttonId) {

  mapTool = buttonId;

  document.getElementById('hint_box').innerHTML = tool_hints[buttonId];



  document.getElementById("hand_b").className="unselected";

  document.getElementById("shape_b").className="unselected";

  document.getElementById("circle_b").className="unselected";

  //document.getElementById("line_b").className="unselected";

  document.getElementById("placemark_b").className="unselected";

  document.getElementById(buttonId).className="selected";

}



function clearTool()

{

 lastOverlay = null;

 mapTool = null;

 //markerListener = null;

}

function stopEditing() {

  clearLastOverlay();

  clearTool();

  select("hand_b");

}



function getColor(named) {

  return COLORS[(colorIndex_++) % COLORS.length][named ? 0 : 1];

}



function getIcon(color) {

  var icon = new GIcon();

  icon.image = "http://google.com/mapfiles/ms/micons/" + color + ".png";

  icon.iconSize = new GSize(32, 32);

  icon.iconAnchor = new GPoint(15, 32);

  return icon;

}



function getCenter()

{

 var mc = map.getCenter();

 return [mc.x,mc.y];

}

function getPoints()

{

 var point_data = {};

 for (var j=0;j<points.length;j++)

 {

   var point = points[j];

   point_data[j] = [];

   t_vertex = point.getLatLng();

   point_data[j].push(t_vertex.lat() , t_vertex.lng());



 }

  return point_data;

}

function getPolylines()

{

 var polyline_data = {};

 for (var j=0;j<polylines.length;j++)

 {

   var polyline = polylines[j];

   polyline_data[j] = {set:[]};



     for (var i=0;i<polyline.getVertexCount();i++)

     {

      var t_vertex = polyline.getVertex(i);

      polyline_data[j].set[i] = [t_vertex.lat() , t_vertex.lng()];

     }

 }

  return polyline_data;

}

function getPolygons()

{

 var polygon_data = {};

 for (var j=0;j<polygons.length;j++)

 {

   var polygon = polygons[j];

   polygon_data[j] = {set:[]};



     for (var i=0;i<polygon.getVertexCount();i++)

     {

      var t_vertex = polygon.getVertex(i);

      polygon_data[j].set[i] = [t_vertex.lat() , t_vertex.lng()];

     }

 }

  return polygon_data;

}

function getCircles()

{

	

 var circle_data = {};

 for (var j=0;j<circles.length;j++)

 {

   var circle = circles[j];

   circle_bounds = circle.getBounds();

   sw_vertex = circle_bounds.getSouthWest();

   ne_vertex = circle_bounds.getNorthEast();

   c_vertex  = circle_bounds.getCenter();

   circle_data[j] = {

   	                 sw :[sw_vertex.lat() , sw_vertex.lng()],

   	                 ne :[ne_vertex.lat() , ne_vertex.lng()],

   	                 c  :[c_vertex.lat()  , c_vertex.lng()],

   	                 set:[]

                        };



     for (var i=0;i<circle.getVertexCount();i++)

     {

      var t_vertex = circle.getVertex(i);

      circle_data[j].set[i] = [t_vertex.lat() , t_vertex.lng()];

     }

 }

  return circle_data;

}



function round(num)

{

 return Math.round(num*1000)/1000;

}

function buildMapData()

{



  var raw_map_data  = {

		      mapCenter : getCenter(),

		      points    : getPoints(),

		      polylines : getPolylines(),

		      polygons  : getPolygons(),

		      circles   : getCircles()

  	              }





  return JSON.stringify(raw_map_data);



}

function clearLastOverlay(clearMarker)

{

 clearMarker = (clearMarker === false)?false:true;



 if (circle_lines[circle_lines.length-1] == lastOverlay)

 {

  circle_lines.pop();

 }

 if (lastOverlay != null)

 {



   map.removeOverlay(lastOverlay);

   GEvent.clearListeners(map, 'click');

   if (markerListener == null)

   {

    GEvent.trigger(lastOverlay,'cancelline');

    lastOverlay.disableEditing();

   }

 }



 if (markerListener != null && !clearMarker)

 {

   GEvent.removeListener(markerListener);

   markerListener = null;

 }

 lastOverlay = null;

}

function startCircle() {

  clearLastOverlay();



 if (mapTool != "circle_b")

 {



  select("circle_b");

  var color = getColor(false);

  var line = new GPolyline([], color);

  map.addOverlay(line);

  line.enableDrawing(options);

  circle_lines.push(line);

  lastOverlay = line;

  line.enableEditing({onEvent: "mouseover",maxVertices:1});

  line.disableEditing({onEvent: "mouseout"});

  GEvent.addListener(line, "mouseover", function()

  {

    line.show();

    line.enableEditing();

  });

  GEvent.addListener(line, "mouseout", function()

  {

    line.disableEditing();

    line.hide();

  });

  GEvent.addListener(line, "lineupdated", function() {



     var vcount = line.getVertexCount();

     if (vcount == 2)

     {



      line.disableEditing();

      line.hide();

      var len = line.getLength()/1000;

      var center = line.getVertex(0);

      var x;

      var new_circle = false;



      clearTool();

      var circle = showCircle(center,len,color);

           GEvent.addListener(circle , "mouseover", function() {

	   	   line.show();

		   line.enableEditing();

		   });

           GEvent.addListener(circle , "mouseout", function() {

		   line.disableEditing();

	   	   line.hide();

		   });



      for (x in circle_lines)

      {

      	if (circle_lines[x] === line)

      	{



   	  if (circles[x])

	  {

	   map.removeOverlay(circles[x]);

	   circles[x] = circle;

	  } else {

	   circles.push(circle);

	   new_circle = true;

	  }



          clearTool();

          circle.disableEditing();

          

             //var area = circle.getArea();

            // var cell_content = round(((Math.round(area / 10000) / 100)*.62)) + " sq. miles";

             var len = circle_lines[x].getLength();

             var cell_content = round(((Math.round(len / 10) / 100)*.62)) + " Mile Radius";

           if (new_circle)

           {

	     var new_val = parseInt(x)+1;

             var cells = addFeatureEntry("Circle "+ new_val +" -", color);

             cells.desc.innerHTML = cell_content;

             circle_cells.push(cells.desc);

           } else {

	     circle_cells[x].innerHTML = cell_content;

	   }

         select("hand_b");

	 break;

	}

      }



     }





  });





 } /* end mapTool */

 return false;

}

function showCircle(center,radius,color) 

{



  return drawCircle(center, radius, 30, color, 1, 0.7, color, 0.2);

}



function startShape() {

  clearLastOverlay();



 if (mapTool != "shape_b")

 {

  select("shape_b");

  var color = getColor(false);

  var polygon = new GPolygon([], color, 2, 0.7, color, 0.2);

  lastOverlay = polygon;

  polygons.push(polygon);

  startDrawing(polygon, "Shape " + (++shapeCounter_) + (" - "), function() {

    var cell = this;

    var area = polygon.getArea();

    cell.innerHTML = round(((Math.round(area / 10000) / 100)*.62)) + " Sq. Miles";

  }, color);

  GEvent.addListener(polygon, "endline", function(latlng, index) {  clearTool(); });



 }



}





function startLine() {

  clearLastOverlay();



 if (mapTool != "line_b")

 {

  select("line_b");

  var color = getColor(false);

  var line = new GPolyline([], color);

  lastOverlay = line;

  polylines.push(line);

  startDrawing(line, "Line " + (++lineCounter_), function() {

    var cell = this;

    var len = line.getLength();

    cell.innerHTML = ((Math.round(len / 10) / 100)*.62) + "mi";

  }, color);

  GEvent.addListener(line, "endline", function(latlng, index) { clearTool(); });



 }



}



function addFeatureEntry(name, color) {

  currentRow_ = document.createElement("tr");

  var colorCell = document.createElement("td");

  currentRow_.appendChild(colorCell);

  colorCell.style.backgroundColor = color;

  colorCell.style.width = "1em";

  colorCell.innerHTML = "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";

  var nameCell = document.createElement("td");

  currentRow_.appendChild(nameCell);

  nameCell.innerHTML = name;

  var descriptionCell = document.createElement("td");

  currentRow_.appendChild(descriptionCell);

  featureTable_.appendChild(currentRow_);

  return {desc: descriptionCell, color: colorCell};

}



function startDrawing(poly, name, onUpdate, color) {

  map.addOverlay(poly);

  poly.enableDrawing(options);

  poly.enableEditing({onEvent: "mouseover"});

  poly.disableEditing({onEvent: "mouseout"});

  GEvent.addListener(poly, "endline", function() {

    select("hand_b");

    var cells = addFeatureEntry(name, color);

    GEvent.bind(poly, "lineupdated", cells.desc, onUpdate);

    GEvent.addListener(poly, "click", function(latlng, index) {

      if (typeof index == "number") {

        poly.deleteVertex(index);

      } else {

        var newColor = getColor(false);

        cells.color.style.backgroundColor = newColor

        poly.setStrokeStyle({color: newColor, weight: 4});

      }

    });

  });

}



function placeMarker() {

 

 clearLastOverlay(false);



 if (mapTool != "placemark_b")

 {

  select("placemark_b");

  markerListener = GEvent.addListener(map, "click", function(overlay, latlng) {

    if (latlng && mapTool == "placemark_b") {

      clearTool();

      select("hand_b");

      GEvent.removeListener(markerListener);

      markerListener = null;



      var color = getColor(true);

      var marker = new GMarker(latlng, {icon: getIcon(color), draggable: true});

      points.push(marker);



      map.addOverlay(marker);

      var cells = addFeatureEntry("Placemark " + (++markerCounter_), color);

      updateMarker(marker, cells);



      GEvent.addListener(marker, "dragend", function() {

        updateMarker(marker, cells);

      });

      GEvent.addListener(marker, "click", function() {

        updateMarker(marker, cells, true);

      });



    }

  });



 } /* maptool end */



}



function updateMarker(marker, cells, opt_changeColor) {

  if (opt_changeColor) {

    var color = getColor(true);

    marker.setImage(getIcon(color).image);

    cells.color.style.backgroundColor = color;

  }

  var latlng = marker.getPoint();

  cells.desc.innerHTML = "(" + Math.round(latlng.y * 100) / 100 + ", " +

  Math.round(latlng.x * 100) / 100 + ")";

}



function addPoint(point)

{

      var color = getColor(true);

      var marker = new GMarker(point, {icon: getIcon(color), draggable: true});

      points.push(marker);

      map.addOverlay(marker);

      GEvent.addListener(marker, "dragend", function() {

        updateMarker(marker, cells);

      });

      GEvent.addListener(marker, "click", function() {

        updateMarker(marker, cells, true);

      });

}

function clearMap()

{

  map.clearOverlays();



  circle_cells   = [];

  circle_lines   = [];

  circles        = [];

  polygons       = [];

  polylines      = [];

  points         = [];

  lineCounter_   = 0;

  shapeCounter_  = 0;

  markerCounter_ = 0;

  colorIndex_    = 0;

  

  var element = document.getElementById('featuretbody');

  while (element.firstChild) {

    element.removeChild(element.firstChild);

  }



  stopEditing();



  return false;

}

function initialize() {

  if (GBrowserIsCompatible()) {

    map = new GMap2(document.getElementById("map"));

    map.setCenter(new GLatLng(40.3749, -75.2988), 15);

    map.addControl(new GSmallMapControl());

    map.addControl(new GMapTypeControl());

    map.addControl(new GScaleControl());

    map.disableDoubleClickZoom();

    //map.enableScrollWheelZoom();

    map.clearOverlays();

    //map.enableGoogleBar();



    featureTable_ = document.getElementById("featuretbody");

    select("hand_b");



  }

}



function calcCircleArea(radius)

{

 var area = 0;

 area = (Math.PI * (radius * radius));

 return area;

}

function updateCircle(circle,point)

{

	

   circle_bounds = circle.getBounds();

   c_vertex  = circle_bounds.getCenter();

   var distance = c_vertex.distanceFrom(point);

   map.removeOverlay(circle);

   circle = drawCircle(c_vertex, distance,20, '#ff0000', 1, 0.5, '#ff0000', 0.5);



}

function drawCircle(center, radius, nodes, line_color, liWidth, line_opacity, fill_color, fill_opacity)

{

	// calc km/degree

	var latC = center.distanceFrom(new GLatLng(center.lat()+0.1, center.lng()))/100;

	var lngC = center.distanceFrom(new GLatLng(center.lat(), center.lng()+0.1))/100;



	// calc circle points 

	var points = [];

	var step = parseInt(360/nodes)||10;

	for(var i=0; i<=360; i+=step)

	{

	  var pint = new GLatLng(

                               center.lat() + (radius/latC * Math.cos(i * Math.PI/180)), 

                               center.lng() + (radius/lngC * Math.sin(i * Math.PI/180))

                               );

	  points.push(pint);

	}



	var poly = new GPolygon(points,line_color,liWidth,line_opacity,fill_color,fill_opacity,{clickable:true});



	map.addOverlay(poly);

        poly.disableEditing();



   return poly;

}



function findAddr()

{

 var newAddr = document.getElementById('address_search').value;

 cg = new GClientGeocoder();

 cg.getLatLng(newAddr, centerMap);

}



function centerMap(coords)

{

 if (coords != null)

 {

   map.setCenter(coords,15);

   addPoint(coords);

 } else {

   alert('Address match was not found.');

 }

}



function userFormSubmit()

{



   var form_valid = validateform();





   document.getElementById('map_data').value = buildMapData();





   if (!points.length && !polygons.length && !polylines.length && form_valid)

   {

     form_valid = false;

     alert('Please use the map tools to select your Trade Area.');

   }



   if (form_valid)

   {

     document.getElementById('map_form').submit();

   } else {

     return false;

   }





}





function validateform()

{





 var required_fields = ['company','first_name','last_name','email'];

 var required_messages = {'company'   : 'Company Name',

                          'first_name': 'First Name',

                          'last_name' : 'Last Name',

                          'email'     : 'Email Address'



                         }




   for(var i=0;i<required_fields.length;i++)

   {



     var el = document.getElementById(required_fields[i]);

	if(el.value == '')

	{

		alert('Please enter your ' + required_messages[required_fields[i]] +'.');

		el.focus();

		return false;

	}

   }

   // require state select
   if (!document.getElementById('state').selectedIndex)
   {
          alert('Please select your State.');
          document.getElementById('state').focus();
          return false;
   }

  return true;

}



































