// Copyright © 2007 by Chris Marx <chrismarx@gmail.com>
// All rights reserved.
//
//Thanks to Mike Williams for many of the contributing examples
//and Bill Chadwick for his work on the svg/vml extensions
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// 1. Redistributions of source code must retain the above copyright
//    notice, this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright
//    notice, this list of conditions and the following disclaimer in the
//    documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
// OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
// OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
// SUCH DAMAGE. 
/*
GoogleDigitizerToolpack Polygon control. Version 0.2 Released 09/27/07

To use:
  map.addControl(new GPolygonControl());
  
  If access to the polygon array is desired, create a global variable from which to access it:
  var polyCtrl = new addPolygonControl();
  map.addControl(polyCtrl);
  
  //after objects have been added
  var polygonArray = polyCtrl.G.prmPolygons;

Note:
	In order to use the GoogleDigitizerToolpack controls, the following scripts must also be included in the html page:
	    
	    <script src="farbtastic/jQuery.js" type="text/javascript"></script>
		<script src="farbtastic/farbtastic.js" type="text/javascript" ></script>
		<script src="BDCCPolyline.js" type="text/javascript"></script>
		<script src="BDCCPolygon.js" type="text/javascript"></script>
	
	Stylesheets (added to the html page):
	
		<link rel="stylesheet" type="text/css" href="google.css" />
		<link rel="stylesheet" href="farbtastic/farbtastic.css" type="text/css" />
		
	Add the farbtastic package to a directory like /farbtastic. The full download (only 28kb, unpacked) can be found here
	
		http://acko.net/dev/farbtastic
		
		Note: There are several help files (.html) included that can be deleted from farbtastic directory
		
	And the following images must be available in a folder called images(unless otherwise specified) at this path "images/" 
		
		addashape.png;
		addashapeP.png;
		inflection.png;
		inflectionP.png;
		transparent.gif;
  
*/

//== Create a Custom GControl == //
function GPolygonControl() {}
     
GPolygonControl.prototype = new GControl();
GPolygonControl.prototype.initialize = function(map) {
       
   // obtain Function Closure on a reference to "this"
   var me=this;

   // store a reference to the map so that we can call setZoom() on it
   me.map = map;
   
   // Is this MSIE, if so we need to use AlphaImageLoader
   var agent = navigator.userAgent.toLowerCase();
   if ((agent.indexOf("msie") > -1) && (agent.indexOf("opera") < 1)){me.ie = true;} else {me.ie = false}

   // create the background graphic as a <div> containing an image
   var containerP = document.createElement("div");
   containerP.style.width="34px";
   containerP.style.height="34px";
   containerP.style.cursor="pointer";
   containerP.id = "polygonControl";

   // Handle transparent PNG files in MSIE
   if(me.ie) {
     var loader = '<a id="addPolygon" href="javascript:void(0)"><span id="addPolygonSpan" style="width:33px;height:33px;display:inline-block;' ;
     loader +=  "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='Images/addashape.png');" ;
     loader +=  '"><img id="addPolygonPic" style="filter:progid:DXImageTransform.Microsoft.Alpha(opacity=0);" src="Images/addashape.png" width="33" height="33" border="0" alt=""></span></a>'; 
     containerP.innerHTML = '<div id="addPolygonDiv" style="height:33px; width:33px; cursor="pointer">'+loader+'</div>';
   } else {
     containerP.innerHTML = '<a id="addPolygon" href="javascript:void(0)"><img id="addPolygonPic" src="Images/addashape.png"  width=33 height=33 border="0" ></a>';
   }

   // attach the control to the map
   me.map.getContainer().appendChild(containerP);
   me.containerP = containerP;

   // add toggle event polygon tool button
   //GEvent.addDomListener(me.containerP, 'click', me.polygButtonClick.on);
   $("#polygonControl").toggle(function(){me.polygButtonClick.on();},function(){me.polygButtonClick.off();});
   
  return containerP;
}
       
// == Set the default position for the control ==//
GPolygonControl.prototype.getDefaultPosition = function(){
     return new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(240, 0));
}      

// == create default coordinate icon ==//
GPolygonControl.prototype.icon = function(){
	
	var coordIcon = new GIcon();
	coordIcon.iconSize = new GSize(12,12);
	coordIcon.iconAnchor = new GPoint(6,9);
	coordIcon.infoWindowAnchor = new GPoint(8,0);
	coordIcon.image = "Images/inflection.png";
	coordIcon.imageP = "Images/inflectionP.png";
	return coordIcon;
} 

//== global variables ==//
GPolygonControl.prototype.G={
								ie:(navigator.userAgent.indexOf("MSIE")==-1)?false:true,
								polygon:null,
								tooltip:null,
								tooltip_handler:null,
								polygon_handler:null,
								addnewpolygonline_handler:null,
								polygonMarkers:new Array(),
								polygonPoints:new Array(),
								newline:null,
								prmPolygons:new Array(),		//permanent polygons, stored in multi-dimensional array (accessible from polyCtrl global var)	
								newGLinePoints:new Array(),
								newGLinePoints2:new Array(),
								newline:null,
								newline2:null,
								adjustvertex_handler:null,
								currentcolor:"#0000ff",
								lineColor:"#3333FF", // brown light line
								lineWeight:4,
								lineOpacity:.5,
								fillColor:"#00FF33", // red ligth fill
								fillOpacity:.4,
								//primary info window html is broken up into 4 pieces. It is assembled with the commented variables in between

								editInfoWindowHtml1:'<div id="editInfoWindow"  style="left: 6px; top: 7px; width: 270px;font-size:11px;"><div><table><tr><td align=right>Pais:</td><td align=left><select id=pai style="vertical-align: middle;font-size:11px;"><option value="Costa Rica">Costa Rica</option><option value="Nicaragua">Nicaragua</option>',
	 /*+g.prmPolygons[k][2]+*/  editInfoWindowHtml2:'</select></td><td><div id="colorIcon" class="icon" onmouseover="javascript:this.style.borderColor = \'#0000FF\'" onmouseout="javascript:this.style.borderColor = \'#DDDDDD\'"><div id="currentColor" class="poly" style="border-color: rgb(191, 191, 191); background-color:',
	 /*+g.prmPolygons[k][4]+*/  editInfoWindowHtml3:'"/></div></td></tr><div><table><tr><td align=right>Uso actual:</td><td align=left><select id=usa style="vertical-align: middle;font-size:11px;"><option value="residencial">residencial</option><option value="comercial">comercial</option><option value="industrial">industrial</option><option value="institucional">institucional</option>',	 
	 /*+g.prmPolygons[k][8]+*/  editInfoWindowHtml5:'</select></td><table><tr><td align=right>Edad:</td><td align=left><select id=edad style="vertical-align: middle;font-size:11px;"><option value="vieja">vieja</option><option value="nueva">nueva</option>',	 
	 /*+g.prmPolygons[k][9]+*/  editInfoWindowHtml6:'</select></td></td><table><tr><td align=right>Categoria socio-economica:</td><td align=left><select id=cse style="vertical-align: middle;font-size:11px;"><option value="alta">alta</option><option value="media">media</option><option value="baja">baja</option>',
	 /*+g.prmPolygons[k][11]+*/  editInfoWindowHtml7:'</select></td><table><tr><td align=right>Sit. edificacion:</td><td align=left><select id=sie style="vertical-align: middle;font-size:11px;"><option value="aislada">aislada</option><option value="esquina con edificios vecinos">esquina con edificios vecinos</option><option value="encajonada lateralmente">encajonada lateralmente</option>',
	 /*+g.prmPolygons[k][12]+*/  editInfoWindowHtml8:'</select></td><table><tr><td align=right>Irregularidad planta:</td><td align=left><select id=irp style="vertical-align: middle;font-size:11px;"><option value="no">no</option><option value="si">si</option>',
	 /*+g.prmPolygons[k][13]+*/  editInfoWindowHtml9:'</select></td><table><tr><td align=right>Numero pisos:</td><td align=left><select id=nump style="vertical-align: middle;font-size:11px;"><option value="1">1</option><option value="2">2</option><option value="3">3</option><option value="4">4</option><option value="5">5</option><option value="6">6</option><option value="7">7</option><option value="8">8</option><option value="9">9</option><option value="10">10</option><option value="11">11</option><option value="12">12</option><option value="13">13</option><option value="14">14</option><option value="15">15</option><option value="16">16</option><option value="17">17</option><option value="18">18</option><option value="19">19</option><option value="20">20</option><option value="21">21</option><option value="22">22</option><option value="23">23</option><option value="24">24</option><option value="25">25</option><option value="26">26</option><option value="27">27</option><option value="28">28</option><option value="29">29</option><option value="30">30</option><option value="31">31</option><option value="32">32</option>',
	 /*+g.prmPolygons[k][14]+*/  editInfoWindowHtml10:'</select></td><table><tr><td align=right>Canton:</td><td align=left><select id=can style="vertical-align: middle;font-size:11px;"><option value="Alfaro Ruiz">Alfaro Ruiz</option><option value="Cote">Cote</option><option value="Puntarenas">Puntarenas</option><option value="Alajuela">Alajuela</option><option value="Nicoya">Nicoya</option><option value="Puerto Cabezas">Puerto Cabezas</option><option value="Chinandega">Chinandega</option><option value="Rivas">Rivas</option><option value="Masaya">Masaya</option><option value="Granada">Granada</option><option value="Leon">Leon</option><option value="Matagalpa">Matagalpa</option><option value="Jinotega">Jinotega</option><option value="Region Autonoma del Atlantico Sur">Region Autonoma del Atlantico Sur</option>',
	 /*+g.prmPolygons[k][15]+*/  editInfoWindowHtml11:'</select></td><div class="msedit"><table class="iwspan"><tbody><tr><td><table class="inputField"><tbody><tr><td class="label">Observacion:</td><td><input id="obs" class="title" type="text" style="font-size:11px"  value="',
	 /*+g.prmPolygons[k][16]+*/  editInfoWindowHtml12:'"/></td><table><tr><td align=right>Ciudad:</td><td align=left><select id=ciu style="vertical-align: middle;font-size:11px;"><option value="Tapesco">Tapesco</option><option value="Cote">Cote</option><option value="Puntarenas">Puntarenas</option><option value="Alajuela">Alajuela</option><option value="Nicoya">Nicoya</option><option value="Puerto Cabezas">Puerto Cabezas</option><option value="Corinto">Corinto</option><option value="San Juan del Sur">San Juan del Sur</option><option value="Masaya">Masaya</option><option value="Granada">Granada</option><option value="Leon">Leon</option><option value="Chinandega">Chinandega</option><option value="Rivas">Rivas</option><option value="Matagalpa">Matagalpa</option><option value="Jinotega">Jinotega</option><option value="Bluefields">Bluefields</option>',
	 /*+g.prmPolygons[k][3]+*/  editInfoWindowHtml4:'</select></td><table style="margin-top:20px;font-size:11px;"><tbody><tr><td class="navLeft"><span class="lk"></span><a id="polyDelete" style="cursor: pointer;" href="javascript:void(0)">Borrar </a>&nbsp;&nbsp;<span class="lk"></span><a id="polyEdit" style="cursor: pointer;" href="javascript:void(0)"> Editar</a></td><td class="navRight"><button id="cancelPoly" style="font-size:11px">Cancelar</button></td><td class="navRight"><button id="okPoly" style="font-size:11px">OK</button></td></tr></tbody></table></div><div class="msstyle" style="display:none; position: absolute; left: 0px; top: 0px;"/></div></div>'																		
} 

GPolygonControl.prototype.me = function(){return this;} 							
        
//== main entry point to polygon functions. Called by the click event of the polygon button ==//
GPolygonControl.prototype.polygButtonClick={  
		
	on:function(){
		var me = GPolygonControl.prototype.me();
		var g = GPolygonControl.prototype.G;
		
		//***** call to turn off any other digitizer tools. needs to be added depending on what other tools are being used *******//
	 	//togToolsOff(); //togDistOff();
	 	
	 	//change the button pic
	 	if(g.ie) {
		 	var loader = '<a id="addPolygon" href="javascript:void(0)"><span id="addPolygonSpan" style="width:33px;height:33px;display:inline-block;' ;
	       	loader +=  "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='Images/addashapeP.png');" ;
	      	loader +=  '"><img id="addPolygonPic" style="filter:progid:DXImageTransform.Microsoft.Alpha(opacity=0);" src="Images/addashapeP.png" width="33" height="33" border="0" alt=""></span></a>'; 
	      	$('#addPolygonDiv').html(loader);	
	 	} else {
	 		$('#addPolygonPic').attr("src","Images/addashapeP.png");
	 	}
	 	
	 	//start the click handler
	 	me.polygpointClick.add();
	 	
	 	//add a custom tooltip
	 	me.cursorTooltip.show("Click para adicionar puntos, click sobre el ultimo punto para cerrar el poligono.");
	    			 
	},
	
	off:function(){
		var me = GPolygonControl.prototype.me();
		var g = GPolygonControl.prototype.G;
   		if(g.ie){
   			var loader = '<a id="addPolygon" href="javascript:void(0)"><span id="addPolygonSpan" style="width:33px;height:33px;display:inline-block;' ;
       		loader +=  "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='Images/addashape.png');" ;
      		loader +=  '"><img id="addPolygonPic" style="filter:progid:DXImageTransform.Microsoft.Alpha(opacity=0);" src="Images/addashape.png" width="33" height="33" border="0" alt=""></span></a>';
      		$('#addPolygonDiv').html(loader);
   		} else {
    	 	$('#addPolygonPic').attr("src","Images/addashape.png");			 	
    	}
 		
 		document.getElementById("map").firstChild.firstChild.style.cursor = "default";
 		if(g.polygon || g.polygonMarkers.length > 0){
 			me.removePolygon();
 		}
		g.polygon = null;
		if(g.polygon_handler) {
			me.polygpointClick.remove();
       	}
       	if(g.addnewpolygonline_handler) {
      		me.newLine.remove();
      	}
		if(me.tooltip_handler) {
			me.cursorTooltip.hide();
		}
 		//need to add additional object removal if the button is clicked before the line is finished
 		return false;
	}        		
} 

//== toggle map click listener ==//
GPolygonControl.prototype.polygpointClick = {
     
	add:function(){	
		//add the marker listener
		var me = GPolygonControl.prototype.me();
		var g = GPolygonControl.prototype.G;
	    g.polygon_handler = GEvent.addListener(map,"click", me.polygonHandlerM);	
	},
	
	remove:function(){
		//remove the cursor tooltip, listeners, etc.
		var me = GPolygonControl.prototype.me();
		var g = GPolygonControl.prototype.G; 
		me.cursorTooltip.hide();
		GEvent.removeListener(g.polygon_handler);
		g.polygon_handler = null;
	}
}

// == access the polygonHandler function depending on whether the click was on the map or on the line tracking mouse movement === //
GPolygonControl.prototype.polygonHandlerM = function(overlay,point){
	if(point){
		var me = GPolygonControl.prototype.me();
		me.polygonHandler(point);	
	}
}

// == as above ==//
GPolygonControl.prototype.polygonHandlerL = function(para){
	
	if(para){
		var me = GPolygonControl.prototype.me();
		me.polygonHandler(para);	
	}
}

GPolygonControl.prototype.polygonHandler = function(click) {
	var me = this.me(); 
	var g = this.G;
	var icon = this.icon();
	if(click){
		var point = click;
		//change cursor type
		document.getElementById("map").firstChild.firstChild.style.cursor = "crosshair";
		var marker = me.addMarkerListeners(point);
		g.polygonMarkers.push(marker);        			 
		g.polygonPoints.push(point);
		 
		map.addOverlay(marker);
		
		if(g.addnewpolygonline_handler==null) {me.newLine.add(g.lineColor);}
	
		if(g.polygonMarkers.length > 1) {
			if(g.polygon){map.removeOverlay(g.polygon);}
		 	g.polygon = new BDCCPolygon(g.polygonPoints, g.lineColor,g.lineWeight,g.lineOpacity,g.fillColor,g.fillOpacity); 
		 	map.addOverlay(g.polygon);
		}
	 }
}

GPolygonControl.prototype.cursorTooltip={
	
	show:function(message){
		var g = GPolygonControl.prototype.G;
		if(!g.tooltip_handler) {	 	
	 		g.tooltip = document.createElement("div");
	 		document.getElementById("map").appendChild(g.tooltip);
	 		g.tooltip.innerHTML = '<div style="border: 1px solid #666666; background-color: #ffffff; color: #666666;">'+ message +'</div>';
	      			
			function showMarkerTooltip(point) {
				var point1=map.getCurrentMapType().getProjection().fromLatLngToPixel(map.getBounds().getSouthWest(),map.getZoom());
				var offset=map.getCurrentMapType().getProjection().fromLatLngToPixel(point,map.getZoom());
				var anchor= new GPoint(-20,15);
				var width = -12;
				var pos = new GControlPosition(G_ANCHOR_BOTTOM_LEFT, new GSize(offset.x - point1.x - anchor.x + width,- offset.y + point1.y +anchor.y)); 
				pos.apply(g.tooltip);
		 	}	
				     
	    	g.tooltip_handler = GEvent.addListener(map, "mousemove", function(point) {
	      			showMarkerTooltip(point);
	     	});
	     }    			
	},
	
	hide:function(){
		var g = GPolygonControl.prototype.G;
      	GEvent.removeListener(g.tooltip_handler);
      	g.tooltip_handler = null;
      	document.getElementById("map").removeChild(g.tooltip);
    }
}

GPolygonControl.prototype.addMarkerListeners = function(point) {
	var me = this.me(); 
	var g = this.G;
	var icon = this.icon();

	var marker = new GMarker(point, {icon:icon, title:"Click sobre vertice para finalizar."});
	GEvent.addListener(marker,"mouseover",function(){marker.setImage(icon.imageP);});
	GEvent.addListener(marker,"mouseout",function(){marker.setImage(icon.image);});
			
	GEvent.addListener(marker,"click",function() {
			if(g.polygonPoints.length >= 2){ 
					me.polygonEnd();
			}
	});
			
 return marker;
}

//== add tracking line listener Note: ie bdccpoly vml bug adds a dashed line to first polygon object!!???!!! ==//
GPolygonControl.prototype.newLine = {
	
	add:function(lineColor){
		var me = GPolygonControl.prototype.me();
		var g = GPolygonControl.prototype.G; 
		g.addnewpolygonline_handler = GEvent.addListener(map, "mousemove", function(point) {
	    		if(g.polygonMarkers.length > 0) { 
					if(point){
						var newGLinePoints = new Array();
						newGLinePoints[0] = g.polygonPoints[g.polygonMarkers.length-1];
						if(g.newline){map.removeOverlay(g.newline);} 
						newGLinePoints[1] = point;
						//Hack: there is a bdcc vml bug here, that recreates the polyline after it has been removed, and it loses the mousemove events.
						var linestyle = (g.ie)?null:"dash";
						g.newline = new BDCCPolyline(newGLinePoints,lineColor,3,0.5,"Line",linestyle);
						GEvent.addListener(g.newline, "click", me.polygonHandlerL);
						map.addOverlay(g.newline); 
					}
				}
		});
	},
	
	remove:function() {
		var g = GPolygonControl.prototype.G; 
	    GEvent.removeListener(g.addnewpolygonline_handler);
	    if (g.newline) {map.removeOverlay(g.newline);g.newline=null;}
	    g.addnewpolygonline_handler = null;
	}
}

GPolygonControl.prototype.polygonEnd = function(){ 		
	var g = this.G;
// racj 200608
	var me = this.me(); // para que funcionen los botones de la caja de diálogo
// racj 200608
	if(g.addnewpolygonline_handler && g.polygonMarkers.length > 2) {
		if(g.polygon){map.removeOverlay(g.polygon);g.polygon=null;}//should this call the full removePolygon function???
		g.polygonPoints[g.polygonMarkers.length] = g.polygonPoints[0];
		var prmPolygon = this.createPolygon(g.polygonPoints, g.lineColor,g.lineWeight,g.lineOpacity,g.fillColor,g.fillOpacity);
		var length = g.prmPolygons.length;
		g.prmPolygons[length] = new Array();
		g.prmPolygons[length][1] = prmPolygon;
		g.prmPolygons[length][2] = "";             //reserved for numero de pisos racj 090608
		g.prmPolygons[length][3] = "";             //reserved for categoria socio-economica racj 090608
	    g.prmPolygons[length][4] = ""+g.lineColor+"";
	    g.prmPolygons[length][5] = ""+g.lineWeight+"";
	    g.prmPolygons[length][6] = ""+g.fillOpacity+"";
	    g.prmPolygons[length][7] = ""+g.fillColor+"";
		g.prmPolygons[length][8] = "";             //reserved for uso actual racj 090608
		g.prmPolygons[length][9] = "";             //reserved for edad racj 040808		
	    g.prmPolygons[length][10] = ""+g.lineOpacity+""; //racj 170708
	   	g.prmPolygons[length][11] = "";            //reserved for situacion de la edificacion racj 040808
	   	g.prmPolygons[length][12] = "";            //reserved for irregularidad en planta racj 040808
	   	g.prmPolygons[length][13] = "";            //reserved for pais racj 050808
	   	g.prmPolygons[length][14] = "";            //reserved for canton racj 050808
	   	g.prmPolygons[length][15] = "";            //reserved for ciudad racj 050808
	   	g.prmPolygons[length][16] = "";            //reserved for observacion racj 180808		

		map.addOverlay(prmPolygon);
//    	map.removeOverlay(prmPolygon);	

    	this.newLine.remove();
		this.polygpointClick.remove();
		document.getElementById("map").firstChild.firstChild.style.cursor = "default";
		
		for (i=0;i<g.polygonMarkers.length;i++) {map.removeOverlay(g.polygonMarkers[i]);}
		
		g.polygonMarkers = new Array();
		g.polygonPoints = new Array();
		
		// note: the following calls this.polygButtonClick.off() by triggering the button toggle with a click to maintain correct button state
		$("#polygonControl").trigger("click");

// racj 200608
					var center = prmPolygon.getBounds().getCenter();
					map.openInfoWindowHtml(center,(g.editInfoWindowHtml1+g.editInfoWindowHtml10+g.prmPolygons[length][15]+g.editInfoWindowHtml11+g.prmPolygons[length][16]+g.editInfoWindowHtml12+g.prmPolygons[length][3]+g.editInfoWindowHtml9+g.prmPolygons[length][14]+g.prmPolygons[length][2]+g.editInfoWindowHtml2+g.prmPolygons[length][4]+g.editInfoWindowHtml3+g.prmPolygons[length][8]+g.editInfoWindowHtml5+g.prmPolygons[length][9]+g.editInfoWindowHtml6+g.prmPolygons[length][11]+g.editInfoWindowHtml7+g.prmPolygons[length][12]+g.editInfoWindowHtml8+g.prmPolygons[length][13]+g.editInfoWindowHtml4));		
					me.addInfoWindowListeners(center, length);	// activa botones de caja de diálogo				
// racj 200608					
	}		 								
}

//== creates markers used when editing polygon ==//
GPolygonControl.prototype.createMarkerG = function(point,icon,number,color,k,last){ 
	var g = this.G;
	var icon = this.icon();
	var marker = new GMarker(point,{icon: icon, draggable: true, bouncy: false, title:"Arrastre para mover vertice. Click para finalizar edicion."});
	marker.number = parseInt(number); //retain state information for use in the listener
	GEvent.addListener(marker,"mouseover",function(){marker.setImage(icon.imageP);});
	GEvent.addListener(marker,"mouseout",function(){marker.setImage(icon.image);});
	
	GEvent.addListener(marker, "dragstart", function() {
			//start/end points need to get their respective before/after points
			g.newGLinePoints[0] = (marker.number != 0)? g.polygonPoints[parseInt(marker.number)-1]:g.polygonPoints[parseInt(last)]; 
			g.newGLinePoints2[0] = (marker.number != last)?g.polygonPoints[parseInt(marker.number+1)]:g.polygonPoints[0]; 
			
			g.adjustvertex_handler = GEvent.addListener(map, "mousemove", function(point) {
					g.newGLinePoints[1] = point;
					g.newGLinePoints2[1] = point;					
					if (g.newline1) {map.removeOverlay(g.newline1);}
					if (g.newline2) {map.removeOverlay(g.newline2);}
					
					if(marker.number != 0 && marker.number != last){
						g.newline1 = new BDCCPolyline(g.newGLinePoints.slice(0,2),color,4,0.5,"New Line","dot");
						map.addOverlay(g.newline1);					
						g.newline2 = new BDCCPolyline(g.newGLinePoints2.slice(0,2),color,4,0.5,"New Line","dot");
						map.addOverlay(g.newline2);
					} else if(marker.number == 0 || marker.number == last){
						g.newline1 = new BDCCPolyline(g.newGLinePoints.slice(0,2),color,4,0.5,"New Line","dot");
						map.addOverlay(g.newline1);
						g.newline2 = new BDCCPolyline(g.newGLinePoints2.slice(0,2),color,4,0.5,"New Line","dot");
						map.addOverlay(g.newline2);
					}
			});
	});
	
	GEvent.addListener(marker, "dragend", function() {
			var point = g.newline1.getVertex(1);
			if (g.newline1) {map.removeOverlay(g.newline1);}
			if (g.newline2) {map.removeOverlay(g.newline2);}
			g.polygonPoints.splice(parseInt(marker.number),1,point)
			g.polygonPoints.splice(0,0,g.polygonPoints[parseInt(last)]);  //overlap start and end points to close polygon
			g.polygon = GPolygonControl.prototype.createPolygon(g.polygonPoints, color,g.lineWeight,g.lineOpacity,color,g.fillOpacity,k); 
			g.polygonPoints.shift(); //delete overlapping point
			map.addOverlay(g.polygon);
			map.removeOverlay(g.prmPolygons[k][1]);
			g.prmPolygons[k][1] = g.polygon;
			GEvent.removeListener(g.adjustvertex_handler);
	});
	
	GEvent.addListener(marker, "click", function() {
		if(g.polygonMarkers.length > 0){
			for(var i=0; i<g.polygonMarkers.length; i++) {
				map.removeOverlay(g.polygonMarkers[i]);
			}
			g.polygonMarkers = new Array();
			g.polygonPoints = new Array();
			g.polygon = null;
		}
	});
	
  return marker;
}

GPolygonControl.prototype.returnVertices = function(polygon) {
	var vertices = new Array();
	  for (var i=0; i < polygon.getVertexCount(); i++) {
	  	vertices[i] = polygon.getVertex(i);
	  }
  return vertices;
}

//== external polygon creation function ==/	      
GPolygonControl.prototype.createPolygon = function(polygonPoints,lineColor,lineWeight,lineOpacity,fillColor,fillOpacity,k){ 
	var me = this.me();
	var g = this.G;
	if(typeof(k)=="undefined"){var k = g.prmPolygons.length;} //new polygons need to find k, existing polygons use preexisting k
	var prmPolygon = new BDCCPolygon(polygonPoints,lineColor,lineWeight,lineOpacity,fillColor,fillOpacity);
    GEvent.addListener(prmPolygon,"mouseover",function(){
    		prmPolygon.setFillOpacity(parseFloat(fillOpacity)+.3);
    });
    GEvent.addListener(prmPolygon,"mouseout",function(){prmPolygon.setFillOpacity(fillOpacity);});
    GEvent.addListener(prmPolygon,"click",function(para){
			if(para){
					map.openInfoWindowHtml(center,(g.editInfoWindowHtml1+g.editInfoWindowHtml10+g.prmPolygons[length][15]+g.editInfoWindowHtml11+g.prmPolygons[length][16]+g.editInfoWindowHtml12+g.prmPolygons[length][3]+g.editInfoWindowHtml9+g.prmPolygons[length][14]+g.prmPolygons[length][2]+g.editInfoWindowHtml2+g.prmPolygons[length][4]+g.editInfoWindowHtml3+g.prmPolygons[length][8]+g.editInfoWindowHtml5+g.prmPolygons[length][9]+g.editInfoWindowHtml6+g.prmPolygons[length][11]+g.editInfoWindowHtml7+g.prmPolygons[length][12]+g.editInfoWindowHtml8+g.prmPolygons[length][13]+g.editInfoWindowHtml4));
				me.addInfoWindowListeners(para, k);
			} else {//mac firefox hack -- bug in normal poly click event, use getCenter instead
				var hackClick_handler = GEvent.addListener(map,"click",function(overlay,point){
					if(overlay){
						var center = overlay.getBounds().getCenter();
					map.openInfoWindowHtml(center,(g.editInfoWindowHtml1+g.editInfoWindowHtml10+g.prmPolygons[length][15]+g.editInfoWindowHtml11+g.prmPolygons[length][16]+g.editInfoWindowHtml12+g.prmPolygons[length][3]+g.editInfoWindowHtml9+g.prmPolygons[length][14]+g.prmPolygons[length][2]+g.editInfoWindowHtml2+g.prmPolygons[length][4]+g.editInfoWindowHtml3+g.prmPolygons[length][8]+g.editInfoWindowHtml5+g.prmPolygons[length][9]+g.editInfoWindowHtml6+g.prmPolygons[length][11]+g.editInfoWindowHtml7+g.prmPolygons[length][12]+g.editInfoWindowHtml8+g.prmPolygons[length][13]+g.editInfoWindowHtml4));
						me.addInfoWindowListeners(center, k);
						GEvent.removeListener(hackClick_handler);
					}
				});
			}
	});
 return prmPolygon;
}

//== edit mode for polygons ==//
GPolygonControl.prototype.adjustline = function(currentPolygon, lineColor, k){ 
	var g = GPolygonControl.prototype.G;	
	var icon = GPolygonControl.prototype.icon();
	var vertices = this.returnVertices(currentPolygon);
	g.polygonPoints = new Array();
	g.polygonMarkers = new Array();
	
	//Note: Don't return start vertex, since start/end vertices overlap
	for (var m=1; m<vertices.length; m++) {
		var marker = GPolygonControl.prototype.createMarkerG(vertices[m],icon,m-1,lineColor,k,vertices.length-2); 				
		g.polygonPoints.push(vertices[m]);
		g.polygonMarkers.push(marker);
		map.addOverlay(marker);
	}					
}

GPolygonControl.prototype.recreatePolygon = function(polygon,lineColor,lineWeight,lineOpacity,fillColor,fillOpacity,k){ 
	var me = this.me();
	var g = this.G;
	var vertices = this.returnVertices(polygon);
	map.removeOverlay(polygon);
	var newPolygon = new BDCCPolygon(vertices,lineColor,lineWeight,lineOpacity,fillColor,fillOpacity);
	GEvent.addListener(newPolygon,"mouseover",function(){
    		newPolygon.setFillOpacity(parseFloat(fillOpacity)+.3);
    });
    GEvent.addListener(newPolygon,"mouseout",function(){
    		newPolygon.setFillOpacity(fillOpacity);
    });
    GEvent.addListener(newPolygon,"click",function(para){
			if(para){
					map.openInfoWindowHtml(center,(g.editInfoWindowHtml1+g.editInfoWindowHtml10+g.prmPolygons[length][15]+g.editInfoWindowHtml11+g.prmPolygons[length][16]+g.editInfoWindowHtml12+g.prmPolygons[length][3]+g.editInfoWindowHtml9+g.prmPolygons[length][14]+g.prmPolygons[length][2]+g.editInfoWindowHtml2+g.prmPolygons[length][4]+g.editInfoWindowHtml3+g.prmPolygons[length][8]+g.editInfoWindowHtml5+g.prmPolygons[length][9]+g.editInfoWindowHtml6+g.prmPolygons[length][11]+g.editInfoWindowHtml7+g.prmPolygons[length][12]+g.editInfoWindowHtml8+g.prmPolygons[length][13]+g.editInfoWindowHtml4));
				me.addInfoWindowListeners(para, k);
			} else {//mac firefox hack -- bug in normal poly click event
				var hackClick_handler = GEvent.addListener(map,"click",function(overlay,point){
					if(overlay){
						var center = overlay.getBounds().getCenter();
					map.openInfoWindowHtml(center,(g.editInfoWindowHtml1+g.editInfoWindowHtml10+g.prmPolygons[length][15]+g.editInfoWindowHtml11+g.prmPolygons[length][16]+g.editInfoWindowHtml12+g.prmPolygons[length][3]+g.editInfoWindowHtml9+g.prmPolygons[length][14]+g.prmPolygons[length][2]+g.editInfoWindowHtml2+g.prmPolygons[length][4]+g.editInfoWindowHtml3+g.prmPolygons[length][8]+g.editInfoWindowHtml5+g.prmPolygons[length][9]+g.editInfoWindowHtml6+g.prmPolygons[length][11]+g.editInfoWindowHtml7+g.prmPolygons[length][12]+g.editInfoWindowHtml8+g.prmPolygons[length][13]+g.editInfoWindowHtml4));
						me.addInfoWindowListeners(center, k);
						GEvent.removeListener(hackClick_handler);
					}
				});
			}
	});
 return newPolygon;
}

GPolygonControl.prototype.addInfoWindowListeners = function(point, k) {
	var me = this.me();
	var g = this.G;
	var currentPolygon = g.prmPolygons[k][1]
	g.currentcolor = g.prmPolygons[k][7];

	//onchange listeners for title and description values
	$('#nump').change(function() {
		g.prmPolygons[k][2] = $('#nump').val();
	});
	
	$('#cse').change(function() {
		g.prmPolygons[k][3] = $('#cse').val();
	});
	
	$('#usa').change(function() {
		g.prmPolygons[k][8] = $('#usa').val();
	});	

	$('#edad').change(function() {
		g.prmPolygons[k][9] = $('#edad').val();
	});	
	
	$('#sie').change(function() {
		g.prmPolygons[k][11] = $('#sie').val();
	});
	
	$('#irp').change(function() {
		g.prmPolygons[k][12] = $('#irp').val();
	});
	
	$('#pai').change(function() {
		g.prmPolygons[k][13] = $('#pai').val();
	});
	
	$('#can').change(function() {
		g.prmPolygons[k][14] = $('#can').val();
	});	
	
	$('#ciu').change(function() {
		g.prmPolygons[k][15] = $('#ciu').val();
	});
	
	$('#obs').change(function() {
		g.prmPolygons[k][16] = $('#obs').val();
	});	


var colorHtml = '<div id="colorPickerDiv" style="position: relative; z-index:100; top:0px; left:0px; width:284px; height:344px; background-image:url(Images/transparent.gif)"><form action="javascript:void(0);" style="width: 274px;">  <div class="form-item"><label for="color"></label><input type="text" style="display:none" id="color" name="color" value="#123456" /></div><div id="picker2"></div></form><table class="msstyle" style="height: 118px;"><tbody><tr><td style="vertical-align: top;"><table class="msline"><tbody><tr><td colspan="2"><b class="title">Edit line style</b></td></tr><tr><td class="label">Line width (pixels, 1-20)</td><td><input id="polygonWeight" class="numberfield" type="text" size="3" value="'+g.prmPolygons[k][5]+'"/></td></tr><tr><td class="label">Fill opacity (10-100)</td><td><input class="numberfield" id="polygonOpacity" type="text" size="3" value="'+g.prmPolygons[k][6]*100+'"/></td></tr></tbody></table></td></tr><tr><td><table><tbody><tr><td class="navLeft"/><td class="navRight"><button id="cancelPoly2">Cancel</button></td><td class="navRight"><button id="okPoly2">OK</button></td></tr></tbody></table></td></tr></tbody></table></div>';
				
	//bind color link
	$('#colorIcon').click(function(){
    		map.openInfoWindowHtml(point,colorHtml);
    		var farb = $.farbtastic('#picker2','#color');
    		farb.setColor(g.prmPolygons[k][7]);
			$("#okPoly2").click(function(){
				
				g.lineWeight = g.prmPolygons[k][5] = (parseInt($("#polygonWeight").val()) > 20 || parseInt($("#polylgonWeight").val()) < 1 || isNaN($("#polygonWeight").val()) )?g.prmPolygons[k][5]:$("#polygonWeight").val();
				g.fillOpacity = g.prmPolygons[k][6] = (parseInt($("#polygonOpacity").val()) > 100 || parseInt($("#polygonOpacity").val()) < 10 || isNaN($("#polygonOpacity").val()) )?g.prmPolygons[k][6]:($("#polygonOpacity").val()/100);
				g.fillColor = g.prmPolygons[k][7] = g.currentcolor = g.lineColor = $('#color').val();
				//restart original process
					map.openInfoWindowHtml(center,(g.editInfoWindowHtml1+g.editInfoWindowHtml10+g.prmPolygons[length][15]+g.editInfoWindowHtml11+g.prmPolygons[length][16]+g.editInfoWindowHtml12+g.prmPolygons[length][3]+g.editInfoWindowHtml9+g.prmPolygons[length][14]+g.prmPolygons[length][2]+g.editInfoWindowHtml2+g.prmPolygons[length][4]+g.editInfoWindowHtml3+g.prmPolygons[length][8]+g.editInfoWindowHtml5+g.prmPolygons[length][9]+g.editInfoWindowHtml6+g.prmPolygons[length][11]+g.editInfoWindowHtml7+g.prmPolygons[length][12]+g.editInfoWindowHtml8+g.prmPolygons[length][13]+g.editInfoWindowHtml4));
				me.addInfoWindowListeners(point,k);
				$('#currentColor').css("background-color", g.currentcolor);
			});
			$("#cancelPoly2").click(function(){
					map.openInfoWindowHtml(center,(g.editInfoWindowHtml1+g.editInfoWindowHtml10+g.prmPolygons[length][15]+g.editInfoWindowHtml11+g.prmPolygons[length][16]+g.editInfoWindowHtml12+g.prmPolygons[length][3]+g.editInfoWindowHtml9+g.prmPolygons[length][14]+g.prmPolygons[length][2]+g.editInfoWindowHtml2+g.prmPolygons[length][4]+g.editInfoWindowHtml3+g.prmPolygons[length][8]+g.editInfoWindowHtml5+g.prmPolygons[length][9]+g.editInfoWindowHtml6+g.prmPolygons[length][11]+g.editInfoWindowHtml7+g.prmPolygons[length][12]+g.editInfoWindowHtml8+g.prmPolygons[length][13]+g.editInfoWindowHtml4));
				me.addInfoWindowListeners(point,k);
			});
			$("#polygonWeight").change(function(){
				if(parseInt($("#polygonWeight").val()) > 20 || parseInt($("#polygonWeight").val()) < 1 || isNaN($("#polygonWeight").val()) ) {
					alert("Out of Range. Please select a number between 1 & 20");
					$("#polygonWeight").val(""+g.prmPolygons[k][5]+"");
				}
			});
			$("#polygonOpacity").change(function(){
				if(parseInt($("#polygonOpacity").val()) > 100 || parseInt($("#polygonOpacity").val()) < 10 || isNaN($("#polygonOpacity").val()) ) {
					alert("Out of Range. Please select a number between 10 & 100");
					$("#polygonOpacity").val(""+g.prmPolygons[k][6]+"");
				}
			});
      	return false;
	}); 
	
	//bind delete link
	$("#polyDelete").click(function(){
		 map.removeOverlay(currentPolygon);
		 g.prmPolygons.splice(k,1);
		 
		 //remove edit markers if present
		 for (i=0;i<g.polygonMarkers.length;i++) {
		 	map.removeOverlay(g.polygonMarkers[i]);
		  }
		   
		 map.closeInfoWindow();
		 $('#colorPickerDiv').css("display", "none");
		 g.polygonMarkers = new Array();
		 g.polygonPoints = new Array();
	});  
 			 
 	//bind edit link
 	$("#polyEdit").click(function(){		
	   	me.adjustline(currentPolygon,g.prmPolygons[k][7],k);
	   	map.closeInfoWindow();
		$('#colorPickerDiv').css("display", "none");
	}); 
 		   
	//cancel button
	$("#cancelPoly").click(function() {
	   		map.closeInfoWindow();
	   		$('#colorPickerDiv').css("display", "none");
	});
	   	
	// ok button
	$("#okPoly").click(function() {
	   	var newPolygon = me.recreatePolygon(currentPolygon,g.lineColor,g.lineWeight,g.lineOpacity,g.currentcolor,g.fillOpacity,k); 
	   	map.addOverlay(newPolygon);
	   	g.prmPolygons[k][1] = newPolygon;
	   	g.prmPolygons[k][2] = $("#nump").val();
	   	g.prmPolygons[k][3] = $("#cse").val();
	   	g.prmPolygons[k][4] = g.currentcolor;
	   	//g.prmPolygons[k][5] = g.lineWeight; //set above in color ok button
	   	//g.prmPolygons[k][6] = g.fillOpacity;
	   	//g.prmPolygons[k][7] = g.currentcolor;
	   	g.prmPolygons[k][8] = $("#usa").val();
	   	g.prmPolygons[k][9] = $("#edad").val();
	   	g.prmPolygons[k][10] = g.lineOpacity;
	   	g.prmPolygons[k][11] = $("#sie").val();
	   	g.prmPolygons[k][12] = $("#irp").val();
	   	g.prmPolygons[k][13] = $("#pai").val();
	   	g.prmPolygons[k][14] = $("#can").val();
	   	g.prmPolygons[k][15] = $("#ciu").val();	
	   	g.prmPolygons[k][16] = $("#obs").val();			
		
          var areaPoly = newPolygon.getArea();
          var placemark = "";
          var placemark2 = "";		  
		  var lbrckt = "[";
		  var rbrckt = "]";		  
	      var vertices = polyCtrl.returnVertices(currentPolygon);
		           	   for (var i=0; i<vertices.length - 1; i++) {
                           var lngth = vertices.length;
  				           var lat = vertices[i].lat();
				           var lon = vertices[i].lng();
				   		   var xxx = placemark += "new GLatLng(" + lat + ", " + lon + ")" + ",";
						   var zzz = placemark2 += lat + "," + lon + ",";
						   var vvv = zzz + vertices[0].lat() + "," + vertices[0].lng();
						   var yyy = lbrckt + xxx + "new GLatLng(" + vertices[0].lat() + "," + vertices[0].lng() + ")" + rbrckt;						   
					   }
	   	$.post("twbscripts/bcksjs.php",{prmPoly: yyy,usa: $("#usa").val(),nump: $("#nump").val(),edad: $("#edad").val(),cse: $("#cse").val(),sie: $("#sie").val(),irp: $("#irp").val(),pai: $("#pai").val(),can: $("#can").val(),ciu: $("#ciu").val(),obs: $("#obs").val(),lineColor: g.lineColor,lineWeight: g.lineWeight,fillOpacity: g.fillOpacity,areaPoly: areaPoly,fillColor: g.currentcolor,lineOpacity: g.lineOpacity,lngPoly: lngth,coorPoly: vvv,action: "postdata"});

	   	map.closeInfoWindow();
	   	$('#colorPickerDiv').css("display", "none");
	 });  								
}

GPolygonControl.prototype.removePolygon = function(){
	 var g = this.G;
	 if(g.polygon){map.removeOverlay(g.polygon);}
	 for (i=0;i<g.polygonMarkers.length;i++) {
		map.removeOverlay(g.polygonMarkers[i]);
	}
	 map.closeInfoWindow();
	 if(g.newline){map.removeOverlay(g.newline);g.newline=null;}
	 g.polygonMarkers = new Array();
	 g.polygonPoints = new Array();
	 map.closeInfoWindow();
	 GEvent.removeListener(g.addnewpolygonline_handler);
	 GEvent.removeListener(g.polygon_handler);
}
// JavaScript Document
