@import <Foundation/CPObject.j>
@import <MapKit/MKMapView.j>
@import <MapKit/MKLocation.j>
@import "RMControllerObject.j"
@import "RSMPoint.j"



@implementation RMMapController : RMControllerObject {

	id addrCompText;
	id addressButt;
	id addrTextFiel;
	id addr;
	id addrType;
	id addrCode;
	
	id baseDispDict;

	id coordinatesButt;
	id coorTextFiel;
	id cntrPopu;
	id cntyPopu;
	id cityPopu;
	id connector;

	id dstrPopu;
	id	drawCircArra;
	id drawMarkArra;
	id drawRegiArra;
	id	drawLine;
	id drawLineArra;
	id	drawQuadArra;

	id	inpuBaseButt;
	id	inpuBaseText;
	id	inpuCityText;
	id	inpuCntrText;
	id	inpuCnttText;
	id	inpuDeltText;
	id	inpuDstrText;
	id	inpuIdenText;
	id	inpuLatiMiniText;
	id	inpuLatiMaxiText;
	id	inpuLatiText;
	id	inpuLngdMiniText;
	id	inpuLngdMaxiText;
	id	inpuLngdText;
	id	inpuMessText;
	id	inpuNameText;
	id	inpuPane;
	id	inpuPoinSearQuerText;
	id	inpuPuntButt;
	id	inpuSpecText;
	id	inpuSpecLatiText;
	id	inpuSpecLongText;
	id	inpuStreText;

	id lastName1TextFiel;
	id lastName2TextFiel;

	id mainPane;
	id mapPane;
	id mapView;
	id markRed;
	id markArra;
	id messText;
	id mousLoca;

	id nameClieTextFiel;

	id	radiTextFiel;

	id persId;

	id refeButt;
	id refeConsPopu;
	id referenceDict;
	id refeDispDict;
	id referenceDispButt;
	id referenceNewText;
	id refePopu;
	id referenceSearExacButt;
	id referenceSearLikeButt;
	id referenceSearText;
	id referenceViewButt;

	id	specDispDict;
	id statPopu;
	
	id wind;

	id RAclieCodeTextFiel;
	id RAknowAddrPopu;

	id searButt;
	id cleaButt;

	id typeAddrFiel;
	id fullAddrTextFiel;
	id teleFiel;
	id auxSele;
	
}



- (CPString) address {
	return [addrCompText stringValue];
}



- (void) addressAction {
	var text= [addrCompText stringValue];
	var textArra= [text componentsSeparatedByString:@"*"];
	if ( [textArra count]==1 )
		textArra= [text componentsSeparatedByString:@","];
	if ( [textArra count]==2 ) {
		var charSet= [CPCharacterSet whitespaceAndNewlineCharacterSet];
		var refeText= [[textArra objectAtIndex:0] stringByTrimmingCharactersInSet:charSet];
		var refeTextArra= [refeText componentsSeparatedByString:@" "];
		var refeTextArraCoun= [refeTextArra count];
		if ( refeTextArraCoun==1 ) {
			[referenceSearText setStringValue:refeText];
		}
		else {
			var refeComp= @"";
			var i;
			for ( i=0; i<refeTextArraCoun; i++ ) {
				refeText= [refeTextArra objectAtIndex:i];
				if ( [refeText isEqualToString:@"De"] || 
				[refeText isEqualToString:@"de"] ||
				[refeText isEqualToString:@"Del"] ||
				[refeText isEqualToString:@"del"] ||
				[refeText isEqualToString:@"la"] ||
				[refeText isEqualToString:@"las"] ||
				[refeText isEqualToString:@"el"] ||
				[refeText isEqualToString:@"los"] )
					continue;
				if ( [refeComp isEqualToString:@""] )
					refeComp= refeText;
				else
					refeComp= [CPString stringWithFormat:@"%@ %@",refeComp,refeText];
			}
			[referenceSearText setStringValue:refeComp];
		}
		[addrTextFiel setStringValue:[textArra objectAtIndex:1]];
	}
	else
		[glblAlerPane showWithMessage:@"Recomendacion" info:"Para analizar la direccion, por favor utilice los signos '*' o ',' para separar el texto que contiene la referencia del texto que contiene la direccion"];
		//alert("Para analizar la direccion, por favor utilice los signos '*' o ',' para separar el texto que contiene la referencia del texto que contiene la direccion.");
}



- (void)  applicationQuit {
	if ( mapPane ) {
		[mapPane orderOut:0];
		[mapPane release];
	}
}



- (void) addressSet:(CPString)addrNew {
	[addrCompText setStringValue:addrNew];
	[addrTextFiel setStringValue:@""];
}



- (void) clearFields {
	[addrCompText setStringValue:@""];
	[referenceSearText setStringValue:@""];
	[addrTextFiel setStringValue:@""];
	[coorTextFiel setStringValue:@""];
	[addressNewText setStringValue:@""];
	[referenceNewText setStringValue:@""];
	[messText setStringValue:@""];
}



- (void) cityPopupAction {
		var cntr= [cntrPopu titleOfSelectedItem];
		var stat= [statPopu titleOfSelectedItem];
		var cnty= [cntyPopu titleOfSelectedItem];
		var dstr= [dstrPopu titleOfSelectedItem];
		var city= [cityPopu titleOfSelectedItem];
		[cityPopu setTitle:city];
		[refeConsPopu selectItemWithTitle:@"Ciudad"];

		var quer= [CPString stringWithFormat:@"select CONCAT(name,':',city,':',district,':',county,':',state,':',country,':',objectNumber) from riglobal.puntos_dbf where country='%@' and state='%@' and county='%@' and district='%@' and city='%@' order by name",cntr,stat,cnty,dstr,city];
		var puntArra= [self query:quer];
		var puntArraCoun= [puntArra count];

		var puntInde;
		[referenceDict removeAllObjects];
		[refePopu removeAllItems];
		for ( puntInde=0; puntInde<puntArraCoun; puntInde++ ) {
			var punt= [[[puntArra objectAtIndex:puntInde] valueList] objectAtIndex:0];
			if ( punt && [punt length]>0 && ![punt isEqualToString:@"."] && ![punt isEqualToString:@"(null)"] && ![punt isEqualToString:@"newValue"] ) {
				[refePopu addItemWithTitle:punt];
				[referenceDict setValue:punt forKey:punt];
				}
		}
		[refePopu setTitle:@"Referencia"];

		if ( puntArraCoun>0 )
			puntArraCoun--;
		[messText setStringValue:[CPString stringWithFormat:@"Se encontraron %d referencias",puntArraCoun]];
}



- (CPString) coordinates  {
	var loca= [markRed location];
	var lngd= [loca longitude];
	var lati= [loca latitude];
	var coor= [CPString stringWithFormat:@"%11.6f, %11.6f",lngd,lati];
	return coor;
}



- (void) coordinatesSet:(float)lngd :(float)lati {
	var loca= [[MKLocation alloc] initWithLatitude:lati andLongitude:lngd];
	if ( markRed )
		[markRed setLocation:loca];
	[mapView setCenter:loca];
	[coorTextFiel setStringValue:[CPString stringWithFormat:@"%11.6f, %11.6f",lngd,lati]];
}



- (void) countryPopupAction {
		var cntr= [cntrPopu titleOfSelectedItem];
		[cntrPopu setTitle:cntr];
		[refeConsPopu selectItemWithTitle:@"Pais"];
		[refeConsPopu setTitle:@"Pais"];

		var quer= [CPString stringWithFormat:@"select distinct state from riglobal.puntos_dbf where country='%@' order by state",cntr];
		var puntArra= [self query:quer];
		var puntArraCoun= [puntArra count];
		var puntInde;
		[statPopu removeAllItems];
		[statPopu addItemWithTitle:@"Seleccione uno de los siguientes..."];
		for ( puntInde=0; puntInde<puntArraCoun; puntInde++ ) {
			var punt= [[[puntArra objectAtIndex:puntInde] valueList] objectAtIndex:0];
			if ( punt && [punt length]>0 && ![punt isEqualToString:@"."] && ![punt isEqualToString:@"(null)"] && ![punt isEqualToString:@"newValue"] )
				[statPopu addItemWithTitle:punt];
		}
		[statPopu setTitle:@"Estado/Provincia"];

		if ( puntArraCoun>0 )
			puntArraCoun--;
		[messText setStringValue:[CPString stringWithFormat:@"Se encontraron %d estados/provincias",puntArraCoun]];

		[cntyPopu removeAllItems];
		[dstrPopu removeAllItems];
		[cityPopu removeAllItems];
		[referenceDict removeAllObjects];
		[refePopu removeAllItems];
}



- (void) countyPopupAction {
		var cntr= [cntrPopu titleOfSelectedItem];
		var stat= [statPopu titleOfSelectedItem];
		var cnty= [cntyPopu titleOfSelectedItem];
		[cntyPopu setTitle:cnty];
		[refeConsPopu selectItemWithTitle:@"Canton"];
		[refeConsPopu setTitle:@"Canton"];

		var quer= [CPString stringWithFormat:@"select distinct district from riglobal.puntos_dbf where state='%@' and county='%@' order by district",stat,cnty];
		var puntArra= [self query:quer];
		var puntArraCoun= [puntArra count];

		var puntInde;
		[dstrPopu removeAllItems];
		[dstrPopu addItemWithTitle:@"Seleccione uno de los siguientes..."];
		for ( puntInde=0; puntInde<puntArraCoun; puntInde++ ) {
			var punt= [[[puntArra objectAtIndex:puntInde] valueList] objectAtIndex:0];
			if ( punt && [punt length]>0 && ![punt isEqualToString:@"."] && ![punt isEqualToString:@"(null)"] && ![punt isEqualToString:@"newValue"] )
				[dstrPopu addItemWithTitle:punt];
		}
		[dstrPopu setTitle:@"Distrito"];

		if ( puntArraCoun>0 )
			puntArraCoun--;
		[messText setStringValue:[CPString stringWithFormat:@"Se encontraron %d distritos",puntArraCoun]];

		[cityPopu removeAllItems];
		[referenceDict removeAllObjects];
		[refePopu removeAllItems];
}



- (void) curve:(id)curvArra type:(int)type erase:(int)eras draw:(BOOL)draw color:(int)coloInde {

	var drawCirc;
	var drawCircArraCoun= [drawCircArra count];

	if ( drawCircArraCoun>0 && eras==1 ) {
		var i;
		for ( i=0; i<drawCircArraCoun; i++ ) {
			drawCirc= [drawCircArra objectAtIndex:0];
			[drawCircArra removeObject:drawCirc];
			drawCirc.setMap(null);
		}
	}
	else if ( drawCircArraCoun>1 && eras==2 ) {
		var i;
		for ( i=1; i<drawCircArraCoun; i++ ) {
			drawCirc= [drawCircArra objectAtIndex:1];
			[drawCircArra removeObject:drawCirc];
			drawCirc.setMap(null);
		}
	}

	if ( draw ) {
		var latiLngdBoun= new google.maps.LatLngBounds();
		var path = [CPArray array];

		var coun= [curvArra count];

		var i;
		if ( type==0 ) {
			for ( i=0; i<coun; i++ ) {
				var loca= [curvArra objectAtIndex:i];
				var lngd= [loca longitude];
				var lati= [loca latitude];
				var vectGoog = new google.maps.LatLng(lati,lngd);		
  				latiLngdBoun.extend(vectGoog);
  				[path addObject:vectGoog];
			}
		}
		else {
			for ( i=0; i<coun; i++ ) {
				var vectGoog = curvArra[i];		
  				latiLngdBoun.extend(vectGoog);
  				[path addObject:vectGoog];
  			}
		}

		var coloTemp;
		if ( coloInde==0 ) {
			var redComp= Math.random();
			var greeComp= Math.random();
			var blueComp= Math.random();
			var ampl= Math.sqrt(redComp*redComp+greeComp*greeComp+blueComp*blueComp);
			redComp/= ampl;
			if ( redComp>1. )
				redComp= 1.;
			greeComp/= ampl;
			if ( greeComp>1. )
				greeComp= 1.;
			blueComp/= ampl;
			if ( blueComp>1. )
				blueComp= 1.;
			coloTemp= [CPColor colorWithCalibratedRed:redComp green:greeComp blue:blueComp alpha:1.];		
		}
		else if ( coloInde==1 )
			coloTemp= [CPColor blackColor];
		else if ( coloInde==2 )
			coloTemp= [CPColor redColor];
		else if ( coloInde==3 )
			coloTemp= [CPColor greenColor];
		else if ( coloInde==4 )
			coloTemp= [CPColor blueColor];
		else if ( coloInde==5 )
			coloTemp= [CPColor orangeColor];
		else if ( coloInde==6 )
			coloTemp= [CPColor cyanColor];
		else if ( coloInde==7 )
			coloTemp= [CPColor magentaColor];

		var colo= "#" + [coloTemp hexString];

		poly = new google.maps.Polyline({
	    	path: path,
	    	geodesic: true,
	    	strokeColor: colo,
	    	strokeOpacity: 1.0,
	    	strokeWeight: 3
		  });

		var gMap= [mapView gMap];
		poly.setMap(gMap);
		[drawCircArra addObject:poly];
	}
}



- (void) dealloc {
	if ( mapPane ) {
		[mapPane close];
		[mapPane release];
	}
	[super dealloc];
}
	
	

- (void) districtPopupAction {
		var cntr= [cntrPopu titleOfSelectedItem];
		var stat= [statPopu titleOfSelectedItem];
		var cnty= [cntyPopu titleOfSelectedItem];
		var dstr= [dstrPopu titleOfSelectedItem];
		[dstrPopu setTitle:dstr];
		[refeConsPopu selectItemWithTitle:@"Distrito"];
		[refeConsPopu setTitle:@"Distrito"];

		var quer= [CPString stringWithFormat:@"select distinct city from riglobal.puntos_dbf where country='%@' and state='%@' and county='%@' and district='%@' order by city",cntr,stat,cnty,dstr];
		var puntArra= [self query:quer];
		var puntArraCoun= [puntArra count];
		var cityArraCoun= puntArraCoun;
		if ( cityArraCoun>0 )
			cityArraCoun--;

		var puntInde;
		[cityPopu removeAllItems];
		[cityPopu addItemWithTitle:@"Seleccione uno de los siguientes..."];
		for ( puntInde=0; puntInde<puntArraCoun; puntInde++ ) {
			var punt= [[[puntArra objectAtIndex:puntInde] valueList] objectAtIndex:0];
			if ( punt && [punt length]>0 && ![punt isEqualToString:@"."] && ![punt isEqualToString:@"(null)"] && ![punt isEqualToString:@"newValue"] )
				[cityPopu addItemWithTitle:punt];
		}
		[cityPopu setTitle:@"City"];

		quer= [CPString stringWithFormat:@"select CONCAT(name,':',city,':',district,':',county,':',state,':',country,':',objectNumber) from riglobal.puntos_dbf where state='%@' and county='%@' and district='%@' order by COUNTRY,NAME,STATE,COUNTY,DISTRICT,CITY",stat,cnty,dstr];
		puntArra= [self query:quer];
		puntArraCoun= [puntArra count];
		[referenceDict removeAllObjects];
		[refePopu removeAllItems];
		[refePopu addItemWithTitle:@"Seleccione uno de los siguientes..."];
		for ( puntInde=0; puntInde<puntArraCoun; puntInde++ ) {
			var punt= [[[puntArra objectAtIndex:puntInde] valueList] objectAtIndex:0];
			if ( punt && [punt length]>0 && ![punt isEqualToString:@"."] && ![punt isEqualToString:@"(null)"] && ![punt isEqualToString:@"newValue"] ) {
				[refePopu addItemWithTitle:punt];
				[referenceDict setValue:punt forKey:punt];
				}
		}
		[refePopu setTitle:@"Referencia"];

		if ( puntArraCoun>0 )
			puntArraCoun--;
		[messText setStringValue:[CPString stringWithFormat:@"Se encontraron %d ciudades y %d referencias",cityArraCoun,puntArraCoun]];
}



- (CPString) getAddrCode {
	return addrCode;
}



- (id) init {
	return [self initWithClientData:nil];
}



- (id) initWithClientData:(CPDictionary)clieData {

	self = [super init];

	baseDispDict= [[CPDictionary alloc] init];

	drawCircArra= [[CPArray alloc] init];
	drawMarkArra= [[CPArray alloc] init];
	drawQuadArra= [[CPArray alloc] init];
	drawRegiArra= [[CPArray alloc] init];
	
	markArra= [[CPArray alloc] init];
	refeDispDict= [[CPDictionary alloc] init];
	specDispDict= [[CPDictionary alloc] init];

	if ( clieData!=nil ) {		
		persId		= [clieData objectForKey:"clieCode"];
		addr		= [clieData objectForKey:"fullAddr"];
		addrType	= [clieData objectForKey:"typeAddr"];
		clieName	= [clieData objectForKey:"nameClie"];
		lastName1	= [clieData objectForKey:"lastName1Clie"];
		lastNAme2	= [clieData objectForKey:"lastName2Clie"];
	}
	else
		addr		= @"";

	connector= nil;
	
	var charInde = addr.indexOf("*");
	[referenceSearText setStringValue:addr.substr(0,charInde)];
	[addrTextFiel setStringValue:addr.substr(charInde+1)];
	
	return self;
}




- (void) locationArrayDraw:(CPArray)locaArra {
	[self locationArrayDraw:locaArra color:@"AAA"];
}



- (void) locationArrayDraw:(CPArray)locaArra color:(CPString)colo {
	drawLine= [MKPolyline polyline];
	[drawLine setColor:colo];
	[drawLine setLineStroke:4];
	
	var locaArraCoun= [locaArra count];
	var i;
	for ( i=0; i<locaArraCoun; i++ )
		[drawLine addLocation:locaArra[i]];
	[drawLine addToMapView:mapView];
}



- (id) mainPanel {

	if ( mainPane )
		return mainPane;

	var brooImag= [CPImage imageNamed:@"spinner"];
	var searImag= [CPImage imageNamed:@"spinner"];

	var vertPosi= 30;
	var vertPosiIncr= 25;
	var vertTextOffs= -3;
	var horiButtPos1= 400;
	var horiButtPos2= horiButtPos1 + 25;
	var horiButtPos3= horiButtPos2 + 25;
	var horiButtPos4= horiButtPos3 + 25;
	var horiButtPos5= horiButtPos4 + 25;
	var horiButtWidt= 250;
	var horiTextPos1= 10;
	var horiTextPosi= 140;
	var horiTextOffs= -3;
	var horiTextWidt= 257;

	/* ************************************* */

	mainPane= [[CPPanel alloc] initWithContentRect:CGRectMake(50,60, 500,640) styleMask:CPHUDBackgroundWindowMask | CPClosableWindowMask];
	[mainPane setFloatingPanel:YES]; 
	[mainPane orderFront:self];
	[mainPane setTitle:"Puntos de Referencia"];
			
	var paneContView= [mainPane contentView];
	[paneContView setBackgroundColor:coloDefaLite];
	[self addBanners:paneContView heightBlue:0. heightOrange:-1.];

	var tabView = [[CPTabView alloc] initWithFrame:CGRectMake(5,15,490,620)];
	[tabView setBackgroundColor:coloDefaBrig];

	var tabViewItem1 = [[CPTabViewItem alloc] initWithIdentifier:@"tabViewItem1"];
	[tabViewItem1 setLabel:@"Referencias"];
				
	var contView= [[CPView alloc] initWithFrame: CGRectMake(50, 50, 50, 50)]; 
	[contView setBackgroundColor:coloDefaBrig];

				var addrLabe= [self addTextField:@"Direccion Completa:" TFPosX:horiTextPos1 TFPosY:vertPosi TFWidth:0 TFHeight:0 VView:contView Editable:NO];
				[addrLabe setTextColor:[CPColor whiteColor]];
				addrCompText= [self addTextField:addr TFPosX:horiTextPosi+horiTextOffs TFPosY:vertPosi+vertTextOffs TFWidth:horiTextWidt TFHeight:50  VView:contView Editable:YES];
				[addrCompText setLineBreakMode:CPLineBreakByWordWrapping];
				[addrCompText setAction:@selector(addressAction)];
				[addrCompText setTarget:self];
				vertPosi+= 50;

				vertPosi+= 10;

				var counLabe= [self addTextField:@"Pais:" TFPosX:horiTextPos1 TFPosY:vertPosi TFWidth:0 TFHeight:0  VView:contView Editable:NO];			
				[counLabe setTextColor:[CPColor whiteColor]];
				cntrPopu= [self addPopupButton:@"Pais" TFPosX:horiTextPosi TFPosY:vertPosi TFWidth:horiButtWidt TFHeight:24  VView:contView pullsDown:YES];
				[cntrPopu setAction:@selector(countryPopupAction)];
				[cntrPopu setTarget:self];
				[self resetFields];

				var counSearButt= [self addButton:@"B"  TFPosX:horiButtPos1 TFPosY:vertPosi TFWidth:24 TFHeight:24  VView:contView sizeToFit:NO Action:@selector(resetFields)];
				[counSearButt setToolTip:@"Buscar paises"];
				vertPosi+= vertPosiIncr;

				var statLabe= [self addTextField:@"Estado/Provincia:" TFPosX:horiTextPos1 TFPosY:vertPosi TFWidth:0 TFHeight:0  VView:contView Editable:NO];			
				[statLabe setTextColor:[CPColor whiteColor]];
				statPopu= [self addPopupButton:@"Estado/Provincia" TFPosX:horiTextPosi TFPosY:vertPosi TFWidth:horiButtWidt TFHeight:24  VView:contView pullsDown:YES];
				[statPopu setAction:@selector(statePopupAction)];
				[statPopu setTarget:self];
				vertPosi+= vertPosiIncr;

	/*puntArra= [self query:@"select distinct state from riglobal.puntos_dbf order by state"];
	puntArraCoun= [puntArra count];
	[messText setStringValue:[CPString stringWithFormat:@"Numero de estados/provincias= %d.",puntArraCoun]];
	for ( puntInde=0; puntInde<puntArraCoun; puntInde++ ) {
		var punt= [[[puntArra objectAtIndex:puntInde] valueList] objectAtIndex:0];
			if ( punt && [punt length]>0 && ![punt isEqualToString:@"."] && ![punt isEqualToString:@"(null)"] && ![punt isEqualToString:@"newValue"] )
			[statPopu addItemWithTitle:punt];
	}
	*/

				var cntyLabe= [self addTextField:@"Canton:" TFPosX:horiTextPos1 TFPosY:vertPosi TFWidth:0 TFHeight:0  VView:contView Editable:NO];
				[cntyLabe setTextColor:[CPColor whiteColor]];
				cntyPopu= [self addPopupButton:@"Canton" TFPosX:horiTextPosi TFPosY:vertPosi TFWidth:horiButtWidt TFHeight:24  VView:contView pullsDown:YES];
				[cntyPopu setAction:@selector(countyPopupAction)];
				[cntyPopu setTarget:self];
				vertPosi+= vertPosiIncr;

				var distLabe= [self addTextField:@"Distrito:" TFPosX:horiTextPos1 TFPosY:vertPosi TFWidth:0 TFHeight:0  VView:contView Editable:NO];
				[distLabe setTextColor:[CPColor whiteColor]];
				dstrPopu= [self addPopupButton:@"Distrito"   TFPosX:horiTextPosi TFPosY:vertPosi TFWidth:horiButtWidt TFHeight:24  VView:contView pullsDown:YES];
				[dstrPopu setAction:@selector(districtPopupAction)];
				[dstrPopu setTarget:self];
				vertPosi+= vertPosiIncr;

				var cityLabe= [self addTextField:@"Ciudad:" TFPosX:horiTextPos1 TFPosY:vertPosi TFWidth:0 TFHeight:0  VView:contView Editable:NO];
				[cityLabe setTextColor:[CPColor whiteColor]];
				cityPopu= [self addPopupButton:@"Ciudad"     TFPosX:horiTextPosi TFPosY:vertPosi TFWidth:horiButtWidt TFHeight:24  VView:contView pullsDown:YES];
				[cityPopu setAction:@selector(cityPopupAction)];
				[cityPopu setTarget:self];
				vertPosi+= vertPosiIncr;

				referenceDict= [[CPDictionary alloc] init];

				var consLabe= [self addTextField:@"Consideracion:" TFPosX:horiTextPos1 TFPosY:vertPosi TFWidth:0 TFHeight:0  VView:contView Editable:NO];
				[consLabe setTextColor:[CPColor whiteColor]];
				refeConsPopu= [self addPopupButton:@"Consideracion" TFPosX:horiTextPosi TFPosY:vertPosi TFWidth:horiButtWidt TFHeight:24  VView:contView pullsDown:YES];
					[refeConsPopu setAction:@selector(referenceConsiderationPopupAction)];
					[refeConsPopu setTarget:self];
					[refeConsPopu addItemWithTitle:@"Ninguna"];
					[refeConsPopu addItemWithTitle:@"Pais"];
					[refeConsPopu addItemWithTitle:@"Estado/Provincia"];
					[refeConsPopu addItemWithTitle:@"Canton"];
					[refeConsPopu addItemWithTitle:@"Distrito"];
					[refeConsPopu addItemWithTitle:@"Ciudad"];
					[refeConsPopu addItemWithTitle:@"Desplegadas en Popup"];
					[refeConsPopu addItemWithTitle:@"Desplegadas en Mapa"];
				referenceConsDeleButt= [self addButton:@"X" TFPosX:horiButtPos1 TFPosY:vertPosi TFWidth:24 TFHeight:24  VView:contView sizeToFit:NO Action:@selector(referenceDeleteConsiderationRegionsAction:)];
				[referenceConsDeleButt setToolTip:@"Borrar regiones"];
				referenceConsDrawButt= [self addButton:@"D" TFPosX:horiButtPos2 TFPosY:vertPosi TFWidth:24 TFHeight:24  VView:contView sizeToFit:NO Action:@selector(referenceDrawConsiderationRegionAction:)];
				[referenceConsDrawButt setToolTip:@"Dibujar region"];
				referenceConsDrawButt= [self addButton:@"M" TFPosX:horiButtPos3 TFPosY:vertPosi TFWidth:24 TFHeight:24  VView:contView sizeToFit:NO Action:@selector(referenceDrawConsiderationMarkersAction:)];
				[referenceConsDrawButt setToolTip:@"Dibujar marcadores"];

				vertPosi+= vertPosiIncr;

				referenceConsDrawButt= [self addButton:@"R" TFPosX:horiButtPos1 TFPosY:vertPosi TFWidth:24 TFHeight:24  VView:contView sizeToFit:NO Action:@selector(regionAtRedMarker:)];
				[referenceConsDrawButt setToolTip:@"Regiones administrativas para marcador rojo"];

				vertPosi+= vertPosiIncr;

				vertPosi+= 10;

				var refeSearLabe= [self addTextField:@"Busque Referencia:" TFPosX:horiTextPos1 TFPosY:vertPosi TFWidth:0 TFHeight:0  VView:contView Editable:NO];
				[refeSearLabe setTextColor:[CPColor whiteColor]];
				referenceSearText= [self addTextField:@"" TFPosX:horiTextPosi+horiTextOffs TFPosY:vertPosi+vertTextOffs TFWidth:258 TFHeight:30  VView:contView Editable:YES];	
					[referenceSearText setAction:@selector(referenceSearchLikeTextAction)];
					[referenceSearText setTarget:self];
				refeSearCleaButt = [self addButton:@"X"  TFPosX:horiButtPos1 TFPosY:vertPosi TFWidth:24 TFHeight:24  VView:contView sizeToFit:NO Action:@selector(referenceSearchClearTextAction)];
				[refeSearCleaButt setToolTip:@"Borrar campo"];
				referenceSearLikeButt= [self addButton:@"B"  TFPosX:horiButtPos2 TFPosY:vertPosi TFWidth:24 TFHeight:24  VView:contView sizeToFit:NO Action:@selector(referenceSearchLikeTextAction)];
				[referenceSearLikeButt setToolTip:@"Buscar"];

				vertPosi+= vertPosiIncr;
		
				var refeLabe= [self addTextField:@"Referencia:" TFPosX:horiTextPos1 TFPosY:vertPosi TFWidth:0 TFHeight:0  VView:contView Editable:NO];
				[refeLabe setTextColor:[CPColor whiteColor]];
				refePopu= [self addPopupButton:@"Referencia" TFPosX:horiTextPosi TFPosY:vertPosi TFWidth:horiButtWidt TFHeight:24  VView:contView pullsDown:YES];
				[refePopu setAction:@selector(referencePopupAction)];
				[refePopu setTarget:self];
				refeCleaButt = [self addButton:@"X"  TFPosX:horiButtPos1 TFPosY:vertPosi TFWidth:24 TFHeight:24  VView:contView sizeToFit:NO Action:@selector(referenceClearButtonAction)];
				[refeCleaButt setToolTip:@"Borrar campo"];
				vertPosi+= vertPosiIncr;
	
				[self addButton:@"Refs ➝ Mapa"  TFPosX:horiTextPosi TFPosY:vertPosi TFWidth:122 TFHeight:24  VView:contView sizeToFit:NO Action:@selector(referenceButtonAction)];
				[self addButton:@"Mapa ➝ Refs"  TFPosX:horiTextPosi+122 TFPosY:vertPosi TFWidth:128 TFHeight:24  VView:contView sizeToFit:NO Action:@selector(referencesInView:)];
								
				vertPosi+= 1.5*vertPosiIncr;

				var addrLabe= [self addTextField:@"Direccion:" TFPosX:horiTextPos1 TFPosY:vertPosi TFWidth:0 TFHeight:0  VView:contView Editable:NO];
				[addrLabe setTextColor:[CPColor whiteColor]];
				addrTextFiel= [self addTextField:@"" TFPosX:horiTextPosi+horiTextOffs TFPosY:vertPosi+vertTextOffs TFWidth:258 TFHeight:30  VView:contView Editable:YES];	
				addrTextCleaButt = [self addButton:@"X"  TFPosX:horiButtPos1 TFPosY:vertPosi TFWidth:24 TFHeight:24  VView:contView sizeToFit:NO Action:@selector(referenceClearAddressCoordinatesButtonAction)];
					//[addrTextCleaButt setBordered:NO];
					//[addrTextCleaButt setImage:escoPng];
				[addrTextCleaButt setToolTip:@"Borrar campo"];
				addressButt= [self addButton:@"C"  TFPosX:horiButtPos2 TFPosY:vertPosi TFWidth:24 TFHeight:24  VView:contView sizeToFit:NO Action:@selector(referenceAddressCoordinatesRButtonAction)];
				[addressButt setToolTip:@"Mover el pin rojo al punto definido por el pin de referencia mas la direccion"];
					//[addressButt setBordered:NO];
					//[addressButt setImage:moveFromBluePng];
				addressButt1= [self addButton:@"M"  TFPosX:horiButtPos3 TFPosY:vertPosi TFWidth:24 TFHeight:24  VView:contView sizeToFit:NO Action:@selector(referenceAddressCoordinatesMButtonAction)];
				[addressButt1 setToolTip:@"Mover el pin de referencia al punto definido por el pin marcador mas la direccion"];
					//[addressButt1 setBordered:NO];
					//[addressButt1 setImage:moveFromYellPng];
				vertPosi+= vertPosiIncr;

				var coorLabe= [self addTextField:@"Coordenadas:" TFPosX:horiTextPos1 TFPosY:vertPosi TFWidth:0 TFHeight:0  VView:contView Editable:NO];
				[coorLabe setTextColor:[CPColor whiteColor]];
				coorTextFiel= [self addTextField:@"" TFPosX:horiTextPosi+horiTextOffs TFPosY:vertPosi+vertTextOffs TFWidth:258 TFHeight:30  VView:contView Editable:YES];
				coorTextCleaButt = [self addButton:@"X"  TFPosX:horiButtPos1 TFPosY:vertPosi TFWidth:24 TFHeight:24  VView:contView sizeToFit:NO Action:@selector(referenceClearCoordinatesButtonAction)];
					//[coorTextCleaButt setBordered:NO];
					//[coorTextCleaButt setImage:escoPng];
				coordinatesButt= [self addButton:@"R"  TFPosX:horiButtPos2 TFPosY:vertPosi TFWidth:24 TFHeight:24  VView:contView sizeToFit:NO Action:@selector(referenceSetCoordinatesButtonAction)];
				[coordinatesButt setToolTip:@"Tomar las coordenadas del pin rojo y centrar el mapa en ese punto"];
				takeCoorButt = [self addButton:@"T"  TFPosX:horiButtPos3 TFPosY:vertPosi TFWidth:24 TFHeight:24  VView:contView sizeToFit:NO Action:@selector(referenceTakeCoordinatesButtonAction)];
				[takeCoorButt setToolTip:@"Tomar las coordenadas del campo y aplicarselas al pin rojo y centrar el mapa en ese punto"];
					//[takeCoorButt setBordered:NO];
					//[takeCoorButt setImage:leftArroPng];
				vertPosi+= vertPosiIncr;

				labe= [self addTextField:@"Radio del Circulo:" TFPosX:horiTextPos1 TFPosY:vertPosi TFWidth:0 TFHeight:0  VView:contView Editable:NO];
				[labe setTextColor:[CPColor whiteColor]];
				radiTextFiel= [self addTextField:@"" TFPosX:horiTextPosi+horiTextOffs TFPosY:vertPosi+vertTextOffs TFWidth:70 TFHeight:30  VView:contView Editable:YES];
				labe= [self addTextField:@"mts" TFPosX:horiTextPosi+horiTextOffs+75 TFPosY:vertPosi TFWidth:0 TFHeight:0  VView:contView Editable:NO];
				[labe setTextColor:[CPColor whiteColor]];
				var drawButt = [self addButton:@"X"  TFPosX:horiButtPos1 TFPosY:vertPosi TFWidth:24 TFHeight:24  VView:contView sizeToFit:NO Action:@selector(radiusCenteredAtPointClearance:)];
				[drawButt setToolTip:@"Borrar circulos"];
				drawButt = [self addButton:@"A"  TFPosX:horiButtPos2 TFPosY:vertPosi TFWidth:24 TFHeight:24  VView:contView sizeToFit:NO Action:@selector(radiusCenteredAtPointAddition:)];
				[drawButt setToolTip:@"Dibujar el radio (adicion)"];
				drawButt = [self addButton:@"R"  TFPosX:horiButtPos3 TFPosY:vertPosi TFWidth:24 TFHeight:24  VView:contView sizeToFit:NO Action:@selector(radiusCenteredAtPointReplacement:)];
				[drawButt setToolTip:@"Dibujar el radio (reemplazo)"];
				vertPosi+= vertPosiIncr;

				var addrNewLabe= [self addTextField:@"Nueva Direccion:" TFPosX:horiTextPos1 TFPosY:vertPosi TFWidth:0 TFHeight:0  VView:contView Editable:NO];
				[addrNewLabe setTextColor:[CPColor whiteColor]];
				addressNewText= [self addTextField:@"" TFPosX:horiTextPosi+horiTextOffs TFPosY:vertPosi+vertTextOffs TFWidth:258 TFHeight:60  VView:contView Editable:YES];
				[addressNewText setLineBreakMode:CPLineBreakByWordWrapping];
	
				[self addButton:@"2"  TFPosX:horiButtPos2 TFPosY:vertPosi TFWidth:24 TFHeight:24  VView:contView sizeToFit:NO Action:@selector(referenceNewAddressCoordinatesButtonAction)];
				[self addButton:@"1"  TFPosX:horiButtPos3 TFPosY:vertPosi TFWidth:24 TFHeight:24  VView:contView sizeToFit:NO Action:@selector(referenceNewAddressDirectCoordinatesButtonAction)];
				vertPosi+= vertPosiIncr;

				refeNewAddrCleaButt = [self addButton:@"X"  TFPosX:horiButtPos1 TFPosY:vertPosi TFWidth:24 TFHeight:24  VView:contView sizeToFit:NO Action:@selector(referenceNewAddressClearButtonAction)];
				[refeNewAddrCleaButt setToolTip:@"Borrar campo"];
					//[refeNewAddrCleaButt setBordered:NO];
					//[refeNewAddrCleaButt setImage:escoPng];

				var creaYellButt = [self addButton:@"A"  TFPosX:horiButtPos2 TFPosY:vertPosi TFWidth:24 TFHeight:24  VView:contView sizeToFit:NO Action:@selector(referenceNewAddressMarkerButtonAction)];
				[creaYellButt setToolTip:@"Introducir pin amarillo"];
					//[creaYellButt setBordered:NO];
					//[creaYellButt setImage:yelloMarkPng];
				var creaDrawButt = [self addButton:@"D"  TFPosX:horiButtPos3 TFPosY:vertPosi TFWidth:24 TFHeight:24  VView:contView sizeToFit:NO Action:@selector(referenceMarkerArrayDrawButtonAction)];
				[creaDrawButt setToolTip:@"Dibujar el arreglo de pines amarillos"];

				vertPosi+= vertPosiIncr;
				vertPosi+= 15;

				labe= [self addTextField:@"Marcadores:" TFPosX:horiTextPos1 TFPosY:vertPosi TFWidth:0 TFHeight:0  VView:contView Editable:NO];
				[labe setTextColor:[CPColor whiteColor]];
				var centButt= [self addButton:@"Centrar Rojo" TFPosX:horiTextPosi TFPosY:vertPosi TFWidth:258/2 TFHeight:24  VView:contView sizeToFit:NO Action:@selector(referenceMarkerInView)];
				[centButt setToolTip:@"Mover el pin rojo al centro del mapa"];
				var refeCleaDispButt = [self addButton:@"Borrar Todos"  TFPosX:horiTextPosi+258/2 TFPosY:vertPosi TFWidth:258/2 TFHeight:24  VView:contView sizeToFit:NO Action:@selector(referenceClearDisplayButtonAction:)];
				[refeCleaDispButt setToolTip:@"Eliminar los pines del mapa"];

				vertPosi+= vertPosiIncr;

				var messLabe= [self addTextField:@"Mensajes:" TFPosX:horiTextPos1 TFPosY:vertPosi TFWidth:0 TFHeight:0  VView:contView Editable:NO];
				[messLabe setTextColor:[CPColor whiteColor]];
				messText= [self addTextField:@"" TFPosX:horiTextPosi+horiTextOffs TFPosY:vertPosi+vertTextOffs TFWidth:258 TFHeight:60  VView:contView Editable:YES];
				[messText setLineBreakMode:CPLineBreakByWordWrapping];
				[messText setTextColor:[CPColor darkGrayColor]];
				
				refeMessCleaButt= [self addButton:@"X"  TFPosX:horiButtPos1 TFPosY:vertPosi TFWidth:24 TFHeight:24  VView:contView sizeToFit:NO Action:@selector(referenceClearMessageTextAction)];
				[refeMessCleaButt setToolTip:@"Borrar campo"];
				var refeMessActiMess= [self addButton:@"J"  TFPosX:horiButtPos2 TFPosY:vertPosi TFWidth:24 TFHeight:24  VView:contView sizeToFit:NO Action:@selector(referenceMessageAction)];
				[refeMessActiMess setToolTip:@"Mandar un mensaje"];
				var inseButt= [self addButton:@"E" TFPosX:horiButtPos3 TFPosY:vertPosi TFWidth:24 TFHeight:24  VView:contView sizeToFit:NO Action:@selector(referenceExecuteAction:)];
				[inseButt setToolTip:@"Ejecutar"];

				if ( addr!=@"" ) {
					[self addButton:@"Devolver direccion"  TFPosX:300 TFPosY:vertPosi TFWidth:120 TFHeight:24  VView:contView sizeToFit:YES Action:@selector(returndirection)];
				}
				vertPosi+= vertPosiIncr;

	[tabViewItem1 setView:contView];
				
	[tabView addTabViewItem: tabViewItem1];
	
	[paneContView addSubview:tabView];

	return mainPane;
}



- (id) mapPanel {
	return mapPane;
}



- (id) mapWithinWindow:(CPWindow)windNew centerAt:(float)lngdNew :(float)latiNew {

	wind= windNew;	

	mapPane = [[CPPanel alloc] initWithContentRect:CGRectMake(520, 120, 600, 600) styleMask:CPHUDBackgroundWindowMask|CPClosableWindowMask|CPResizableWindowMask];
	[mapPane setFloatingPanel:YES]; 
	[mapPane orderFront:self];
	[mapPane setTitle:"Mapa"];
			
	paneContView= [mapPane contentView];
	[paneContView setBackgroundColor:coloDefaLite];
	[self addBanners:paneContView heightBlue:0. heightOrange:-1.];
	
	var lngd= -84.1;
	if ( lngdNew )
		lngd= lngdNew;
	var lati;
	if ( latiNew )
		lati= latiNew;
	var loca= [[MKLocation alloc] initWithLatitude:lati andLongitude:lngd];

	mapView= [[MKMapView alloc] initWithFrame:CGRectMake(5, 5, 590, 590) apiKey:'' center:loca];
	[mapView setAutoresizingMask:CPViewHeightSizable|CPViewWidthSizable];
	[mapView setDelegate:self];
	[mapView setMapController:self];
	[paneContView addSubview:mapView];
	
	//[self addButton:@"Refresh Map"  TFPosX:895 TFPosY:520 TFWidth:30 TFHeight:24  VView:paneContView sizeToFit:YES Action:@selector(mapReload)];

}



- (MKMapView) mapView {
	return mapView;
}



- (void) mapViewIsReady:(MKMapView)mapView  {
	[mapView setZoom:14];
	[self referenceMarkerInView];
}



- (void) mapReferencePointsRefresh:(id)sender {
	[self mapaPuntosDeReferencia:sender];
	[mapPane close];
}



- (void) mapReload {
	if ( mapView!=null )
		[mapView _load];
	else {
		var loca= [markRed location];
		mapView= [[MKMapView alloc] initWithFrame:CGRectMake(5, 5, 500, 500) apiKey:'' center:loca];
		[mapView setAutoresizingMask:CPViewHeightSizable | CPViewWidthSizable];
		[mapView setDelegate:self];
		[[mapPane contentView] addSubview:mapView];
	}
}



- (CPArray) markerArray {
	return markArra;
}



- (MKLocation) mouseLocation {
	return mousLoca;
}



- (void) none:(id)sender {
}



- (void) performWith:(CPString)stri {
	var arra= [stri componentsSeparatedBy:@":"];
	if ( [arra count]>0 )
		[inpuIdenText setStringValue:[arra objectAtIndex:0]];
}


	
- (void) quadAt:(float)lngdCent :(float)latiCent :(float)lngdDelt :(float)latiDelt erase:(BOOL)eras draw:(BOOL)draw color:(CPColor)colo {

	var drawQuad;
	var drawQuadArraCoun= [drawQuadArra count];

	if ( drawQuadArraCoun>0 && eras ) {
		var i;
		for ( i=0; i<drawQuadArraCoun; i++ ) {
			drawQuad= [drawQuadArra objectAtIndex:0];
			[drawQuadArra removeObjectAtIndex:0];
			drawQuad.setMap(null);
		}
	}

	if ( draw ) {
		var latiLngdBoun= new google.maps.LatLngBounds();
		var path = [CPArray array];

		var lngd= lngdCent;
		var lati= latiCent;
		var vectGoog = new google.maps.LatLng(lati,lngd);		
		latiLngdBoun.extend(vectGoog);
		[path addObject:vectGoog];

		var lngd= lngdCent + lngdDelt;
		var lati= latiCent;
		var vectGoog = new google.maps.LatLng(lati,lngd);		
		latiLngdBoun.extend(vectGoog);
		[path addObject:vectGoog];

		var lngd= lngdCent + lngdDelt;
		var lati= latiCent + latiDelt;
		var vectGoog = new google.maps.LatLng(lati,lngd);		
		latiLngdBoun.extend(vectGoog);
		[path addObject:vectGoog];

		var lngd= lngdCent;
		var lati= latiCent + latiDelt;
		var vectGoog = new google.maps.LatLng(lati,lngd);		
		latiLngdBoun.extend(vectGoog);
		[path addObject:vectGoog];

		var color= "#" + [colo hexString];
		var alph= [colo alphaComponent];
		poly= new google.maps.Polygon({
   			paths: path,
   			strokeColor: color,
   			strokeOpacity: 0.7,
   			strokeWeight: 2,
   			fillColor: color,
   			fillOpacity: alph
			});
		var gMap= [mapView gMap];
		poly.setMap(gMap);
		[drawQuadArra addObject:poly];
	}
}



- (void) radiusCenteredAtPointAddition:(id)sender {
	[self radiusCenteredAtPoint:sender erase:NO draw:YES];
}



- (void) radiusCenteredAtPointClearance:(id)sender {
	[self radiusCenteredAtPoint:sender erase:YES draw:NO];
}



- (void) radiusCenteredAtPointReplacement:(id)sender {
	[self radiusCenteredAtPoint:sender erase:YES draw:YES];
}



- (void) radiusCenteredAtPoint:(id)sender erase:(BOOL)eras draw:(BOOL)draw {
	var loca= [markRed location];
	var lngdCent= [loca longitude];
	var latiCent= [loca latitude];
	var radi= [radiTextFiel floatValue]/111450.;
	var colo= [CPColor greenColor];
	[self radiusCenteredAtPoint:lngdCent :latiCent erase:eras draw:draw radius:radi color:colo];
}


- (void) radiusCenteredAtPoint:(float)lngdCent :(float)latiCent erase:(BOOL)eras draw:(BOOL)draw radius:(float)radi color:(CPColor)colo {
	var info = @"info";
	[self radiusCenteredAtPoint:lngdCent :latiCent erase:eras draw:draw radius:radi color:colo information:info];
}



- (void) radiusCenteredAtPoint:(float)lngdCent :(float)latiCent erase:(BOOL)eras draw:(BOOL)draw radius:(float)radi color:(CPColor)colo information:(CPString)info {

	var drawCirc;
	var drawCircArraCoun= [drawCircArra count];

	if ( drawCircArraCoun>0 && eras ) {
		var i;
		for ( i=0; i<drawCircArraCoun; i++ ) {
			drawCirc= [drawCircArra objectAtIndex:0];
			[drawCircArra removeObjectAtIndex:0];
			drawCirc.setMap(null);
		}
	}

	if ( draw && latiCent!=0. && lngdCent!=0. ) {
		
		var gMap = [mapView gMap];
		var coloHexa = "#" + [colo hexString];
		var alph = [colo alphaComponent];

		poly = new google.maps.Marker({
			position: new google.maps.LatLng(latiCent,lngdCent),
			map: gMap,
			icon: {
			  path: google.maps.SymbolPath.CIRCLE,
			  fillColor: coloHexa,
			  fillOpacity: alph,
			  strokeColor: coloHexa,
			  strokeWeight: .5,
			  scale: 10000*radi
			}
		  });
		  
		if ( [info isEqualToString:@"info"] ) {
			google.maps.event.addListener(poly, 'click',
				function polyClicked(e) {
				[glblAlerPane showWithMessage:@"" info:"Polilinea en la posición: latitud,longitud="+e.latLng];
				//alert("Polilinea en la posición: latitud,longitud="+e.latLng);
				mousLoca = [[MKLocation alloc] initWithLatLng:e.latLng];
				});
		}
		else {
			google.maps.event.addListener(poly, 'click',
				function polyClicked(e) {
				alert(info);
				mousLoca = [[MKLocation alloc] initWithLatLng:e.latLng];
				});
		}

		[drawCircArra addObject:poly];
		
	}
}



- (void) referenceExecuteAction:(id)sender {
	var messTextStri= [messText stringValue];
	var refeNewTextStri= [referenceNewText stringValue];
}




- (void) referenceAddressCoordinatesRButtonAction {
	var coorText= [coorTextFiel stringValue];
	return [self referenceAddressCoordinatesButtonAction:coorText];
}
	
	

- (void) referenceAddressCoordinatesMButtonAction {
	if ( !markArra ) {
		[glblAlerPane showWithMessage:@"" info:"Marcador amarillo no existe; debe crearlo primero con el boton 'A'."];
		//alert("Marcador amarillo no existe; debe crearlo primero con el boton 'A'.");
		return;
	}
	var loca= [markArra location];
	var lngd= [loca longitude];
	var lati= [loca latitude];
	var coorText= [CPString stringWithFormat:@"%11.6f %11.6f",lngd,lati];
	[self referenceAddressCoordinatesButtonAction:coorText];
}


- (void) referenceAddressCoordinatesButtonAction:(CPString)coorText {
	var addrText= [addrTextFiel stringValue];

	if ( [addrText length]==0 || [coorText length]==0 ) {
		[glblAlerPane showWithMessage:@"" info:"No hay suficientes datos (1)"];
		//alert("No hay suficientes datos (1)");
		return;
	}

	// addrText
	var rang= [addrText rangeOfString:@"  "];
	while ( rang.location!=CPNotFound ) {
		addrText= [addrText stringByReplacingOccurrencesOfString:@"  " withString:@" "];
		rang= [addrText rangeOfString:@"  "];
	}
	if ( [addrText length]<=1 ) {
		[glblAlerPane showWithMessage:@"" info:"No hay suficientes datos (2)"];
		//alert("No hay suficientes datos (2)");
		return;
	}
	rang= [addrText rangeOfString:@" "];
	while ( rang.location==0 ) {
		addrText= [addrText stringByReplacingOccurrencesOfString:@" " withString:@"" options:CPCaseInsensitiveSearch range:rang];
		rang= [addrText rangeOfString:@" "];
	}
	rang.location= [addrText length]-1;
	rang.length= 1;
	rang= [addrText rangeOfString:@" " options:CPCaseInsensitiveSearch range:rang];
	while ( rang.location!=CPNotFound ) {
		addrText= [addrText stringByReplacingOccurrencesOfString:@" " withString:@"" options:CPCaseInsensitiveSearch range:rang];
		rang.location= [addrText length]-1;
		rang.length= 1;
		rang= [addrText rangeOfString:@" " options:CPCaseInsensitiveSearch range:rang];
	}

	// coorText:
	rang= [coorText rangeOfString:@"  "];
	while ( rang.location!=CPNotFound ) {
		coorText= [coorText stringByReplacingOccurrencesOfString:@"  " withString:@" "];
		rang= [coorText rangeOfString:@"  "];
	}
	if ( [coorText length]<=1 ) {
		[glblAlerPane showWithMessage:@"" info:"No hay suficientes datos (3)"];
		//alert("No hay suficientes datos (3)");
		return;
	}
	rang= [coorText rangeOfString:@" "];
	while ( rang.location==0 ) {
		coorText= [coorText stringByReplacingOccurrencesOfString:@" " withString:@"" options:CPCaseInsensitiveSearch range:rang];
		rang= [coorText rangeOfString:@" "];
	}
	rang.location= [coorText length]-1;
	rang.length= 1;
	rang= [coorText rangeOfString:@" " options:CPCaseInsensitiveSearch range:rang];
	while ( rang.location!=CPNotFound ) {
		coorText= [coorText stringByReplacingOccurrencesOfString:@" " withString:@"" options:CPCaseInsensitiveSearch range:rang];
		rang.location= [coorText length]-1;
		rang.length= 1;
		rang= [coorText rangeOfString:@" " options:CPCaseInsensitiveSearch range:rang];
	}


	var addrArra= [addrText componentsSeparatedByString:@" "];
	var addrArraCoun= [addrArra count];
	[messText setStringValue:[CPString stringWithFormat:@"Numero de terminos: %d.",addrArraCoun]];

	var rema= addrArraCoun%3;
	if ( rema!=0 ) {
		[messText setStringValue:[CPString stringWithFormat:@"Numero de terminos: %d no es multiplo de 3 (*%@*).",addrArraCoun,addrText]];
		[glblAlerPane showWithMessage:@"" info:"Numero de terminos no es multiplo de 3."];
		//alert("Numero de terminos no es multiplo de 3.");
		return;
	}
	var setsNumb= addrArraCoun/3;
	var lngdDelt= 0.;
	var latiDelt= 0.;

	var i;
	for ( i=0; i<setsNumb; i++ ) {
		var amou= [[addrArra objectAtIndex:i*3+0] doubleValue];
		var unit= [addrArra objectAtIndex:i*3+1];
		if ( [unit isEqualToString:@"bloque"] || [unit isEqualToString:@"bloques"] || [unit isEqualToString:@"cuadra"] || [unit isEqualToString:@"cuadras"] || [unit isEqualToString:@"manzana"] || [unit isEqualToString:@"manzanas"] )
			unit= 100./111.45;
		else if ( [unit isEqualToString:@"km"] )
			unit= 1./111.45;
		else if ( [unit isEqualToString:@"m"] || [unit isEqualToString:@"mts"] || [unit isEqualToString:@"metros"] )
			unit= 0.001/111.45;
		else if ( [unit isEqualToString:@"varas"] )
			unit= 0.0009/111.45;
		else {
			[glblAlerPane showWithMessage:@"" info:"Las unidades del grupo "+i+" no se reconocieron"];
			//alert("Las unidades del grupo "+i+" no se reconocieron");
			return;
		}
		var dire= [addrArra objectAtIndex:i*3+2];
		if ( [dire isEqualToString:@"e"] || [dire isEqualToString:@"este"] )
			lngdDelt+= amou*unit;
		else if ( [dire isEqualToString:@"n"] || [dire isEqualToString:@"norte"] )
			latiDelt+= amou*unit;
		else if ( [dire isEqualToString:@"ne"] || [dire isEqualToString:@"noreste"] ) {
			lngdDelt+= amou*unit*0.707;
			latiDelt+= amou*unit*0.707;
			}
		else if ( [dire isEqualToString:@"nee"] || [dire isEqualToString:@"noresteeste"] ) {
			lngdDelt+= amou*unit*0.924;
			latiDelt+= amou*unit*0.383;
			}
		else if ( [dire isEqualToString:@"neee"] || [dire isEqualToString:@"noresteesteeste"] ) {
			lngdDelt+= amou*unit*0.981;
			latiDelt+= amou*unit*0.195;
			}
		else if ( [dire isEqualToString:@"nne"] || [dire isEqualToString:@"nornoreste"] ) {
			lngdDelt+= amou*unit*0.383;
			latiDelt+= amou*unit*0.924;
			}
		else if ( [dire isEqualToString:@"nnne"] || [dire isEqualToString:@"nornornoreste"] ) {
			lngdDelt+= amou*unit*0.195;
			latiDelt+= amou*unit*0.981;
			}
		else if ( [dire isEqualToString:@"no"] || [dire isEqualToString:@"noroeste"] ) {
			lngdDelt-= amou*unit*0.707;
			latiDelt+= amou*unit*0.707;
			}
		else if ( [dire isEqualToString:@"noo"] || [dire isEqualToString:@"noroesteoeste"] ) {
			lngdDelt-= amou*unit*0.924;
			latiDelt+= amou*unit*0.383;
			}
		else if ( [dire isEqualToString:@"nooo"] || [dire isEqualToString:@"noroesteoesteoeste"] ) {
			lngdDelt-= amou*unit*0.981;
			latiDelt+= amou*unit*0.195;
			}
		else if ( [dire isEqualToString:@"nno"] || [dire isEqualToString:@"nornoroeste"] ) {
			lngdDelt-= amou*unit*0.383;
			latiDelt+= amou*unit*0.924;
			}
		else if ( [dire isEqualToString:@"nnno"] || [dire isEqualToString:@"nornornoroeste"] ) {
			lngdDelt-= amou*unit*0.195;
			latiDelt+= amou*unit*0.981;
			}
		else if ( [dire isEqualToString:@"o"] || [dire isEqualToString:@"oeste"] )
			lngdDelt-= amou*unit;
		else if ( [dire isEqualToString:@"s"] || [dire isEqualToString:@"sur"] )
			latiDelt-= amou*unit;
		else if ( [dire isEqualToString:@"se"] || [dire isEqualToString:@"sureste"] ) {
			lngdDelt+= amou*unit*0.707;
			latiDelt-= amou*unit*0.707;
			}
		else if ( [dire isEqualToString:@"see"] || [dire isEqualToString:@"suresteeste"] ) {
			lngdDelt+= amou*unit*0.924;
			latiDelt-= amou*unit*0.383;
			}
		else if ( [dire isEqualToString:@"seee"] || [dire isEqualToString:@"suresteesteeste"] ) {
			lngdDelt+= amou*unit*0.981;
			latiDelt-= amou*unit*0.195;
			}
		else if ( [dire isEqualToString:@"sse"] || [dire isEqualToString:@"sursureste"] ) {
			lngdDelt+= amou*unit*0.383;
			latiDelt-= amou*unit*0.924;
			}
		else if ( [dire isEqualToString:@"ssse"] || [dire isEqualToString:@"sursursureste"] ) {
			lngdDelt+= amou*unit*0.195;
			latiDelt-= amou*unit*0.981;
			}
		else if ( [dire isEqualToString:@"so"] || [dire isEqualToString:@"suroeste"] ) {
			lngdDelt-= amou*unit*0.707;
			latiDelt-= amou*unit*0.707;
			}
		else if ( [dire isEqualToString:@"soo"] || [dire isEqualToString:@"suroesteoeste"] ) {
			lngdDelt-= amou*unit*0.924;
			latiDelt-= amou*unit*0.383;
			}
		else if ( [dire isEqualToString:@"sooo"] || [dire isEqualToString:@"suroesteoesteoeste"] ) {
			lngdDelt-= amou*unit*0.981;
			latiDelt-= amou*unit*0.195;
			}
		else if ( [dire isEqualToString:@"sso"] || [dire isEqualToString:@"sursuroeste"] ) {
			lngdDelt-= amou*unit*0.383;
			latiDelt-= amou*unit*0.924;
			}
		else if ( [dire isEqualToString:@"ssso"] || [dire isEqualToString:@"sursursuroeste"] ) {
			lngdDelt-= amou*unit*0.195;
			latiDelt-= amou*unit*0.981;
			}
		else {
			[glblAlerPane showWithMessage:@"" info:"La direccion del grupo "+i+" no se reconocio"];
			//alert("La direccion del grupo "+i+" no se reconocio");
			return;
		}
	}

	rang= [coorText rangeOfString:@","];
	if ( rang.location!=CPNotFound )
		sepa= @",";
	else
		sepa= @" ";

	var coorArra= [coorText componentsSeparatedByString:sepa];
	if ( coorArra==nil || [coorArra count]==1 )
		return;

	var markLngd= [[coorArra objectAtIndex:0] floatValue] + lngdDelt;
	var markLati= [[coorArra objectAtIndex:1] floatValue] + latiDelt;

	var loca= [[MKLocation alloc] initWithLatitude:markLati andLongitude:markLngd];
	[markRed setLocation:loca];
	[mapView setCenter:loca];
}



- (void) referenceButtonAction {
	var refePopuCoun= [refePopu numberOfItems];
	var i;
	for ( i=0; i<refePopuCoun; i++ ) {
		var reference= [refePopu itemTitleAtIndex:i];
		var arra= [reference componentsSeparatedByString:@":"];
		var arraCoun= [arra count];
		if ( arraCoun>1 ) {
			var quer= [CPString stringWithFormat:@"select longitude,latitude from riglobal.puntos_dbf where objectNumber='%@' order by name",[arra objectAtIndex:arraCoun-1]];
			var puntArra= [self query:quer];
			var puntArraCoun= [puntArra count];

			var lngd = [[[puntArra objectAtIndex:0] valueList] objectAtIndex:0];
			var lati = [[[puntArra objectAtIndex:0] valueList] objectAtIndex:1];

			var loc2= [[MKLocation alloc] initWithLatitude:lati andLongitude:lngd];
			var mark= [[MKMarker alloc] initAtLocation:loc2];
			[mark setGoogleIcon:@"ltblue-dot" withShadow:YES];
			[mark setDraggable:NO];
			[mark setTitle:reference];
			[mark addToMapView:mapView];
			[markArra addObject:mark];
		}
	}
}



- (void) referenceClearAddressCoordinatesButtonAction {
	[addrTextFiel setStringValue:@""];
}



- (void) referenceClearDisplayButtonAction:(id)sender {
	var baseDispKeyArra= [baseDispDict allKeys];
	var coun= [baseDispDict count];
	//alert("Clear display: 1 coun="+coun);
	var i;
	for ( i=0; i<coun; i++ ) {
		var key= [baseDispKeyArra objectAtIndex:0];
		var mark= [baseDispDict objectForKey:key];
		[baseDispDict setObject:NULL forKey:key];
		var gMark= [mark getMarker];
		gMark.setMap(null);
		//alert("mark="+mark+"     gMark="+gMark);
		[mark release];
	}
	//alert("count= "+coun+" / "+[baseDispDict count]);

	var refeDispKeyArra= [refeDispDict allKeys];
	coun= [refeDispDict count];
	var noneCoun= 0;
	//alert("Clear display: 2 coun="+coun);
	for ( i=0; i<coun; i++ ) {
		var key= [refeDispKeyArra objectAtIndex:i];
		var mark= [refeDispDict objectForKey:key];
		//alert("key="+key+"  mark="+mark);
		[refeDispDict setObject:NULL forKey:key];
		var gMark= [mark getMarker];
		if ( gMark )
			gMark.setMap(null);
		else
			noneCoun++;
		//alert("mark="+mark+"     gMark="+gMark);
		[mark release];
	}
	//alert("coun= "+coun+"  refeDispDictCount"+[refeDispDict count]+"  noneCoun="+noneCoun);

	var specDispKeyArra= [specDispDict allKeys];
	coun= [specDispDict count];
	//alert("Clear display: 3 coun="+coun);
	for ( i=0; i<coun; i++ ) {
		var key= [specDispKeyArra objectAtIndex:i];
		var mark= [specDispDict objectForKey:key];
		[specDispDict setObject:NULL forKey:key];
		var gMark= [mark getMarker];
		gMark.setMap(null);
		//alert("mark="+mark+"     gMark="+gMark);
		[mark release];
	}
	//alert("count= "+coun+" / "+[specDispDict count]);

	coun= [markArra count];
	for ( i=0; i<coun; i++ ) {
		var mark= [markArra objectAtIndex:0];
		[markArra removeObjectAtIndex:0];
		var gMark= [mark getMarker];
		gMark.setMap(null);
		[mark release];
	}

	[self referenceMarkerInView];
}



- (void) referenceClearButtonAction {
	if ( [refePopu numberOfItems]>0 ) {
		[referenceDict removeAllObjects];
		[refePopu removeAllItems];
		[refePopu addItemWithTitle:@"Referencia"];
		[messText setStringValue:@"Las referencias han sido borradas."];
		}
}



- (void) referenceClearCoordinatesButtonAction {
	[coorTextFiel setStringValue:@""];
}



- (void) referenceClearMessageTextAction {
	[messText setStringValue:@""];
}



- (void) referenceConsiderationPopupAction {
		var reference= [refeConsPopu titleOfSelectedItem];
		[refeConsPopu setTitle:reference];
}



- (void) referenceDrawConsiderationMarkersAction:(id)sender {
	var cons= [admiRegiConsPopu titleOfSelectedItem];
	
	var quer= NULL;
	if ( [cons isEqualToString:@"Estado/Provincia"] ) {
		var stat= [statPopu titleOfSelectedItem];
		if ( [stat isEqualToString:@"Seleccione uno de los siguientes..."] )
			return;
		quer= [CPString stringWithFormat:@"select t1.longitude,t1.latitude,t1.segno,t1.seqno from GIS.provincias_shp t1, GIS.provincias_dbf t2 where t2.PROVINCIA_0='%@' and t1.objectNumber=t2.objectNumber ",
			stat];
	}
	else if ( [cons isEqualToString:@"Canton"] ) {
		var stat= [statPopu titleOfSelectedItem];
		var cnty= [cntyPopu titleOfSelectedItem];
		if ( [cnty isEqualToString:@"Seleccione uno de los siguientes..."] )
			return;
		quer= [CPString stringWithFormat:@"select t1.longitude,t1.latitude,t1.segno,t1.seqno from GIS.cantones_shp t1, GIS.cantones_dbf t2 where t2.NPROVINCIA_1='%@' and t2.NCANTON_0='%@' and t1.objectNumber=t2.objectNumber ",
			stat,cnty];
	}
	else if ( [cons isEqualToString:@"Distrito"] ) {
		var stat= [statPopu titleOfSelectedItem];
		var cnty= [cntyPopu titleOfSelectedItem];
		var dstr= [dstrPopu titleOfSelectedItem];
		if ( [dstr isEqualToString:@"Seleccione uno de los siguientes..."] )
			return;
		quer= [CPString stringWithFormat:@"select t1.longitude,t1.latitude,t1.segno,t1.seqno from GIS.distritos_shp t1, GIS.distritos_dbf t2 where t2.PROVINCIA_0='%@' and t2.NCANTON_1='%@' and t2.NDISTRITO_2='%@' and t1.objectNumber=t2.objectNumber ",
			stat,cnty,dstr];
	}
	else {
		[glblAlerPane showWithMessage:@"" info:"Por favor elija como consideracion 'Estado/Provincia', 'Canton' o 'Distrito'"];
		//alert("Por favor elija como consideracion 'Estado/Provincia', 'Canton' o 'Distrito'");
		return;
	}

	var gMap= [mapView gMap];
	var boun= gMap.getBounds();
	var cent= boun.getCenter();
	var span= boun.toSpan();
	var lngdMini= cent.lng() - span.lng()*0.45;
	var lngdMaxi= cent.lng() + span.lng()*0.45;
	var latiMini= cent.lat() - span.lat()*0.45;
	var latiMaxi= cent.lat() + span.lat()*0.45;
	
	quer= quer+"and t1.longitude>="+lngdMini+" and t1.longitude<="+lngdMaxi+" and t1.latitude>="+latiMini+" and t1.latitude<="+latiMaxi+" order by t1.segno,t1.seqno";

	var conf= confirm(quer);
	if ( !conf )
		return;

	var coorArra= [self query:quer];
	var coorArraCoun= [coorArra count];
	
	if ( coorArraCoun < 1 ) {
		alert("No se encontraron elementos. query:*"+quer+"*  count="+coorArraCoun);
		return;
	}
	if ( coorArraCoun > 100 ) {
		var conf= confirm("Quiere proceder con "+coorArraCoun+" marcadores?");
		if ( !conf )
			return;
	}

	var j= 0;
	while ( j<coorArraCoun ) {
		var xy= [[coorArra objectAtIndex:j] valueList];
		var x = [xy objectAtIndex:0];
		var y = [xy objectAtIndex:1];
		var segm= [xy objectAtIndex:2];
		var sequ= [xy objectAtIndex:3];
		var loca= [[MKLocation alloc] initWithLatitude:y andLongitude:x];
		var mark= [[MKMarker alloc] initAtLocation:loca];
		[mark setGoogleIcon:@"orange-dot" withShadow:YES];
		[mark setDraggable:NO];
		var titl= "segm="+segm+"   sequ="+sequ+"   j="+j+"   x="+x+" y="+y;
		[mark setTitle:titl];
		[mark addToMapView:mapView];
		[drawMarkArra addObject:mark];
		j++;
	}
}



- (void) referenceDrawConsiderationRegionAction:(id)sender {
	var cons= [refeConsPopu titleOfSelectedItem];
	
	var quer= NULL;
	if ( [cons isEqualToString:@"Estado/Provincia"] ) {
		var stat= [statPopu titleOfSelectedItem];
		if ( [stat isEqualToString:@"Seleccione uno de los siguientes..."] )
			return;
		quer= [CPString stringWithFormat:@"select t1.longitude,t1.latitude,t1.segno from GIS.provincias_shp t1, GIS.provincias_dbf t2 where t2.PROVINCIA_0='%@' and t1.objectNumber=t2.objectNumber order by t1.segno,t1.seqno",
			stat];
	}
	else if ( [cons isEqualToString:@"Canton"] ) {
		var stat= [statPopu titleOfSelectedItem];
		var cnty= [cntyPopu titleOfSelectedItem];
		if ( [cnty isEqualToString:@"Seleccione uno de los siguientes..."] )
			return;
		quer= [CPString stringWithFormat:@"select t1.longitude,t1.latitude,t1.segno from GIS.cantones_shp t1, GIS.cantones_dbf t2 where t2.NPROVINCIA_1='%@' and t2.NCANTON_0='%@' and t1.objectNumber=t2.objectNumber order by t1.segno,t1.seqno",
			stat,cnty];
	}
	else if ( [cons isEqualToString:@"Distrito"] ) {
		var stat= [statPopu titleOfSelectedItem];
		var cnty= [cntyPopu titleOfSelectedItem];
		var dstr= [dstrPopu titleOfSelectedItem];
		if ( [dstr isEqualToString:@"Seleccione uno de los siguientes..."] )
			return;
		quer= [CPString stringWithFormat:@"select t1.longitude,t1.latitude,t1.segno from GIS.distritos_shp t1, GIS.distritos_dbf t2 where t2.PROVINCIA_0='%@' and t2.NCANTON_1='%@' and t2.NDISTRITO_2='%@' and t1.objectNumber=t2.objectNumber order by t1.segno,t1.seqno",
			stat,cnty,dstr];
	}
	else {
		[glblAlerPane showWithMessage:@"" info:"Por favor elija como consideracion 'Estado/Provincia', 'Canton' o 'Distrito'"];
		//alert("Por favor elija como consideracion 'Estado/Provincia', 'Canton' o 'Distrito'");
		return;
	}

	var coorArra= [self query:quer];
	var coorArraCoun= [coorArra count];
	
	if ( coorArraCoun < 1 ) {
		alert("No se encontraron elementos. query:*"+quer+"*  count="+coorArraCoun);
		return;
	}

	var gMap= [mapView gMap];

	var coloTemp;
	if ( sender <= 0 )  {
		var redComp= - sender;
		var greeComp= 0.5;
		var blueComp= 1 - redComp;
		coloTemp= [CPColor colorWithCalibratedRed:redComp green:greeComp blue:blueComp alpha:1.];		
	}
	else {
		var redComp= 0.1 + Math.random();
		var greeComp= 0.1 + Math.random();
		var blueComp= 0.1 + Math.random();
		var ampl= Math.sqrt(redComp*redComp+greeComp*greeComp+blueComp*blueComp);
		redComp/= ampl * 2.;
		greeComp/= ampl * 2.;
		blueComp/= ampl * 2.;
		if ( redComp>1. )
			redComp= 1.;
		if ( greeComp>1. )
			greeComp= 1.;
		if ( blueComp>1. )
			blueComp= 1.;
		coloTemp= [CPColor colorWithCalibratedRed:redComp green:greeComp blue:blueComp alpha:1.];		
	}
	var color= "#" + [coloTemp hexString];

	var latiLngdBoun= NULL;
	var path = [CPArray array];
	var sOld= -1;

	var xyPrev= [[coorArra objectAtIndex:0] valueList];
	var xPrev = [xyPrev objectAtIndex:0];
	var yPrev = [xyPrev objectAtIndex:1];
	var distMaxi= 0.;
	var jMaxi;
	var striMaxi;

	var j= 0;
	while ( j<coorArraCoun ) {
		var xy= [[coorArra objectAtIndex:j] valueList];
		var x = [xy objectAtIndex:0];
		var y = [xy objectAtIndex:1];
		var s = [xy objectAtIndex:2];
		var vectGoog= new google.maps.LatLng(y,x);
		
		var xDiff= x - xPrev;
		var yDiff= y - yPrev;
		var dist= Math.sqrt(xDiff*xDiff+yDiff*yDiff) * 111.45;
		if ( dist > distMaxi ) {
			distMaxi= dist;
			jMaxi= j;
			striMaxi= "  coordinates: x= "+x+" - "+xPrev+"   y= "+y+" - "+yPrev;
		}
		xPrev= x;
		yPrev= y;
		
		
		if ( s != sOld ) {
			if ( j > 0 ) {

				redComp+=  (Math.random() - 0.5) * 0.1;
				greeComp+= (Math.random() - 0.5) * 0.1;
				blueComp+= (Math.random() - 0.5) * 0.1;
				if ( redComp>1. )
					redComp= 1.;
				if ( greeComp>1. )
					greeComp= 1.;
				if ( blueComp>1. )
					blueComp= 1.;
				coloTemp= [CPColor colorWithCalibratedRed:redComp green:greeComp blue:blueComp alpha:1.];
				color= "#" + [coloTemp hexString];

				poly= new google.maps.Polygon({
	    			paths: path,
	    			strokeColor: color,
	    			strokeOpacity: 0.5,
	    			strokeWeight: 2,
	    			fillColor: color,
	    			fillOpacity: 0.3
					});
				poly.setMap(gMap);
				[drawRegiArra addObject:poly];
			}
			latiLngdBoun = new google.maps.LatLngBounds();
			path = [CPArray array];
			sOld= s;
			//alert("s: "+s+"  sOld: "+sOld);
		}

  		latiLngdBoun.extend(vectGoog);
  		[path addObject:vectGoog];
	  	
	  	j++;
	}
	
	redComp+=  (Math.random() - 0.5) * 0.2;
	greeComp+= (Math.random() - 0.5) * 0.2;
	blueComp+= (Math.random() - 0.5) * 0.2;
	if ( redComp>1. )
		redComp= 1.;
	if ( greeComp>1. )
		greeComp= 1.;
	if ( blueComp>1. )
		blueComp= 1.;
	coloTemp= [CPColor colorWithCalibratedRed:redComp green:greeComp blue:blueComp alpha:1.];
	color= "#" + [coloTemp hexString];

	poly= new google.maps.Polygon({
   			paths: path,
   			strokeColor: color,
   			strokeOpacity: 0.5,
   			strokeWeight: 2,
   			fillColor: color,
   			fillOpacity: 0.3
			});
	poly.setMap(gMap);
	[drawRegiArra addObject:poly];

	/*
	if ( distMaxi > 30. )
		alert("Maximum distance= "+distMaxi+"  at point: "+jMaxi+striMaxi);
	*/
}



- (void) referenceDeleteConsiderationRegionsAction:(id)sender {
	var coun= [drawMarkArra count];
	var i;
	for ( i=0; i<coun; i++ ) {
		var mark= [drawMarkArra objectAtIndex:0];
		[drawMarkArra removeObjectAtIndex:0];
		var gMark= [mark getMarker];
		gMark.setMap(null);
		[mark release];
	}
	coun= [drawMarkArra count];
	if ( coun > 0 )
		alert("Did not remove all markers ("+coun+") !");

	var coun= [drawRegiArra count];
	var i;
	for ( i=0; i<coun; i++ ) {
		var obje= [drawRegiArra objectAtIndex:i];
		obje.setMap(null);
	}
	[drawRegiArra removeAllObjects];
}



- (void) referenceMarkerInView  {
	var gMap= [mapView gMap];
	if ( markRed ) {
		var gMark= [markRed getMarker];
		gMark.setMap(null);
		[markRed release];
	}
	var boun= gMap.getBounds();
	var cent= boun.getCenter();
	var lngd= cent.lng();
	var lati= cent.lat();
	var loca= [[MKLocation alloc] initWithLatitude:lati andLongitude:lngd];
	
	markRed= [[MKMarker alloc] initAtLocation:loca];
	[markRed addToMapView:mapView];
	[markRed setTitle:@"Red pin marker"];
}



- (void) referencePopupAction {
	var reference= [refePopu titleOfSelectedItem];
	[refePopu setTitle:reference];
	[messText setStringValue:reference];
	var arra= [reference componentsSeparatedByString:@":"];
	var arraCoun= [arra count];
	if ( arraCoun<2 ) {
		alert("Reference name does not contain id");
		return;
	}
	var quer= [CPString stringWithFormat:@"select country,state,county,district,city,longitude,latitude from riglobal.puntos_dbf where objectNumber=%@ order by COUNTRY,NAME,STATE,COUNTY,DISTRICT,CITY",[arra objectAtIndex:arraCoun-1]];
	var puntArra= [self query:quer];
	var puntArraCoun= [puntArra count];
	[messText setStringValue:[CPString stringWithFormat:@"Numero de referencias encontradas: %d",puntArraCoun]];

	if ( puntArraCoun>0 ) {
		var pntr= [puntArra objectAtIndex:0];
		var valuList= [pntr valueList];
		var valuListCoun= [valuList count];

		var lngd= 0;
		var lati= 0;
		
		if ( valuListCoun==7 ) {
			var country= [valuList objectAtIndex:0];
			[cntrPopu removeAllItems];
			[cntrPopu addItemWithTitle:@"Seleccione uno de los siguientes..."];
			[cntrPopu addItemWithTitle:country];
			[cntrPopu setTitle:country];

			var state = [valuList objectAtIndex:1];
			[statPopu removeAllItems];
			[statPopu addItemWithTitle:@"Seleccione uno de los siguientes..."];
			[statPopu addItemWithTitle:state];
			[statPopu setTitle:state];
		
			var county = [valuList objectAtIndex:2];
			[cntyPopu removeAllItems];
			[cntyPopu addItemWithTitle:@"Seleccione uno de los siguientes..."];
			[cntyPopu addItemWithTitle:county];
			[cntyPopu setTitle:county];

			var district = [valuList objectAtIndex:3];
			[dstrPopu removeAllItems];
			[dstrPopu addItemWithTitle:@"Seleccione uno de los siguientes..."];
			[dstrPopu addItemWithTitle:district];
			[dstrPopu setTitle:district];

			var city = [valuList objectAtIndex:4];
			[cityPopu removeAllItems];
			[cityPopu addItemWithTitle:@"Seleccione uno de los siguientes..."];
			[cityPopu addItemWithTitle:city];
			[cityPopu setTitle:city];

			lngd = [valuList objectAtIndex:5];
			lati = [valuList objectAtIndex:6];
			[coorTextFiel setStringValue:[CPString stringWithFormat:@"%@, %@",lngd,lati]];

			lngd= [lngd floatValue];
			lati= [lati floatValue];
		}

		var loc2 = [[MKLocation alloc] initWithLatitude:lati andLongitude:lngd];
		var mark= [[MKMarker alloc] initAtLocation:loc2];
		[mark setGoogleIcon:@"blue-dot" withShadow:YES];
		[mark setTitle:reference];
		//[mark setInfoWindowHTML:reference openOnClick:YES];
		[mark setDraggable:NO];
		[mark addToMapView:mapView];

		[mapView setCenter:loc2];
	}

}



- (void) referenceMarkerArrayDrawButtonAction {
	if ( drawLine ) {
		var gMap= [mapView gMap];
		//drawLine.setMap(null);
	}
	drawLine= [MKPolyline polyline];
	[drawLine setColor:@"008F8F"];
	[drawLine setLineStroke:4];
	
	var markArraCoun= [markArra count];
	var i;
	for ( i=0; i<markArraCoun; i++ ) {
		var mark= [markArra objectAtIndex:i];
		var markLoca= [mark location];
		[drawLine addLocation:markLoca];
	}
	[drawLine addToMapView:mapView];
}



- (void) referenceMessageAction {
	var quer= [CPString stringWithFormat:@"insert into messages (message) values ('%@')",[refeText stringValue]];
	var puntArra= [self query:quer];
}



- (void) referenceNewAddressClearButtonAction {
	[addressNewText setStringValue:@""];
}


- (void) referenceNewAddressCoordinatesButtonAction {
	if ( markArra==nil )
		return;
	var markArraCoun= [markArra count];
	if ( markArraCoun<2 )
		return;

	//[addressNewText setStringValue:[CPString stringWithFormat:@"De: %@, ",[refePopu titleOfSelectedItem]]];

	var stri= @"";
	var distTota= 0.;
	var i;
	for ( i=1; i<markArraCoun; i++ ) {
	var loca= [[markArra objectAtIndex:i] location];
	var lngd1= [loca longitude];
	var lati1= [loca latitude];
	loca= [[markArra objectAtIndex:i-1] location];
	var lngd2= [loca longitude];
	var lati2= [loca latitude];
	var lngdDelt= lngd1 - lngd2;
	lngdDelt*= 111.45;
	var latiDelt= lati1 - lati2;
	latiDelt*= 111.45;
	var dist= Math.sqrt(lngdDelt*lngdDelt+latiDelt*latiDelt);
	distTota+= dist;

	var eastWestDire= @"este";
	if ( lngdDelt<0. ) {
		eastWestDire= @"oeste";
		lngdDelt*= -1.;
	}
	var nortSoutDire= @"norte";
	if ( latiDelt<0. ) {
		nortSoutDire= @"sur";
		latiDelt*= -1.;
	}
	
	var nortSout= 1;
	var eastWest= 1;
	if ( Math.abs(lngdDelt/latiDelt)<0.1 )
		eastWest= 0;
	else if ( Math.abs(latiDelt/lngdDelt)<0.1 )
		nortSout= 0;
		
	var nortSoutUnit= @"km";
	var eastWestUnit= @"km";
	if ( latiDelt<1. ) {
		latiDelt*= 100.;
		latiDelt= Math.ceil(latiDelt)*10.;
		nortSoutUnit= @"mts";
	}
	if ( lngdDelt<1. ) {
		lngdDelt*= 100.;
		lngdDelt= Math.ceil(lngdDelt)*10.;
		eastWestUnit= @"mts";
	}

	if ( nortSout==1 && eastWest==1 )
		stri= [CPString stringWithFormat:@"%@%d: %8.2f %@ %@   %8.2f %@ %@\n",stri,i,latiDelt,nortSoutUnit,nortSoutDire,lngdDelt,eastWestUnit,eastWestDire];
	else if ( nortSout==1 )
		stri= [CPString stringWithFormat:@"%@%d: %8.2f %@ %@\n",stri,i,latiDelt,nortSoutUnit,nortSoutDire];
	else if ( eastWest==1 )
		stri= [CPString stringWithFormat:@"%@%d: %8.2f %@ %@\n",stri,i,lngdDelt,eastWestUnit,eastWestDire];
	}
	[addressNewText setStringValue:stri];
	distTota= Math.floor(distTota*1000.)/1000.;
	stri= [CPString stringWithFormat:@"Distancia Total: %f km\n",distTota];
	[messText setStringValue:stri];
}



- (void) referenceNewAddressDirectCoordinatesButtonAction {
	if ( markArra==nil )
		return;
	var markArraCoun= [markArra count];
	if ( markArraCoun<2 ) {
		[glblAlerPane showWithMessage:@"Atencion" info:"No hay suficientes puntos"];
		//alert("No hay suficientes puntos.");
		return;
	}

	var stri= @"";
	var distTota= 0.;
	var i;
	for ( i=1; i<markArraCoun; i++ ) {
	var loca= [[markArra objectAtIndex:i] location];
	var lngd1= [loca longitude];
	var lati1= [loca latitude];
	loca= [[markArra objectAtIndex:i-1] location];
	var lngd2= [loca longitude];
	var lati2= [loca latitude];
	var lngdDelt= lngd1 - lngd2;
	lngdDelt*= 111.45;
	var latiDelt= lati1 - lati2;
	latiDelt*= 111.45;
	var delt= Math.sqrt(lngdDelt*lngdDelt+latiDelt*latiDelt);
	distTota+= delt;
	if ( delt<0.00001 ) {
		[addressNewText setStringValue:@"(mismo lugar)"];
		return;
	}
	
	var cosi= lngdDelt/delt;
	var angl= Math.acos(cosi)*latiDelt/Math.abs(latiDelt)*180./3.14159653;
	var dire= @"e";
	if ( angl>172.5 )
		dire= @"o";
	else if ( angl>157.5 )
		dire= @"nooo";
	else if ( angl>142.5 )
		dire= @"noo";
	else if ( angl>127.5 )
		dire= @"no";
	else if ( angl>112.5 )
		dire= @"nno";
	else if ( angl>97.5 )
		dire= @"nnno";
	else if ( angl>82.5 )
		dire= @"n";
	else if ( angl>67.5 )
		dire= @"nnne";
	else if ( angl>52.5 )
		dire= @"nne";
	else if ( angl>37.5 )
		dire= @"ne";
	else if ( angl>22.5 )
		dire= @"nee";
	else if ( angl>7.5 )
		dire= @"neee";
	else if ( angl>0. )
		dire= @"e";
	else if ( angl<-172.5 )
		dire= @"o";
	else if ( angl<-157.5 )
		dire= @"sooo";
	else if ( angl<-142.5 )
		dire= @"soo";
	else if ( angl<-127.5 )
		dire= @"so";
	else if ( angl<-112.5 )
		dire= @"sso";
	else if ( angl<-97.5 )
		dire= @"ssso";
	else if ( angl<-82.5 )
		dire= @"s";
	else if ( angl<-67.5 )
		dire= @"ssse";
	else if ( angl<-52.5 )
		dire= @"sse";
	else if ( angl<-37.5 )
		dire= @"se";
	else if ( angl<-22.5 )
		dire= @"see";
	else if ( angl<-7.5 )
		dire= @"seee";
	else if ( angl<0. )
		dire= @"e";
	
	var unit= @"km";
	if ( delt<1. ) {
		delt*= 40.;
		delt= Math.ceil(delt)*25.;
		unit= @"mts";
	}
	stri= [CPString stringWithFormat:@"%@%d: %8.2f %@ %@\n",stri,i,delt,unit,dire];
	}
	[addressNewText setStringValue:stri];
	distTota= Math.floor(distTota*1000.)/1000.;
	stri= [CPString stringWithFormat:@"Distancia Total: %f km\n",distTota];
	[messText setStringValue:stri];
}



- (void) referenceNewAddressMarkerButtonAction {
	var loca= [markRed location];
	var mark= [[MKMarker alloc] initAtLocation:loca];
	if ( [markArra count]==0 )
		[mark setGoogleIcon:@"orange-dot" withShadow:YES];
	else
		[mark setGoogleIcon:@"yellow-dot" withShadow:YES];
	[mark addToMapView:mapView];
	//[mark setInfoWindowHTML:@"mark" openOnClick:YES];
	[markArra addObject:mark];
}



- (void) referenceNewClearAction {
	[referenceNewText setStringValue:@""];
}



- (void) referenceNewTransferAction {
	if ( !mapPane )
		[self mapaPuntosDeReferencia:self];
	var stri= [referenceSearText stringValue];
	[referenceNewText setStringValue:stri];
}
	


- (void) referenceSearchLikeTextAction {
		var like= [referenceSearText stringValue];
		if ( [like length]<2 )
			return;

		like= [like uppercaseString];

		var likeArra= [like componentsSeparatedByString:@" "];
		var likeArraCoun= [likeArra count];

		var word= [likeArra objectAtIndex:0];
		var quer= [CPString stringWithFormat:@"select CONCAT(name,':',city,':',district,':',county,':',state,':',country,':',objectNumber) from riglobal.puntos_dbf where name like '<p>%@<p>'",word];
		var i;
		for ( i=1; i<likeArraCoun; i++ ) {
			word= [likeArra objectAtIndex:i];
			if ( [word length]>0 )
				quer= [CPString stringWithFormat:@"%@ and name like '<p>%@<p>'",quer,word];		
		}
		
		if ( [refeConsPopu indexOfSelectedItem]<=6 ) {
			if ( [refeConsPopu indexOfSelectedItem]>=2 )
				quer= [CPString stringWithFormat:@"%@ and country = '%@'",quer,[cntrPopu titleOfSelectedItem]];		
			if ( [refeConsPopu indexOfSelectedItem]>=3 )
				quer= [CPString stringWithFormat:@"%@ and state = '%@'",quer,[statPopu titleOfSelectedItem]];		
			if ( [refeConsPopu indexOfSelectedItem]>=4 )
				quer= [CPString stringWithFormat:@"%@ and county = '%@'",quer,[cntyPopu titleOfSelectedItem]];		
			if ( [refeConsPopu indexOfSelectedItem]>=5 )
				quer= [CPString stringWithFormat:@"%@ and district = '%@'",quer,[dstrPopu titleOfSelectedItem]];		
			if ( [refeConsPopu indexOfSelectedItem]==6 )
				quer= [CPString stringWithFormat:@"%@ and city = '%@'",quer,[cityPopu titleOfSelectedItem]];
		}
		else if ( [refeConsPopu indexOfSelectedItem]==7 && [referenceDict count]>0 ) {
				quer= [CPString stringWithFormat:@"%@ and (",quer];
				var refeArra= [referenceDict allKeys];
				var refeCoun= [refeArra count];
				var objeArra= [[refeArra objectAtIndex:0] componentsSeparatedByString:@":"];
				if ( [objeArra count]<2 ) {
					alert([refeArra objectAtIndex:0]);
					return;
				}
				quer= [CPString stringWithFormat:@"%@ objectNumber=%@",quer,[objeArra objectAtIndex:1]];
				var i;
				for ( i=1; i<refeCoun; i++ ) {
					objeArra= [[refeArra objectAtIndex:i] componentsSeparatedByString:@":"]
					if ( [objeArra count]<2 ) {
						alert([refeArra objectAtIndex:i]);
					}
					quer= [CPString stringWithFormat:@"%@ or objectNumber=%@",quer,[objeArra objectAtIndex:1]];
				}
				quer= [CPString stringWithFormat:@"%@ )",quer];
		}
		else if ( [refeConsPopu indexOfSelectedItem]==8 && [refeDispDict count]>0 ) {
				quer= [CPString stringWithFormat:@"%@ and (",quer];
				var refeDispArra= [refeDispDict allKeys];
				var refeDispCoun= [refeDispArra count];
				var objeArra= [[refeDispArra objectAtIndex:0] componentsSeparatedByString:@":"];
				if ( [objeArra count]<2 ) {
					alert([refeDispArra objectAtIndex:0]);
					return;
				}
				quer= [CPString stringWithFormat:@"%@ objectNumber=%@",quer,[objeArra objectAtIndex:1]];
				var i;
				for ( i=1; i<refeDispCoun; i++ ) {
					objeArra= [[refeDispArra objectAtIndex:i] componentsSeparatedByString:@":"]
					if ( [objeArra count]<2 ) {
						alert([refeDispArra objectAtIndex:i]);
					}
					quer= [CPString stringWithFormat:@"%@ or objectNumber=%@",quer,[objeArra objectAtIndex:1]];
				}
				quer= [CPString stringWithFormat:@"%@ )",quer];
		}
			
		quer= [CPString stringWithFormat:@"%@ order by COUNTRY,NAME,STATE,COUNTY,DISTRICT,CITY",quer];
	
		var puntArra= [self query:quer];
		var puntArraCoun= [puntArra count];
		[messText setStringValue:[CPString stringWithFormat:@"Numero de referencias encontradas: %d",puntArraCoun-1]];
		
		if ( puntArraCoun>200 ) {
			var arraCoun= prompt("Se encontraron "+puntArraCoun+" referencias. Indique el numero que desea considerar:");
			if ( arraCoun>0 && arraCoun<=puntArraCoun )
				puntArraCoun= arraCoun;
			if ( puntArraCoun>1000 ) {
				alert("El numero se ha restringido a 1000 para poder procesar la informacion en el pop-up.");
				puntArraCoun= 1000;
			}
		}

		[referenceDict removeAllObjects];
		[refePopu removeAllItems];
		[refePopu addItemWithTitle:@"Seleccione uno de los siguientes..."];
		var puntInde;
		for ( puntInde=0; puntInde<puntArraCoun; puntInde++ ) {
			var punt= [[[puntArra objectAtIndex:puntInde] valueList] objectAtIndex:0];
			if ( punt && [punt length]>0 && ![punt isEqualToString:@"."] && ![punt isEqualToString:@"(null)"] && ![punt isEqualToString:@"newValue"] ) {
				[referenceDict setValue:punt forKey:punt];
				[refePopu addItemWithTitle:punt];
				}
		}
		[refePopu setTitle:@"Referencia"];
		
		if ( puntArraCoun==0 )
			alert("No se encontraron referencias con las palabras clave. Por favor introduzca otra combinacion de palabras clave.");
}



- (void) referenceSearchClearTextAction {
	[referenceSearText setStringValue:@""];
}



- (void) referenceSetCoordinatesButtonAction {
	var loca= [markRed location];
	var lngd= [loca longitude];
	var lati= [loca latitude];
	[coorTextFiel setStringValue:[CPString stringWithFormat:@"%11.6f, %11.6f",lngd,lati]];
	[mapView setCenter:loca];
}



- (void) referenceSearchTextConsiderationAction {
	if ( !mapPane )
		[self mapaPuntosDeReferencia:self];
	var stri= [referenceSearText stringValue];
	[referenceNewText setStringValue:stri];
}
	


- (void) referenceTakeCoordinatesButtonAction {
	var coorText= [coorTextFiel stringValue];
	if ( [coorText length]<3 )
		return;
	var coorTextArra= [coorText componentsSeparatedByString:@","];
	var coorTextArraCoun= [coorTextArra count];
	if ( coorTextArraCoun!=2 )
		return;
	var loca= [markRed location];
	[loca setLongitude:[[coorTextArra objectAtIndex:0] doubleValue]];
	[loca setLatitude:[[coorTextArra objectAtIndex:1] doubleValue]];
	[markRed setLocation:loca];
	[mapView setCenter:loca];
}



- (void) referencesInView:(id)sender {
	if ( [refePopu numberOfItems]==0 )
		[refePopu addItemWithTitle:@"Referencias"];

	var gMap= [mapView gMap];
	var boun= gMap.getBounds();
	var cent= boun.getCenter();
	var span= boun.toSpan();
	var lngdMini= cent.lng() - span.lng()*0.45;
	var lngdMaxi= cent.lng() + span.lng()*0.45;
	var latiMini= cent.lat() - span.lat()*0.45;
	var latiMaxi= cent.lat() + span.lat()*0.45;

	var quer= "select longitude,latitude,NAME,STRT_ADDR,CITY,DISTRICT,COUNTY,STATE,COUNTRY,objectNumber from riglobal.puntos_dbf where longitude>"+lngdMini+" and longitude<"+lngdMaxi+" and latitude>"+latiMini+" and latitude<"+latiMaxi+" order by COUNTRY,NAME,STATE,COUNTY,DISTRICT,CITY";

	var puntArra= [self query:quer];
	var puntArraCoun= [puntArra count];
	if ( puntArraCoun>100 ) {
		var conf= confirm("El numero de referencias es: "+puntArraCoun+".  Desea continuar?");
		if ( !conf )
			return;
	}
	[messText setStringValue:[CPString stringWithFormat:@"Numero de referencias en rectangulo: %d",puntArraCoun]];

	var puntInde;
	for ( puntInde=0; puntInde<puntArraCoun; puntInde++ ) {
		var valuList= [[puntArra objectAtIndex:puntInde] valueList];
		if ( [valuList count]<10 ) {
			alert("Problemas con puntInde= "+puntInde);
			continue;
		}
		var iden= [valuList objectAtIndex:9];
		//alert("Iden0= *"+iden+"*  puntInde="+puntInde+"   puntArraCoun="+puntArraCoun);
		if ( ![refeDispDict objectForKey:iden] ) {
			var lngd= [[valuList objectAtIndex:0] doubleValue];
			var lati= [[valuList objectAtIndex:1] doubleValue];
			var loc2= [[MKLocation alloc] initWithLatitude:lati andLongitude:lngd];
			var mark= [[MKMarker alloc] initAtLocation:loc2];
			[mark setGoogleIcon:@"green-dot" withShadow:YES];
			//[mark setIcon:@"file:///Users/me/Sites/RouteAddress/Resources/ButtonPointGreen_10x10.png"];
			[mark setDraggable:NO];
			//[mark setInfoWindowHTML:iden openOnClick:YES];
			var titl= @"";
			var name= [valuList objectAtIndex:2];
			if ( name && [name length]>0 && ![name isEqualToString:@"(NULL)"] && ![name isEqualToString:@"(null)"] )
				titl= [CPString stringWithFormat:@"%@",name];
			var stre= [valuList objectAtIndex:3];
			if ( stre && [stre length]>0 && ![stre isEqualToString:@"(NULL)"] && ![stre isEqualToString:@"(null)"] )
				titl= [CPString stringWithFormat:@"%@(%@)",titl,stre];
			var city= [valuList objectAtIndex:4];
			if ( city && [city length]>0 && ![city isEqualToString:@"(NULL)"] && ![city isEqualToString:@"(null)"] )
				titl= [CPString stringWithFormat:@"%@:%@",titl,city];
			var dist= [valuList objectAtIndex:5];
			if ( dist && [dist length]>0 && ![dist isEqualToString:@"(NULL)"] && ![dist isEqualToString:@"(null)"] )
				titl= [CPString stringWithFormat:@"%@:%@",titl,dist];
			var cnty= [valuList objectAtIndex:6];
			if ( cnty && [cnty length]>0 && ![cnty isEqualToString:@"(NULL)"] && ![cnty isEqualToString:@"(null)"] )
				titl= [CPString stringWithFormat:@"%@:%@",titl,cnty];
			var stat= [valuList objectAtIndex:7];
			if ( stat && [stat length]>0 && ![stat isEqualToString:@"(NULL)"] && ![stat isEqualToString:@"(null)"] )
				titl= [CPString stringWithFormat:@"%@:%@",titl,stat];
			var cntr= [valuList objectAtIndex:8];
			if ( cntr && [cntr length]>0 && ![cntr isEqualToString:@"(NULL)"] && ![cntr isEqualToString:@"(null)"] )
				titl= [CPString stringWithFormat:@"%@:%@",titl,cntr];
			titl= [CPString stringWithFormat:@"%@:%@",titl,iden];
			[mark setTitle:titl];
			[mark addToMapView:mapView];

			[refeDispDict setObject:mark forKey:iden];
		}
		if ( ![referenceDict objectForKey:iden] ) {
			var refe= [CPString stringWithFormat:@"%@:%@",[valuList objectAtIndex:2],iden];
			[referenceDict setValue:refe forKey:iden];
			[refePopu addItemWithTitle:refe];
		}
	}

	[refePopu setTitle:@"Referencias Desplegadas"];
}



- (void) regionAtRedMarker:(id)sender {
    
	var loca= [markRed location];
    var lngd= [loca longitude];
	var lati= [loca latitude];
    
    var lngdLatiPoin= CPMakePoint(lngd,lati);
    
    //alert("lngd="+lngd+"  lati="+lati+"  "+lngdLatiPoin);
    
    var quer= NULL;
	var cntrSolu= NULL;
	var statSolu= NULL;
	var cntySolu= NULL;
	var dstrSolu= NULL;

	var t0;
	var titl= [refeConsPopu titleOfSelectedItem];
	if ( [titl isEqualToString:@"Pais"] ) {
		cntrSolu= [cntrPopu titleOfSelectedItem];
		t0= 0;
	}
	else if ( [titl isEqualToString:@"Estado/Provincia"] ) {
		cntrSolu= [cntrPopu titleOfSelectedItem];
		t0= 0;
	}
	else if ( [titl isEqualToString:@"Canton"] ) {
		cntrSolu= [cntrPopu titleOfSelectedItem];
		statSolu= [statPopu titleOfSelectedItem];
		t0= 1;
	}
	else if ( [titl isEqualToString:@"Distrito"] ) {
		cntrSolu= [cntrPopu titleOfSelectedItem];
		statSolu= [statPopu titleOfSelectedItem];
		cntySolu= [cntyPopu titleOfSelectedItem];
		t0= 2;
	}
	else
		t0= 0;
	//alert("titl="+titl+"   t0="+t0);

	var t;
	for ( t=t0; t<3; t++ ) {
		//alert("t="+t);

	    if ( t == 0 )
	        quer= @"select t1.objectNumber,t1.PROVINCIA_0, "+
	        "min(t2.longitude),max(t2.longitude),min(t2.latitude),max(t2.latitude) "+
	        "from GIS.provincias_dbf t1, GIS.provincias_shp t2 where t2.objectNumber=t1.objectNumber "+
	        "group by t1.PROVINCIA_0 order by t1.PROVINCIA_0";
	    else if ( t == 1 )
	        quer= [CPString stringWithFormat:@"select t1.objectNumber,t1.NCANTON_0, "+
	        "min(t2.longitude),max(t2.longitude),min(t2.latitude),max(t2.latitude) "+
	        "from GIS.cantones_dbf t1, GIS.cantones_shp t2 where t2.objectNumber=t1.objectNumber and t1.NPROVINCIA_1='%@' "+
	        "group by t1.NCANTON_0 order by t1.NCANTON_0",statSolu];
	    else if ( t == 2 )
	        quer= [CPString stringWithFormat:@"select t1.objectNumber,t1.NDISTRITO_2, "+
	        "min(t2.longitude),max(t2.longitude),min(t2.latitude),max(t2.latitude) "+
	        "from GIS.distritos_dbf t1, GIS.distritos_shp t2 where t2.objectNumber=t1.objectNumber and t1.PROVINCIA_0='%@' and t1.NCANTON_1='%@' "+
	        "group by t1.NDISTRITO_2 order by t1.NDISTRITO_2",statSolu,cntySolu];

		var regiMatr= [self query:quer];

		//alert(quer);

		if ( !regiMatr )
			return;
		var regiMatrCoun= [regiMatr count];
		if ( regiMatrCoun < 1 )
			return;

		//alert("Count: "+regiMatrCoun);
		
		var rema= 0;

	    for ( var i=0; i<regiMatrCoun && rema==0; i++ ) {
	    	//alert("i="+i+" / "+regiMatrCoun);

	    	var valuList= [[regiMatr objectAtIndex:i] valueList];
	        var objeNumb= [valuList objectAtIndex:0];
	        var objeName= [valuList objectAtIndex:1];
	        var lngdMini= [[valuList objectAtIndex:2] doubleValue];
	        var lngdMaxi= [[valuList objectAtIndex:3] doubleValue];
	        var latiMini= [[valuList objectAtIndex:4] doubleValue];
	        var latiMaxi= [[valuList objectAtIndex:5] doubleValue];
	        
	        //alert(objeNumb+"   "+objeName+" ("+lngdMini+" "+lngd+" "+lngdMaxi+") ("+latiMini+" "+lati+" "+latiMaxi+")");

	        if ( lngdMini<=lngd && lngd<=lngdMaxi && latiMini<=lati && lati<=latiMaxi ) {

	            if ( t == 0 )
	                quer= [CPString stringWithFormat:@"select segno,min(longitude),max(longitude),min(latitude),max(latitude) from GIS.provincias_shp "+
                       "where objectNumber='%@' group by segno order by segno",objeNumb];
	            else if ( t == 1 )
	                quer= [CPString stringWithFormat:@"select segno,min(longitude),max(longitude),min(latitude),max(latitude) from GIS.cantones_shp "+
                       "where objectNumber='%@' group by segno order by segno",objeNumb];
	            else if ( t == 2 )
	                quer= [CPString stringWithFormat:@"select segno,min(longitude),max(longitude),min(latitude),max(latitude) from GIS.distritos_shp "+
                       "where objectNumber='%@' group by segno order by segno",objeNumb];

	            var regiSegmMatr= [self query:quer];
	            var segmNumb= [regiSegmMatr count];

				var s;
				for ( s=0; s<segmNumb && rema==0; s++ ) {
				
	    			valuList= [[regiSegmMatr objectAtIndex:s] valueList];
	        		segm= [valuList objectAtIndex:0];
	        		lngdMini= [[valuList objectAtIndex:1] doubleValue];
	        		lngdMaxi= [[valuList objectAtIndex:2] doubleValue];
	        		latiMini= [[valuList objectAtIndex:3] doubleValue];
	        		latiMaxi= [[valuList objectAtIndex:4] doubleValue];
	        
	        		//alert(objeNumb+"   "+objeName+" ("+lngdMini+" "+lngd+" "+lngdMaxi+") ("+latiMini+" "+lati+" "+latiMaxi+")");

			    	//alert("s="+s+" / "+segmNumb+"    segm="+segm);

			        if ( lngdMini<=lngd && lngd<=lngdMaxi && latiMini<=lati && lati<=latiMaxi ) {

			            if ( t == 0 )
			                quer= [CPString stringWithFormat:@"select longitude,latitude,segno from GIS.provincias_shp "+
		                       "where objectNumber='%@' and segno=%@ order by seqno",objeNumb,segm];
			            else if ( t == 1 )
			                quer= [CPString stringWithFormat:@"select longitude,latitude,segno from GIS.cantones_shp "+
		                       "where objectNumber='%@' and segno=%@ order by seqno",objeNumb,segm];
			            else if ( t == 2 )
			                quer= [CPString stringWithFormat:@"select longitude,latitude,segno from GIS.distritos_shp "+
		                       "where objectNumber='%@' and segno=%@ order by seqno",objeNumb,segm];

			            var regiCoorMatr= [self query:quer];

						//alert(quer);

			            if ( !regiCoorMatr )
			                continue;
			            var regiCoorMatrCoun= [regiCoorMatr count];
			            if ( regiCoorMatrCoun<1 )
			                continue;

						//alert("Count="+regiCoorMatrCoun);

						var xa= lngd;
						var ya= lati;
						var xb= 0;
						var yb= 0;
				    	var m00= xb - xa;
				    	var m10= yb - ya;

						var coun= 0;
			            for ( var j=1; j<regiCoorMatrCoun; j++ ) {
					    	valuList= [[regiCoorMatr objectAtIndex:j-1] valueList];
					    	var xc= [[valuList objectAtIndex:0] doubleValue];
					    	var yc= [[valuList objectAtIndex:1] doubleValue];
					    	valuList= [[regiCoorMatr objectAtIndex:j] valueList];
					    	var xd= [[valuList objectAtIndex:0] doubleValue];
					    	var yd= [[valuList objectAtIndex:1] doubleValue];
		    	
					    	var m01= xc - xd;
					    	var m11= yc - yd;
					    	var r0 = xc - xa;
					    	var r1 = yc - ya;
			    	
					    	var dete= m00*m11 - m01*m10;
					    	var im00= m11/dete;
					    	var im01= - m01/dete;
					    	var im10= - m10/dete;
					    	var im11= m00/dete;
			    	
					    	var alph= im00*r0 + im01*r1;
					    	var beta= im10*r0 + im11*r1;

					    	if ( alph>=0 && alph<=1. && beta>=0 && beta<=1. )
					    		coun++;
			            }
				    	valuList= [[regiCoorMatr objectAtIndex:regiCoorMatrCoun-1] valueList];
				    	var xc= [[valuList objectAtIndex:0] doubleValue];
				    	var yc= [[valuList objectAtIndex:1] doubleValue];
				    	valuList= [[regiCoorMatr objectAtIndex:0] valueList];
				    	var xd= [[valuList objectAtIndex:0] doubleValue];
				    	var yd= [[valuList objectAtIndex:1] doubleValue];
			    	
				    	var m01= xc - xd;
				    	var m11= yc - yd;
				    	var r0 = xc - xa;
				    	var r1 = yc - ya;
			    	
				    	var dete= m00*m11 - m01*m10;
				    	var im00= m11/dete;
				    	var im01= - m01/dete;
				    	var im10= - m10/dete;
				    	var im11= m00/dete;
			    	
				    	var alph= im00*r0 + im01*r1;
				    	var beta= im10*r0 + im11*r1;
				    	if ( alph>=0 && alph<=1. && beta>=0 && beta<=1. )
				    		coun++;

			            rema= coun%2;
			            if ( rema == 1 ) {
				            //alert("bezier checking "+objeName+"  coun="+coun+"  odd");
			            	if ( t == 0 ) {
				                statSolu= objeName;
				                [statPopu selectItemWithTitle:statSolu];
				                [statPopu setTitle:statSolu];
				            }
			            	else if ( t == 1 ) {
				                cntySolu= objeName;
				                [cntyPopu selectItemWithTitle:cntySolu];
				                [cntyPopu setTitle:cntySolu];
				            }
			            	else if ( t == 2 ) {
				                dstrSolu= objeName;
				                [dstrPopu selectItemWithTitle:dstrSolu];
				                [dstrPopu setTitle:dstrSolu];
				            }
			                break;
			            }
			        }

		        }
		    }
	    }
    }
}



- (void) resetFields {
	[cntrPopu removeAllItems];
	[cntrPopu addItemWithTitle:@"Pais"];
	var puntArra= [self query:@"select distinct country from riglobal.puntos_dbf order by country"];
	var puntArraCoun= [puntArra count];
	[messText setStringValue:[CPString stringWithFormat:@"Numero de paises= %d.",puntArraCoun]];
	var puntInde;
	for ( puntInde=0; puntInde<puntArraCoun; puntInde++ ) {
		var punt= [[[puntArra objectAtIndex:puntInde] valueList] objectAtIndex:0];
		if ( punt && [punt length]>0 && ![punt isEqualToString:@"."] && ![punt isEqualToString:@"(null)"] && ![punt isEqualToString:@"newValue"] )
			[cntrPopu addItemWithTitle:punt];
	}

	[statPopu removeAllItems];
	[cntyPopu removeAllItems];
	[dstrPopu removeAllItems]
	[cityPopu removeAllItems];
	[refeConsPopu removeAllItems];
	
	[statPopu setTitle:@"Estado/Provincia"];
	[cntyPopu setTitle:@"Canton"];
	[dstrPopu setTitle:@"Distrito"];
	[cityPopu setTitle:@"Ciudad"];
	[refeConsPopu setTitle:@"Consideracion"];
	
	[refeConsPopu addItemWithTitle:@"Ninguna"];
	[refeConsPopu addItemWithTitle:@"Pais"];
	[refeConsPopu addItemWithTitle:@"Estado/Provincia"];
	[refeConsPopu addItemWithTitle:@"Canton"];
	[refeConsPopu addItemWithTitle:@"Distrito"];
	[refeConsPopu addItemWithTitle:@"Ciudad"];
	[refeConsPopu addItemWithTitle:@"Desplegadas en Popup"];
	[refeConsPopu addItemWithTitle:@"Desplegadas en Mapa"];
}



- (void)  returndirection {
	var auxAddrId;
	/*
	create table addresses ( 
	addressId varchar(32), 
	address1 varchar(64), 
	address2 varchar(64), 
	city varchar(32), 
	district varchar(32), 
	county varchar(32), 
	state varchar(32), 
	country varchar(32), 
	postalCode varchar(8), 
	postBox varchar(8), 
	longitude real, 
	latitude real );
	*/
	[self referenceTakeCoordinatesButtonAction];
	
	var quer= @"select count(*) from rsmcore_credomatic.addresses";
	counAddrArra	= [self query:quer];
	if ( [counAddrArra count]>0 ) {
		counAddr		= [[[counAddrArra objectAtIndex:0] valueList] objectAtIndex:0];
	}
	
	//alert(anAddress);
	addrCode = "addressId"+counAddr;
	
	quer = @"insert into rsmcore_credomatic.addresses (addressId , address1 , address2 , city , district ,county , state, country, postalCode , postBox, longitude, latitude) values ('"+addrCode+"','"+addr+"', 'null', '"+[cityPopu title]+"','"+[dstrPopu title]+"','"+[cntyPopu title]+"','"+[statPopu title]+"','"+[cntrPopu title]+"','PC00000','PB00000',"+[self clientLongitude]+","+[self clientLatitude]+")";
	[self query:quer];
	
	/*
	create table personAddress (  
	personId varchar(32), 
	addressId varchar(32), 
	type varchar(32) );
	*/
	
	quer = @"insert into rsmcore_credomatic.personAddress (personId,addressId,type) values ('"+persId+"','addressId"+counAddr+"','"+addrType+"')";
	[self query:quer];
	
	[mapPane close];	
	[mainPane close];
}



- (void) setMouseLocation:(MKLocation)loca {
	mousLoca = loca;
}



- (CPArray) query:(CPString)aQuery {
	if ( !connector )
		connector = [[ServerConnector alloc] init];

	var tim1= [CPDate date];
	XML = [connector obtainFromServerXML:aQuery];
	var tim2= [CPDate date];
	var timeDiff= [tim2 timeIntervalSinceDate:tim1];

	var regiList= [XML elements];
	return regiList;
}



- (void) statePopupAction {
		var stat= [statPopu titleOfSelectedItem];
		[statPopu setTitle:stat];
		[refeConsPopu selectItemWithTitle:@"Estado/Provincia"];
		[refeConsPopu setTitle:@"Estado/Provincia"];

		var quer= [CPString stringWithFormat:@"select distinct county from riglobal.puntos_dbf where state='%@' order by county",stat];
		var puntArra= [self query:quer];
		var puntArraCoun= [puntArra count];
		var puntInde;
		[cntyPopu removeAllItems];
		[cntyPopu addItemWithTitle:@"Seleccione uno de los siguientes..."];
		for ( puntInde=0; puntInde<puntArraCoun; puntInde++ ) {
			var punt= [[[puntArra objectAtIndex:puntInde] valueList] objectAtIndex:0];
			if ( punt && [punt length]>0 && ![punt isEqualToString:@"."] && ![punt isEqualToString:@"(null)"] && ![punt isEqualToString:@"newValue"] )
				[cntyPopu addItemWithTitle:punt];
		}
		[cntyPopu setTitle:@"Canton"];

		if ( puntArraCoun>0 )
			puntArraCoun--;
		[messText setStringValue:[CPString stringWithFormat:@"Se encontraron %d cantones",puntArraCoun]];
		
		[dstrPopu removeAllItems];
		[cityPopu removeAllItems];
		[referenceDict removeAllObjects];
		[refePopu removeAllItems];
}



// CPTableView Delegate Methods

// Some type of Delegate
- (void) windowClose {
	if ( inpuPane ) {
		[inpuPane close];
		[inpuPane release];
		inpuPane= NULL;
	}
	if ( mainPane ) {
		[mainPane close];
		[mainPane release];
		mainPane= NULL;
	}
	if ( mapPane ) {
		[mapPane close];
		[mapPane release];
		mapPane= NULL;
	}
}



@end


/*
- (void) RAknowAddrPopuAction {
	[nameClieTextFiel setStringValue:@""]; 
	[lastName1TextFiel setStringValue:@""];
	[lastName2TextFiel setStringValue:@""];
	[fullAddrTextFiel setStringValue:@""];
	[typeAddrFiel setStringValue:@""];
	
	
	clieCode =[RAclieCodeTextFiel stringValue];
	quer = @"select addressId,type from rsmcore_credomatic.personAddress where personId ='"+clieCode+"'";
	var addrArra		= [self query:quer];
	var addrArraCoun	= [addrArra count];
	var addrInde;
	var auxDist;
	var auxCoun;
	var auxStri;
	var auxAddr;
	
	addrDict= [[CPDictionary alloc] init]; 
	
	if ( addrArraCoun==0 ) {
		[RAknowAddrPopu setTitle:"No se hallaron direcciones"];
		//[checButt setEnabled:NO];
	}
	else
	{
		quer = @"select nameFirst,nameLast from rsmcore_credomatic.person where personId ='"+clieCode+"'";	
		var persArra		= [self query:quer];
		var persArraCoun	= [persArra count];
		var persInde;
		var lastStri;
		var charInde;
		var auxAddrId = [addrDict objectForKey:[RAknowAddrPopu title]];
		//var auxLati;
		//var auxLong;
	
		for ( persInde = 0; persInde < persArraCoun; persInde++ ) {
			[nameClieTextFiel setStringValue:[[[persArra objectAtIndex:persInde] valueList] objectAtIndex:0]];
			lastStri = [[[persArra objectAtIndex:persInde] valueList] objectAtIndex:1];
			charInde = lastStri.indexOf("_");
			[lastName1TextFiel setStringValue:lastStri.substr(0,charInde)];
			[lastName2TextFiel setStringValue:lastStri.substr(charInde+1)];
		}
		
		[RAknowAddrPopu removeAllItems];
		var auxMenuItem = [[CPMenuItem alloc] init];
		[auxMenuItem setTitle:"Introducir nueva direcci\xf3n"];
		[auxMenuItem setTarget:self];
		[auxMenuItem setAction:@selector(RAchooKnowAddr:)]; 
		
		[RAknowAddrPopu addItem:auxMenuItem];
		[RAknowAddrPopu addItem:auxMenuItem];
		
		[RAknowAddrPopu addItem:[[CPMenuItem alloc] initWithTitle:"Introducir nueva direcci\xf3n"  action:@selector(RAchooKnowAddr:) keyEquivalent:nil]];
		for ( addrInde=0; addrInde<addrArraCoun; addrInde++ ) 
		{
			auxAddrId	= [[[addrArra objectAtIndex:addrInde] valueList] objectAtIndex:0];
			auxType		= [[[addrArra objectAtIndex:addrInde] valueList] objectAtIndex:1];
			quer		= @"select district,county,address1 from rsmcore_credomatic.addresses where addressId ='"+auxAddrId+"'";
			var addrArra2 = [self query:quer];
			auxDist	= [[[addrArra2 objectAtIndex:0] valueList] objectAtIndex:0];
			auxCoun	= [[[addrArra2 objectAtIndex:0] valueList] objectAtIndex:1];
			auxAddr = [[[addrArra2 objectAtIndex:0] valueList] objectAtIndex:2];
			auxStri = auxType+" en "+auxDist+", "+auxCoun;
			[RAknowAddrPopu addItem:[[CPMenuItem alloc] initWithTitle:auxStri action:@selector(RAchooKnowAddr:) keyEquivalent:nil]];
			[addrDict setObject:auxAddrId forKey:auxStri];
			[RAknowAddrPopu setTitle:"Se hallaron direcciones"];
		}
	}

	
}



- (void) RAchooKnowAddr:(id)sender {
	var auxLong;
	var auxLati;
	var auxTitl = [sender title];
	//[knowAddrPopu setTitle:auxTitl];
	if ( auxTitl == "Introducir nueva direcci\xf3n" || auxTitl == "Se hallaron direcciones" ) {
		[fullAddrTextFiel setStringValue:@""];
		[typeAddrFiel setStringValue:@""];
	}
	else {
		var auxAddrId = [addrDict objectForKey:[sender title]];
		quer = @"select type from rsmcore_credomatic.personAddress where personId ='"+clieCode+"' and addressId = '"+auxAddrId+"'";
		var typeArra		= [self query:quer];
		[typeAddrFiel setStringValue:[[[typeArra objectAtIndex:0] valueList] objectAtIndex:0]];
	
		quer = @"select address1,latitude,longitude from rsmcore_credomatic.addresses where addressId='"+[addrDict objectForKey:[RAknowAddrPopu title]]+"'"; 
		var AddrArra		= [self query:quer];
		[fullAddrTextFiel setStringValue:[[[AddrArra objectAtIndex:0] valueList] objectAtIndex:0]];
		auxLati = [[[AddrArra objectAtIndex:0] valueList] objectAtIndex:1];
		auxLong = [[[AddrArra objectAtIndex:0] valueList] objectAtIndex:2];
	
	
		cliePoin= [[RSMPoint alloc] init];
			[cliePoin  setLati:auxLati];
			[cliePoin  setLong:auxLong];
		addrCode = auxAddrId;
	}

}




*/
