// 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 GPolylineControl() {}
     
GPolylineControl.prototype = new GControl();
GPolylineControl.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 = "polylineControl";

   // Handle transparent PNG files in MSIE
   if(me.ie) {
     var loader = '<a id="addPolyline" href="javascript:void(0)"><span id="addPolylineSpan" style="width:33px;height:33px;display:inline-block;' ;
     loader +=  "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='Images/addapolyl.png');" ;
     loader +=  '"><img id="addPolylinePic" style="filter:progid:DXImageTransform.Microsoft.Alpha(opacity=0);" src="Images/addapolyl.png" width="33" height="33" border="0" alt=""></span></a>'; 
     containerP.innerHTML = '<div id="addPolylineDiv" style="height:33px; width:33px; cursor="pointer">'+loader+'</div>';
   } else {
     containerP.innerHTML = '<a id="addPolyline" href="javascript:void(0)"><img id="addPolylinePic" src="Images/addapolyl.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);
   $("#polylineControl").toggle(function(){me.polylButtonClick.on();},function(){me.polylButtonClick.off();});
   
  return containerP;
}
       
// == Set the default position for the control ==//
GPolylineControl.prototype.getDefaultPosition = function(){
     return new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(100, 0));
}      

// == create default coordinate icon ==//
GPolylineControl.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 ==//
GPolylineControl.prototype.G={
								ie:(navigator.userAgent.indexOf("MSIE")==-1)?false:true,
								polyline:null,
								tooltip:null,
								tooltip_handler:null,
								polyline_handler:null,
								addnewpolylineline_handler:null,
								polylineMarkers:new Array(),
								polylinePoints:new Array(),
								newline:null,
								prmPolylines: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:"#B62084", // #FF6600 orange light line - #FFF0F5 crema claro - #B62084 rojo sangretoro
								lineWeight:4,
								lineOpacity:.75,
//								fillColor:"#FF8C00", // 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="Colombia">Colombia</option>',
	 /*+g.prmPolylines[k][13]+*/  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.prmPolylines[k][4]+*/  editInfoWindowHtml3:'"/></div></td></tr><div><table><tr><td align=right>Tipo linea:</td><td align=left><select id=usa style="vertical-align: middle;font-size:11px;"><option value="cicloruta">cicloruta</option><option value="peatonal">peatonal</option><option value="limite">limite</option><option value="puente">puente</option><option value="via">via</option>',	 
	 /*+g.prmPolylines[k][8]+*/  editInfoWindowHtml5:'</select></td><table><tr><td align=right>Estado:</td><td align=left><select id=edad style="vertical-align: middle;font-size:11px;"><option value="bueno">bueno</option><option value="regular">regular</option><option value="malo">malo</option>',	 
	 /*+g.prmPolylines[k][9]+*/  
	 /*+g.prmPolylines[k][2]+*/  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.prmPolylines[k][14]+*/  editInfoWindowHtml12:'</select></td><table><tr><td align=right>Ciudad:</td><td align=left><select id=ciu style="vertical-align: middle;font-size:11px;"><option value="Bogota">Bogota</option>',
 	 /*+g.prmPolylines[k][15]+*/  editInfoWindowHtml13:'</select></td><div class="msedit"><table class="iwspan"><tbody><tr><td><table class="inputField"><tbody><tr><td class="label" style="font-size:11px;">Observacion:</td><td><input id="obs" class="title" type="text" style="font-size:11px" value="',
	 /*+g.prmPolylines[k][16]+*/   editInfoWindowHtml4:'"/></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;<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>'																		
} 

GPolylineControl.prototype.me = function(){return this;} 							
        
//== main entry point to polygon functions. Called by the click event of the polygon button ==//
GPolylineControl.prototype.polylButtonClick={  
		
	on:function(){
		var me = GPolylineControl.prototype.me();
		var g = GPolylineControl.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="addPolyline" href="javascript:void(0)"><span id="addPolylineSpan" style="width:33px;height:33px;display:inline-block;' ;
	       	loader +=  "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='Images/addapolylP.png');" ;
	      	loader +=  '"><img id="addPolylinePic" style="filter:progid:DXImageTransform.Microsoft.Alpha(opacity=0);" src="Images/addapolylP.png" width="33" height="33" border="0" alt=""></span></a>'; 
	      	$('#addPolylineDiv').html(loader);	
	 	} else {
	 		$('#addPolylinePic').attr("src","Images/addapolylP.png");
	 	}
	 	
	 	//start the click handler
	 	me.polylpointClick.add();
	 	
	 	//add a custom tooltip
	 	me.cursorTooltip.show("Click para adicionar puntos, click sobre el ultimo punto para terminar.");
	    			 
	},
	
	off:function(){
		var me = GPolylineControl.prototype.me();
		var g = GPolylineControl.prototype.G;
   		if(g.ie){
   			var loader = '<a id="addPolyline" href="javascript:void(0)"><span id="addPolylineSpan" style="width:33px;height:33px;display:inline-block;' ;
       		loader +=  "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='Images/addapolyl.png');" ;
      		loader +=  '"><img id="addPolylinePic" style="filter:progid:DXImageTransform.Microsoft.Alpha(opacity=0);" src="Images/addapolyl.png" width="33" height="33" border="0" alt=""></span></a>';
      		$('#addPolylineDiv').html(loader);
   		} else {
    	 	$('#addPolylinePic').attr("src","Images/addapolyl.png");			 	
    	}
 		
 		document.getElementById("mapDiv").firstChild.firstChild.style.cursor = "default";
 		if(g.polyline || g.polylineMarkers.length > 0){
 			me.removePolyline();
 		}
		g.polyline = null;
		if(g.polyline_handler) {
			me.polylpointClick.remove();
       	}
       	if(g.addnewpolylineline_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 ==//
GPolylineControl.prototype.polylpointClick = {
     
	add:function(){	
		//add the marker listener
		var me = GPolylineControl.prototype.me();
		var g = GPolylineControl.prototype.G;
	    g.polyline_handler = GEvent.addListener(map,"click", me.polylineHandlerM);	
	},
	
	remove:function(){
		//remove the cursor tooltip, listeners, etc.
		var me = GPolylineControl.prototype.me();
		var g = GPolylineControl.prototype.G; 
		me.cursorTooltip.hide();
		GEvent.removeListener(g.polyline_handler);
		g.polyline_handler = null;
	}
}

// == access the polygonHandler function depending on whether the click was on the map or on the line tracking mouse movement === //
GPolylineControl.prototype.polylineHandlerM = function(overlay,point){
	if(point){
		var me = GPolylineControl.prototype.me();
		me.polylineHandler(point);	
	}
}

// == as above ==//
GPolylineControl.prototype.polylineHandlerL = function(para){
	
	if(para){
		var me = GPolylineControl.prototype.me();
		me.polylineHandler(para);	
	}
}

GPolylineControl.prototype.polylineHandler = function(click) {
	var me = this.me(); 
	var g = this.G;
	var icon = this.icon();
	if(click){
		var point = click;
		//change cursor type
		document.getElementById("mapDiv").firstChild.firstChild.style.cursor = "crosshair";
		var marker = me.addMarkerListeners(point);
		g.polylineMarkers.push(marker);        			 
		g.polylinePoints.push(point);
		 
		map.addOverlay(marker);
		
		if(g.addnewpolylineline_handler==null) {me.newLine.add(g.lineColor);}
	
		if(g.polylineMarkers.length > 1) {
			if(g.polyline){map.removeOverlay(g.polyline);}
		 	g.polyline = new BDCCPolyline(g.polylinePoints, g.lineColor,g.lineWeight,g.lineOpacity); 
		 	map.addOverlay(g.polyline);
		}
	 }
}

GPolylineControl.prototype.cursorTooltip={
	
	show:function(message){
		var g = GPolylineControl.prototype.G;
		if(!g.tooltip_handler) {	 	
	 		g.tooltip = document.createElement("div");
	 		document.getElementById("mapDiv").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 = GPolylineControl.prototype.G;
      	GEvent.removeListener(g.tooltip_handler);
      	g.tooltip_handler = null;
      	document.getElementById("mapDiv").removeChild(g.tooltip);
    }
}

GPolylineControl.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.polylinePoints.length >= 2){ 
					me.polylineEnd();
			}
	});
			
 return marker;
}

//== add tracking line listener Note: ie bdccpoly vml bug adds a dashed line to first polygon object!!???!!! ==//
GPolylineControl.prototype.newLine = {
	
	add:function(lineColor){
		var me = GPolylineControl.prototype.me();
		var g = GPolylineControl.prototype.G; 
		g.addnewpolylineline_handler = GEvent.addListener(map, "mousemove", function(point) {
	    		if(g.polylineMarkers.length > 0) { 
					if(point){
						var newGLinePoints = new Array();
						newGLinePoints[0] = g.polylinePoints[g.polylineMarkers.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.polylineHandlerL);
						map.addOverlay(g.newline); 
					}
				}
		});
	},
	
	remove:function() {
		var g = GPolylineControl.prototype.G; 
	    GEvent.removeListener(g.addnewpolylineline_handler);
	    if (g.newline) {map.removeOverlay(g.newline);g.newline=null;}
	    g.addnewpolylineline_handler = null;
	}
}

GPolylineControl.prototype.polylineEnd = 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.addnewpolylineline_handler && g.polylineMarkers.length > 2) {
		if(g.polyline){map.removeOverlay(g.polyline);g.polyline=null;}//should this call the full removePolygon function???
		g.polylinePoints[g.polylineMarkers.length] = g.polylinePoints[1000]; // con [0] cierra el polígono, con [1] lo deja abierto RACJ 210709
		var prmPolyline = this.createPolyline(g.polylinePoints, g.lineColor,g.lineWeight,g.lineOpacity);
		var length = g.prmPolylines.length;
		g.prmPolylines[length] = new Array();
		g.prmPolylines[length][1] = prmPolyline;
		g.prmPolylines[length][2] = "";             //reserved for numero de pisos racj 090608
		g.prmPolylines[length][3] = "";             //reserved for categoria socio-economica racj 090608
	    g.prmPolylines[length][4] = ""+g.lineColor+"";
	    g.prmPolylines[length][5] = ""+g.lineWeight+"";
//	    g.prmPolylines[length][6] = ""+g.fillOpacity+"";
//	    g.prmPolylines[length][7] = ""+g.fillColor+"";
		g.prmPolylines[length][8] = "";             //reserved for uso actual racj 090608
		g.prmPolylines[length][9] = "";             //reserved for edad racj 040808		
	    g.prmPolylines[length][10] = ""+g.lineOpacity+""; //racj 170708
	   	g.prmPolylines[length][11] = "";            //reserved for situacion de la edificacion racj 040808
	   	g.prmPolylines[length][12] = "";            //reserved for irregularidad en planta racj 040808
	   	g.prmPolylines[length][13] = "";            //reserved for pais racj 050808
	   	g.prmPolylines[length][14] = "";            //reserved for canton racj 050808
	   	g.prmPolylines[length][15] = "";            //reserved for ciudad racj 050808
	   	g.prmPolylines[length][16] = "";            //reserved for observacion racj 180808		

		map.addOverlay(prmPolyline);
//    	map.removeOverlay(prmPolygon);	

    	this.newLine.remove();
		this.polylpointClick.remove();
		document.getElementById("mapDiv").firstChild.firstChild.style.cursor = "default";
		
		for (i=0;i<g.polylineMarkers.length;i++) {map.removeOverlay(g.polylineMarkers[i]);}
		
		g.polylineMarkers = new Array();
		g.polylinePoints = new Array();
		
		// note: the following calls this.polygButtonClick.off() by triggering the button toggle with a click to maintain correct button state
		$("#polylineControl").trigger("click");

// racj 200608
					var center = prmPolyline.getBounds().getCenter();
					map.openInfoWindowHtml(center,(g.editInfoWindowHtml1+g.editInfoWindowHtml10+g.prmPolylines[length][14]+g.editInfoWindowHtml12+g.prmPolylines[length][15]+g.editInfoWindowHtml3+g.prmPolylines[length][8]+g.editInfoWindowHtml5+g.prmPolylines[length][9]+g.editInfoWindowHtml6+g.prmPolylines[length][3]+g.editInfoWindowHtml7+g.prmPolylines[length][11]+g.editInfoWindowHtml8+g.prmPolylines[length][12]+g.editInfoWindowHtml9+g.prmPolylines[length][2]+g.editInfoWindowHtml13+g.prmPolylines[length][16]+g.editInfoWindowHtml4));		
					me.addInfoWindowListeners(center, length);	// activa botones de caja de diálogo				
// racj 200608					
	}		 								
}

//== creates markers used when editing polygon ==//
GPolylineControl.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.polylinePoints[parseInt(marker.number)-1]:g.polylinePoints[parseInt(last)]; 
			g.newGLinePoints2[0] = (marker.number != last)?g.polylinePoints[parseInt(marker.number+1)]:g.polylinePoints[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.polylinePoints.splice(parseInt(marker.number),1,point)
			g.polylinePoints.splice(0,0,g.polylinePoints[parseInt(last)]);  //overlap start and end points to close polygon
			g.polyline = GPolylineControl.prototype.createPolyline(g.polylinePoints, color,g.lineWeight,g.lineOpacity,color,k); 
			g.polylinePoints.shift(); //delete overlapping point
			map.addOverlay(g.polyline);
			map.removeOverlay(g.prmPolylines[k][1]);
			g.prmPolylines[k][1] = g.polyline;
			GEvent.removeListener(g.adjustvertex_handler);
	});
	
	GEvent.addListener(marker, "click", function() {
		if(g.polylineMarkers.length > 0){
			for(var i=0; i<g.polylineMarkers.length; i++) {
				map.removeOverlay(g.polylineMarkers[i]);
			}
			g.polylineMarkers = new Array();
			g.polylinePoints = new Array();
			g.polyline = null;
		}
	});
	
  return marker;
}

GPolylineControl.prototype.returnVertices = function(polyline) {
	var vertices = new Array();
	  for (var i=0; i < polyline.getVertexCount(); i++) {
	  	vertices[i] = polyline.getVertex(i);
	  }
  return vertices;
}

//== external polygon creation function ==/	      
GPolylineControl.prototype.createPolyline = function(polylinePoints,lineColor,lineWeight,lineOpacity,k){ 
	var me = this.me();
	var g = this.G;
	if(typeof(k)=="undefined"){var k = g.prmPolylines.length;} //new polygons need to find k, existing polygons use preexisting k
	var prmPolyline = new BDCCPolyline(polylinePoints,lineColor,lineWeight,lineOpacity);
//    GEvent.addListener(prmPolyline,"mouseover",function(){
//    		prmPolyline.setFillOpacity(parseFloat(fillOpacity)+.3);
//    });
//    GEvent.addListener(prmPolyline,"mouseout",function(){prmPolyline.setFillOpacity(fillOpacity);});
    GEvent.addListener(prmPolyline,"click",function(para){
			if(para){
					map.openInfoWindowHtml(center,(g.editInfoWindowHtml1+g.editInfoWindowHtml10+g.prmPolylines[length][14]+g.editInfoWindowHtml12+g.prmPolylines[length][15]+g.editInfoWindowHtml3+g.prmPolylines[length][8]+g.editInfoWindowHtml5+g.prmPolylines[length][9]+g.editInfoWindowHtml6+g.prmPolylines[length][3]+g.editInfoWindowHtml7+g.prmPolylines[length][11]+g.editInfoWindowHtml8+g.prmPolylines[length][12]+g.editInfoWindowHtml9+g.prmPolylines[length][2]+g.editInfoWindowHtml13+g.prmPolylines[length][16]+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.prmPolylines[length][14]+g.editInfoWindowHtml12+g.prmPolylines[length][15]+g.editInfoWindowHtml3+g.prmPolylines[length][8]+g.editInfoWindowHtml5+g.prmPolylines[length][9]+g.editInfoWindowHtml6+g.prmPolylines[length][3]+g.editInfoWindowHtml7+g.prmPolylines[length][11]+g.editInfoWindowHtml8+g.prmPolylines[length][12]+g.editInfoWindowHtml9+g.prmPolylines[length][2]+g.editInfoWindowHtml13+g.prmPolylines[length][16]+g.editInfoWindowHtml4));
						me.addInfoWindowListeners(center, k);
						GEvent.removeListener(hackClick_handler);
					}
				});
			}
	});
 return prmPolyline;
}

//== edit mode for polygons ==//
GPolylineControl.prototype.adjustline = function(currentPolyline, lineColor, k){ 
	var g = GPolylineControl.prototype.G;	
	var icon = GPolylineControl.prototype.icon();
	var vertices = this.returnVertices(currentPolyline);
	g.polylinePoints = new Array();
	g.polylineMarkers = new Array();
	
	//Note: Don't return start vertex, since start/end vertices overlap
	for (var m=1; m<vertices.length; m++) {
		var marker = GPolylineControl.prototype.createMarkerG(vertices[m],icon,m-1,lineColor,k,vertices.length-2); 				
		g.polylinePoints.push(vertices[m]);
		g.polylineMarkers.push(marker);
		map.addOverlay(marker);
	}					
}

GPolylineControl.prototype.recreatePolyline = function(polyline,lineColor,lineWeight,lineOpacity,k){ 
	var me = this.me();
	var g = this.G;
	var vertices = this.returnVertices(polyline);
	map.removeOverlay(polyline);
	var newPolyline = new BDCCPolyline(vertices,lineColor,lineWeight,lineOpacity);
//	GEvent.addListener(newPolyline,"mouseover",function(){
//    		newPolyline.setFillOpacity(parseFloat(fillOpacity)+.3);
//    });
//    GEvent.addListener(newPolyline,"mouseout",function(){
//    		newPolyline.setFillOpacity(fillOpacity);
//    });
    GEvent.addListener(newPolyline,"click",function(para){
			if(para){
					map.openInfoWindowHtml(center,(g.editInfoWindowHtml1+g.editInfoWindowHtml10+g.prmPolylines[length][14]+g.editInfoWindowHtml12+g.prmPolylines[length][15]+g.editInfoWindowHtml3+g.prmPolylines[length][8]+g.editInfoWindowHtml5+g.prmPolylines[length][9]+g.editInfoWindowHtml6+g.prmPolylines[length][3]+g.editInfoWindowHtml7+g.prmPolylines[length][11]+g.editInfoWindowHtml8+g.prmPolylines[length][12]+g.editInfoWindowHtml9+g.prmPolylines[length][2]+g.editInfoWindowHtml13+g.prmPolylines[length][16]+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.prmPolylines[length][14]+g.editInfoWindowHtml12+g.prmPolylines[length][15]+g.editInfoWindowHtml3+g.prmPolylines[length][8]+g.editInfoWindowHtml5+g.prmPolylines[length][9]+g.editInfoWindowHtml6+g.prmPolylines[length][3]+g.editInfoWindowHtml7+g.prmPolylines[length][11]+g.editInfoWindowHtml8+g.prmPolylines[length][12]+g.editInfoWindowHtml9+g.prmPolylines[length][2]+g.editInfoWindowHtml13+g.prmPolylines[length][16]+g.editInfoWindowHtml4));
						me.addInfoWindowListeners(center, k);
						GEvent.removeListener(hackClick_handler);
					}
				});
			}
	});
 return newPolyline;
}

GPolylineControl.prototype.addInfoWindowListeners = function(point, k) {
	var me = this.me();
	var g = this.G;
	var currentPolyline = g.prmPolylines[k][1]
	g.currentcolor = g.prmPolylines[k][7];

	//onchange listeners for title and description values
	$('#nump').change(function() {
		g.prmPolylines[k][2] = $('#nump').val();
	});
	
	$('#cse').change(function() {
		g.prmPolylines[k][3] = $('#cse').val();
	});
	
	$('#usa').change(function() {
		g.prmPolylines[k][8] = $('#usa').val();
	});	

	$('#edad').change(function() {
		g.prmPolylines[k][9] = $('#edad').val();
	});	
	
	$('#sie').change(function() {
		g.prmPolylines[k][11] = $('#sie').val();
	});
	
	$('#irp').change(function() {
		g.prmPolylines[k][12] = $('#irp').val();
	});
	
	$('#pai').change(function() {
		g.prmPolylines[k][13] = $('#pai').val();
	});
	
	$('#can').change(function() {
		g.prmPolylines[k][14] = $('#can').val();
	});	
	
	$('#ciu').change(function() {
		g.prmPolylines[k][15] = $('#ciu').val();
	});
	
	$('#obs').change(function() {
		g.prmPolylines[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="polylineWeight" class="numberfield" type="text" size="3" value="'+g.prmPolylines[k][5]+'"/></td></tr><tr><td class="label">Fill opacity (10-100)</td><td><input class="numberfield" id="polylineOpacity" type="text" size="3" value="'+g.prmPolylines[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.prmPolylines[k][7]);
			$("#okPoly2").click(function(){
				
				g.lineWeight = g.prmPolylines[k][5] = (parseInt($("#polylineWeight").val()) > 20 || parseInt($("#polylgonWeight").val()) < 1 || isNaN($("#polylineWeight").val()) )?g.prmPolylines[k][5]:$("#polylineWeight").val();
				g.fillOpacity = g.prmPolylines[k][6] = (parseInt($("#polylineOpacity").val()) > 100 || parseInt($("#polylineOpacity").val()) < 10 || isNaN($("#polylineOpacity").val()) )?g.prmPolylines[k][6]:($("#polylineOpacity").val()/100);
				g.fillColor = g.prmPolylines[k][7] = g.currentcolor = g.lineColor = $('#color').val();
				//restart original process
					map.openInfoWindowHtml(center,(g.editInfoWindowHtml1+g.editInfoWindowHtml10+g.prmPolylines[length][14]+g.editInfoWindowHtml12+g.prmPolylines[length][15]+g.editInfoWindowHtml3+g.prmPolylines[length][8]+g.editInfoWindowHtml5+g.prmPolylines[length][9]+g.editInfoWindowHtml6+g.prmPolylines[length][3]+g.editInfoWindowHtml7+g.prmPolylines[length][11]+g.editInfoWindowHtml8+g.prmPolylines[length][12]+g.editInfoWindowHtml9+g.prmPolylines[length][2]+g.editInfoWindowHtml13+g.prmPolylines[length][16]+g.editInfoWindowHtml4));
				me.addInfoWindowListeners(point,k);
				$('#currentColor').css("background-color", g.currentcolor);
			});
			$("#cancelPoly2").click(function(){
					map.openInfoWindowHtml(center,(g.editInfoWindowHtml1+g.editInfoWindowHtml10+g.prmPolylines[length][14]+g.editInfoWindowHtml12+g.prmPolylines[length][15]+g.editInfoWindowHtml3+g.prmPolylines[length][8]+g.editInfoWindowHtml5+g.prmPolylines[length][9]+g.editInfoWindowHtml6+g.prmPolylines[length][3]+g.editInfoWindowHtml7+g.prmPolylines[length][11]+g.editInfoWindowHtml8+g.prmPolylines[length][12]+g.editInfoWindowHtml9+g.prmPolylines[length][2]+g.editInfoWindowHtml13+g.prmPolylines[length][16]+g.editInfoWindowHtml4));
				me.addInfoWindowListeners(point,k);
			});
			$("#polylineWeight").change(function(){
				if(parseInt($("#polylineWeight").val()) > 20 || parseInt($("#polylineWeight").val()) < 1 || isNaN($("#polylineWeight").val()) ) {
					alert("Out of Range. Please select a number between 1 & 20");
					$("#polylineWeight").val(""+g.prmPolylines[k][5]+"");
				}
			});
			$("#polylineOpacity").change(function(){
				if(parseInt($("#polylineOpacity").val()) > 100 || parseInt($("#polylineOpacity").val()) < 10 || isNaN($("#polylineOpacity").val()) ) {
					alert("Out of Range. Please select a number between 10 & 100");
					$("#polylineOpacity").val(""+g.prmPolylines[k][6]+"");
				}
			});
      	return false;
	}); 
	
	//bind delete link
	$("#polyDelete").click(function(){
		 map.removeOverlay(currentPolyline);
		 g.prmPolylines.splice(k,1);
		 
		 //remove edit markers if present
		 for (i=0;i<g.polylineMarkers.length;i++) {
		 	map.removeOverlay(g.polylineMarkers[i]);
		  }
// borrar tabla con polígonos de cálculo 220109
//		 $.post("twbscripts/bckzhuSJ3.php",{action: "borrapoly"});
//		   
		 map.closeInfoWindow();
		 $('#colorPickerDiv').css("display", "none");
		 g.polylineMarkers = new Array();
		 g.polylinePoints = new Array();
	});  
 			 
 	//bind edit link
 	$("#polyEdit").click(function(){		
	   	me.adjustline(currentPolyline,g.prmPolylines[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 newPolyline = me.recreatePolyline(currentPolyline,g.lineColor,g.lineWeight,g.lineOpacity,g.currentcolor,k); 
	   	map.addOverlay(newPolyline);
	   	g.prmPolylines[k][1] = newPolyline;
	   	g.prmPolylines[k][2] = $("#nump").val();
	   	g.prmPolylines[k][3] = $("#cse").val();
	   	g.prmPolylines[k][4] = g.currentcolor;
	   	g.prmPolylines[k][5] = g.lineWeight; //set above in color ok button
//	   	g.prmPolylines[k][6] = g.fillOpacity;
	   	g.prmPolylines[k][7] = g.currentcolor;
	   	g.prmPolylines[k][8] = $("#usa").val();
	   	g.prmPolylines[k][9] = $("#edad").val();
	   	g.prmPolylines[k][10] = g.lineOpacity;
	   	g.prmPolylines[k][11] = $("#sie").val();
	   	g.prmPolylines[k][12] = $("#irp").val();
	   	g.prmPolylines[k][13] = $("#pai").val();
	   	g.prmPolylines[k][14] = $("#can").val();
	   	g.prmPolylines[k][15] = $("#ciu").val();	
	   	g.prmPolylines[k][16] = $("#obs").val();			
		
          var lengthPolyl = newPolyline.getLength();
          var placemark = "";
          var placemark2 = "";		  
		  var lbrckt = "[";
		  var rbrckt = "]";		  
	      var vertices = polyCtrl.returnVertices(currentPolyline);
//		           	   for (var i=0; i<vertices.length -1; i++) { // Para polígonos?
		           	   for (var i=0; i<vertices.length; 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;
						   var yyy = lbrckt + xxx + rbrckt; // sin "new GLatLng(" + vertices[0].lat() + "," + vertices[0].lng() + ")" no repite las coordenadas del último punto
					   }
	   	$.post("twbscripts/bckline.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,lengthPolyl: lengthPolyl,lineOpacity: g.lineOpacity,lngPoly: lngth,coorPoly: zzz,action: "postdata"}); // coorPoly: zzz no repite el primer punto; coorPoly: vvv adiciona el primer punto

	   	map.closeInfoWindow();
	   	$('#colorPickerDiv').css("display", "none");
	 });  								
}

GPolylineControl.prototype.removePolyline = function(){
	 var g = this.G;
	 if(g.polyline){map.removeOverlay(g.polyline);}
	 for (i=0;i<g.polylineMarkers.length;i++) {
		map.removeOverlay(g.polylineMarkers[i]);
	}
	 map.closeInfoWindow();
	 if(g.newline){map.removeOverlay(g.newline);g.newline=null;}
	 g.polylineMarkers = new Array();
	 g.polylinePoints = new Array();
	 map.closeInfoWindow();
	 GEvent.removeListener(g.addnewpolylineline_handler);
	 GEvent.removeListener(g.polyline_handler);
}
// JavaScript Document
