var exclude=/[^@\-\.\w]|^[_@\.\-]|[\._\-]{2}|[@\.]{2}|(@)[^@]*\1/;
var check=/@[\w\-]+\./;
var checkend=/\.[a-zA-Z]{2,3}$/;

var ra, dec, z, mylocation

reserveThisField = function() {
	$('#reserveRow').hide();
	$('#reserveform').show();
	updateTarget();
}

checkEmail = function(el, value){
	if (((value.search(exclude) != -1) || (value.search(check)) == -1) || (value.search(checkend) == -1)) {
		// Not valid email format
		$('#InvalidEntry').show();
		$('#RequestAccount').hide();
		$('#PasswordRow').hide();
	} else {
		// Valid email format
		$('#InvalidEntry').hide();
		$.get('/utilities/login.asp', { action: 'checkemail', email: value },	function(data){	eval(data);	});
	}
}

reConfirm = function(value) {
	$.get('/utilities/login.asp', { action: 'reconfirm', email: value }, function(data){	eval(data);	});
}

requestPassword = function(value) {
	$.get('/utilities/login.asp', { action: 'mailpassword', email: value }, function(data){	eval(data);	});
}

checkPassword = function(el, value){
	$.get('/utilities/login.asp', { action: 'checkpassword', email: $('#user').val(), password: value }, function(data){	eval(data);	});
}

checkSession = function() {
	showPage(mylocation);
}

submitAccountRequest = function() {
	$.get('/utilities/login.asp', { action: 'requestaccount',  email: $('#user').val(), password: $('#pw2').val() }, function(data){	eval(data);	} );
}

getMyFields = function () {
	$('#myfields').load('myfields.asp');
}

browseSky = function(thisr, thisd, thisz) {
	//$('dssfieldSelector').update('<div style="height:480px;width:480px;background-color:#ffffff;vertical-align:middle;text-align:center;background-image:url(\'images/throbber.gif\');background-position:center center;background-repeat:no-repeat;"></div>');
	
	thisdecimaldec = getDecimalDec(thisd);
	thisdecimalra = RAtoDecimal(thisr);

	$('#dssfieldSelector').hide();
	$('#navtools').hide();
	$('#fieldSelector').show();
	map.setCenter(new GLatLng(thisdecimaldec, 180-thisdecimalra), thisz);
	
		
	ra = thisr;
	dec = thisd;
	z = thisz;	
	temp = ra.split(':');
	$('#ra1').val(temp[0]);
	$('#ra2').val(temp[1]);
	$('#ra3').val(temp[2]);
	temp = dec.split(':');
	$('#dec1').val(temp[0]);
	$('#dec2').val(temp[1]);
	$('#dec3').val(temp[2]);
	
}

zoomin = function() {
	z = z / 2;
	if (z<1) {
		z=1; 
		alert('Sorry, the browser only zooms in to 1 pixel/arcsecond');
	};
	if (z==1) {
		$('zoomin').src='images/spacer.gif';
	}
	$('zoomout').src='images/zoomout.gif';
	browseSky(ra, dec, z)
}

zoomout = function() {
	z = z * 2;
	if (z > 128) {
		z=128;
		alert('Sorry, the browser only zooms out to 8 pixels/arcsecond');
	};
	if (z==128) {
		$('zoomout').src='images/spacer.gif';
	}
	$('zoomin').src='images/zoomin.gif';
	browseSky(ra, dec, z);
}


navup = function () {
	changeDec(z*240)
}

navdown = function() {
	changeDec(z*240*-1)
}

changeDec = function(moveseconds) {
	decangle = getDecimalDec(dec);
	decangle = decangle + (moveseconds/3600);
	if (decangle < -90) {
		decangle = -90;
		alert('Sorry, the browser only goes down to -90 decrees in declination');
	}
	if (decangle > 90) {
		alert('Sorry, the browser only goes up to 90 degrees in declination');
		decangle = 90;
	}
	if (decangle < 0) {
		temp[0] = Math.ceil(decangle);
		if (temp[0] == 0) {
			temp[0] = '-' + temp[0];
		} else {
			
		}
		decangle = (decangle - temp[0])*60;
		temp[1] = Math.abs(Math.ceil(decangle));
		decangle = parseFloat((decangle + temp[1])*60);
		temp[2] = Math.abs(Math.round(decangle));
	} else {
		temp[0] = Math.floor(decangle);
		decangle = (decangle - temp[0]) * 60;
		temp[1] = Math.floor(decangle);
		decangle = (decangle - temp[1]) * 60;
		temp[2] = Math.round(decangle);
	}
	dec = temp.join('+');
	browseSky(ra, dec, z);
}	
	

navleft = function() {
	decimalDec = getDecimalDec(dec);
	thisCos = Math.cos(parseFloat(decimalDec) * Math.PI / 180);
	if (thisCos < 0) {
		raShift = 0;
	} else {
		raShift = ((1/thisCos) * z * 240)/60/4; 
	}
	changeRA(raShift);
}

navright = function() {
	decimalDec = getDecimalDec(dec);
	thisCos = Math.cos(parseFloat(decimalDec) * Math.PI / 180);
	if (thisCos < 0) {
		raShift = 0;
	} else {
		raShift = ((1/thisCos) * z * -240)/60/4; 
	}
	changeRA(raShift);
}

function getDecimalDec(decString) {
	var temp = new Array();
	decString = decString.replace('+', ':', 'g')
	temp = decString.split(':'); //temp[0] = degrees, temp[1] = minutes, temp[2] = seconds
	
	temp[2] = parseFloat(temp[2].replace('[', '.'))/3600;
	temp[1] = parseFloat(temp[1])/60;
	if (temp[0].substring(0,1) == '-') {
		decangle = 0 - (Math.abs(temp[0]) + temp[1] + temp[2]);
	} else {
		decangle = 0 + parseFloat(temp[0]) + temp[1] + temp[2];
	}
	return decangle;
}

function RAtoDecimal(raString) {
	var temp = new Array();
	raString = raString.replace('+', ':', 'g')
	temp = raString.split(':'); //temp[0] = hours, temp[1] = minutes, temp[2] = seconds
	temp[0] = parseFloat(temp[0]) * 15;
	temp[1] = parseFloat(temp[1]) * .25;
	temp[2] = parseFloat(temp[2].replace('[', '.')) / 240;
	RAangle = (temp[0] + temp[1] + temp[2]) ;
	return RAangle;
}

function decimalToRA(degrees) {
	if (degrees < 0) {
		degrees = degrees + 360;
	}
	temp4 = new Array();
	temp4[0] = Math.floor(degrees / 15);
	degrees = degrees - (temp4[0] * 15);
	temp4[1] = Math.floor(degrees * 4);
	degrees = degrees - (temp4[1] / 4);
	temp4[2] = Math.round(degrees * 240);
	result = temp4.join('+');
	return result;
}

function decimalToDEC(latitude) {
  if (latitude < 0) return '-' + decimalToDEC(- latitude);
  var DEC = Math.floor(latitude).toString() + '+';
  latitude = (latitude - Math.floor(latitude)) * 60;
  DEC += Math.floor(latitude).toString() + '+';
  latitude = (latitude - Math.floor(latitude)) * 60;
  DEC += latitude.toFixed(1) + '';
  return DEC;
}


changeRA = function(moveseconds) {
	RAangle = RAtoDecimal(ra);
	RAangle = RAangle + (moveseconds/15);
	if (RAangle < 0) {
		RAangle = 360+RAangle;
	}
	if (RAangle >= 360) {
		RAangle = RAangle - 360;
	}
	ra = decimalToRA(RAangle);
	browseSky(ra, dec, z);
}

showPage = function(thisPage) {
	$('welcome').hide();
	$('status').hide();
	$('reserve').hide();
	$('fields').hide();
	$('profile').hide();
	
	
	$('statustab').hide();
	$('reservetab').hide();
	$('fieldstab').hide();
	$('profiletab').hide();
	
	$(thisPage).show();
	
	if (thisPage != 'welcome') {
		$(thisPage+'tab').show();
		$('tabs').show();
	} else {
		checkEmail($('user'), $('user').value);
	}	
	mylocation = thisPage;
	new Ajax.Request('/utilities/snsearch.asp?action=updateLocation', {
  		method: 'post',
  		parameters: { action: 'updateLocation',  mylocation: thisPage }
	});
}

reserveFieldNow = function() {
	thisra = $('#ra1').val()+'+'+$('#ra2').val()+'+'+$('#ra3').val();
	thisdec = $('#dec1').val()+'+'+$('#dec2').val()+'+'+$('#dec3').val();
	thiswidth = $('#ccdwidth').val();
	thisheight = $('#ccdheight').val();
	thisroll = $('#roll').val();
	thisdecimaldec = getDecimalDec(thisdec);
	thisdecimalra = RAtoDecimal(thisra);
	$.get("/utilities/snsearch.asp", 
		{ action: 'reserveField', r: thisra, d: thisdec, w: thiswidth, h: thisheight, l: thisroll, dd: thisdecimaldec, dr: thisdecimalra }, 
		function(data){
          eval(data);
         }
 	);
		
}

updateFieldNow = function() {
	thisid = $("#editFieldid").val();
	thisra = $("#editFieldRA1").val()+'+'+$("#editFieldRA2").val()+'+'+$("#editFieldRA3").val();
	thisdec = $("#editFieldDEC1").val()+'+'+$("#editFieldDEC2").val()+'+'+$("#editFieldDEC3").val();
	thiswidth = $("#editFieldWidth").val();
	thisheight = $("#editFieldHeight").val();
	thisroll = $("#editFieldRoll").val();
	thisdecimaldec = getDecimalDec(thisdec);
	thisdecimalra = RAtoDecimal(thisra);
	thisfieldlabel = $("#editFieldLabel").val();
	thislecho = $("#editFieldLecho").val();
	
	$.post("/utilities/snsearch.asp", { action: 'updateField', t: Date(), r: thisra, d: thisdec, w: thiswidth, h: thisheight, l: thisroll, dd: thisdecimaldec, dr: thisdecimalra, b: thisfieldlabel, e: thislecho, i: thisid },
		function(data){
    		$("#editField").dialog("close");
    		window.location.href="fields.asp?fieldpk="+thisid;
		}
	);
}

var map, skyLayerManager, menuVersionN = 0;
var kmlOverlay = null, planetKmlOverlay = null, constOverlay = null;  // Simplify: there will be only one or zero + 1 or 0 planets
function gotoInit() {
  map.setCenter(new GLatLng(69.35708, 30.9375), 7);
}


loadSky = function() {
  //resizeMap();
  
  var initOpacity = {'Spitzer': 0, 'ChandraXO': 0, 'Galex': 0, 'IRAS': 0, 'WMAP': 0, 'Cassini': 0};
  var initSlide = 1, lmIndex = -1, loIndex = -1;
  var initLat = parseFloat(getDecimalDec('65:45:0'));
	var initLng = parseFloat(RAtoDecimal('0:25:6'));
	var initZoom = 4;
	try {
	var urlInfo = document.location.toString().split('?');
	if (urlInfo.length == 2) {
	  var params = urlInfo[1].split('&');
	 
	  for (var i = 0; i < params.length; i++) {
		var paramInfo = params[i].split('=');
		if (paramInfo.length == 2) {
		  switch (paramInfo[0]) {
			case 'd': initLat = parseFloat(paramInfo[1]); break;
			case 'r': initLng = parseFloat(paramInfo[1]); break;
			case 'z': initZoom = parseFloat(paramInfo[1]); break;
		  }
		}
	  }
	}
  } catch (ex) {
		var initLat = parseFloat(getDecimalDec('0:25:6'));
		var initLng = parseFloat(RAtoDecimal('65:45:0'));
		var initZoom = 8;
	}
	 //alert(initLat);
  if (GBrowserIsCompatible()) {
	map = new GMap2(document.getElementById("fieldSelector"), {logoPassive: true});
	
	map.setCenter(new GLatLng(initLat, 180 - initLng), initZoom);
	
	GEvent.addListener(map, "moveend", function() {
	  var center = map.getCenter();
	  zoom = map.getZoom();
	  if (zoom > 100) {
	  	$('#fieldSelector').hide();
	  	$('#dssfieldSelector').show();
	  	$('#navtools').show();
	  	
	  	//browseSky(decimalToRA(center.lng()), decimalToDEC(center.lat()), 8)
	  }
	  updateCoordDisplay(center);
	});
	
	//map.addControl(new GMapTypeControl());
	map.addControl(new GLargeMapControl());
	
	generateSkyMap(map, getSkyTileLayer());

	skyLayerManager = new SkyLayerManager(map);
	//map.addControl(new CoordDisplay());
	//map.addControl(new QuadtreeBoxes());
  }
  map.disableScrollWheelZoom();
  //resizeMap(); 
}

updateCoordDisplay = function(center){
	var temp = new Array();
	ra = center.lng();
	dec = center.lat();
	
	rasrt = decimalToRA(180-ra);
	decstr = decimalToDEC(dec);
	
	temp = rasrt.split('+');
	$('#ra1').val(temp[0]);
	$('#ra2').val(temp[1]);
	$('#ra3').val(temp[2]);
	temp = decstr.split('+');
	$('#dec1').val(temp[0]);
	$('#dec2').val(temp[1]);
	$('#dec3').val(temp[2]);
}
    

function generateSkyUrl() {
  var url = document.location.toString().split('#');
  url = url[0];
  url += '#latitude=' + map.getCenter().lat().toString() + '&';
  url += 'longitude=' + (- map.getCenter().lng().toString()).toString() + '&';
  url += 'zoom=' + map.getZoom().toString() + '&';
  var layers = ['Spitzer', 'ChandraXO', 'Galex', 'IRAS', 'WMAP', 'Cassini'];
  for (var ln = 0; ln < layers.length; ln++) {
	url += layers[ln] + '=' + skyLayerManager.getOverlayOpacity(layers[ln]).toFixed(2) + '&';
  }
  url += 'slide=' + currentMenuSlide + '&mI=' + lastClickedMenu[0] + '&oI=' + lastClickedMenu[1];
  document.location = url;
}
function popUpPrint(URL) {
  var print = window.open(URL, 'print', 'toolbar=0,scrollbars=1,location=0,statusbar=1,menubar=0,resizable=1');
}
function printPopUp() {
  var zoom = map.getZoom();
  var bounds = map.getBounds();
  var swbound = bounds.getSouthWest();
  var nebound = bounds.getNorthEast();
  var projection = map.getCurrentMapType().getProjection();
  var swPixel = projection.fromLatLngToPixel(swbound, zoom);
  var nePixel = projection.fromLatLngToPixel(nebound, zoom);
  var x0 = Math.floor(swPixel.x / 256);
  var y0 = Math.floor(nePixel.y / 256);
  var x1 = Math.floor(nePixel.x / 256);
  var y1 = Math.floor(swPixel.y / 256);
  popUpPrint('print.html#' + x0 + ',' + x1 + ',' + y0 + ',' + y1 + ',' + zoom);
}
function centerKML() {
  var center = map.getCenter();
  document.location = 'http://maps.google.com/maps?output=kml&q=sky:' + 
					  center.lat().toString() + ',' + (- center.lng()).toString();
}
function checkMapSize() {
  if (map) {
	map.checkResize();
	// Set the center to the current center, this way moveend will fire
	map.setCenter(map.getCenter(), map.getZoom());
  }
}
function moveSliderHeader() {
  try {
	var slider = document.getElementById("slider");
	var sliderPos = getPosition(slider);
	var left = parseInt(slider.scrollLeft) + 2;
	var sliderHeader = document.getElementById("sliderHeader");
	sliderHeader.style.left = left.toString() + 'px';
  } catch (ex) {
  }
}

function addFieldToSky(r, d, rd, dd, e, w, h, l, p) {
					
	var brushcolor, thisicon, thisStatus, options, radius, point
	
	switch (e) {
		
		case 'True':
			brushColor = '#01FF01';
			thisicon = iconGreen;
			thisStatus = 'Echo Observed';
			break;
		case 'False':
			brushColor = '#FF0101';
			thisicon = iconRed;
			thisStatus = 'No Echo Observed';
			break;
		case 'rem':
			brushColor = '#0101FF';
			thisicon = iconBlue;
			thisStatus = 'Supernova Remnant';
			break;
		case 'target':
			brushColor = '#FF6601';
			thisicon = iconOrange;
			thisStatus = 'Target';
			break;
		default:
			brushColor = '#FFFF01';
			thisicon = iconYellow;
			thisStatus = 'Reserved';
	}
	
	options = { 
		title: p,
		icon: thisicon,
		draggable: false,
		bouncy: false
	};	
	
	switch (l) {
		case 999:
			radius = w > h ? h : w
			polygon = drawCircle(dd, 180 - rd, radius, brushColor, 1, 0.75, brushcolor,.5,e);
			var point = new GLatLng(parseFloat(dd), 180 - parseFloat(rd));
			break;
		case 0:
			
			d2r = Math.PI / 180.0;
			crd = 180.0 - rd;
			ch = h / 120.0;
			cw = w / 120.0;
			
			p1y = dd + ch;
			p12o = cw / Math.cos(p1y * d2r)
			p1x = crd + p12o;
			p2x = crd - p12o;
			
			p3y = dd - ch;
			p34o = cw / Math.cos(p3y * d2r)
			p3x = crd - p34o;
			p4x = crd + p34o;
			
			if (     ( (p1x > 180) && (p2x < 180) )     ||     ( (p1x > -180) && (p2x < -180) )     ) {
				// Handle 180 RA bug here
				polygon = new GPolygon([
					new GLatLng(p1y, p1x),
					new GLatLng(p1y, -180),
					new GLatLng(p3y, -180),
					new GLatLng(p3y, p4x),
					new GLatLng(p1y, p1x)
				], brushColor, 1, 0, brushColor, 0.2);
				addPoly(polygon, e, 1);
				
				polyline = new GPolyline([
					new GLatLng(p1y, -180),
					new GLatLng(p1y, p1x),
					new GLatLng(p3y, p4x),
					new GLatLng(p3y, -180)
				], brushColor, 1, 1);
				addPoly(polyline, e, 0);
				
				polyline = new GPolyline([
					new GLatLng(p1y, 180),
					new GLatLng(p1y, p2x),
					new GLatLng(p3y, p2x),
					new GLatLng(p3y, 180)
				], brushColor, 1, 1);
				addPoly(polyline, e, 0);
				
				polygon = new GPolygon([
					new GLatLng(p1y, 180),
					new GLatLng(p1y, p2x),
					new GLatLng(p3y, p3x),
					new GLatLng(p3y, 180),
					new GLatLng(p1y, 180)
				], brushColor, 1, 0, brushColor, 0.2);
				addPoly(polygon, e, 0);
				} else {
				
				polygon = new GPolygon([
					new GLatLng(p1y, p1x),
					new GLatLng(p1y, p2x),
					new GLatLng(p3y, p3x),
					new GLatLng(p3y, p4x),
					new GLatLng(p1y, p1x)
				], brushColor, 1, 1, brushColor, 0.2);
				addPoly(polygon, e, 0);
			}
			var point = new GLatLng(parseFloat(dd), 180 - parseFloat(rd));
			break;
		default:
			// Handle rotated field here
			degrees2RadiansFactor = Math.PI / 180.0;
			crd = 180.0 - rd;
			ch = h / 120.0;
			cw = w / 120.0;
			
			p1theta = Math.atan(ch/cw)-(l*degrees2RadiansFactor);
			p2theta = Math.PI-Math.atan(ch/cw)-(l*degrees2RadiansFactor);
			p3theta = Math.PI+p1theta;
			p4theta = p2theta-Math.PI;
			
			var hypo = Math.sqrt(Math.pow(ch,2) + Math.pow(cw,2));
			
			p1y = dd + hypo*Math.sin(p1theta);
			p1x = crd + hypo*Math.cos(p1theta) / Math.cos(p1y * degrees2RadiansFactor);
			
			p2y = dd + hypo*Math.sin(p2theta);
			p2x = crd + hypo*Math.cos(p2theta) / Math.cos(p2y * degrees2RadiansFactor);
			
			p3y = dd + hypo*Math.sin(p3theta);
			p3x = crd + hypo*Math.cos(p3theta) / Math.cos(p3y * degrees2RadiansFactor);
			
			p4y = dd + hypo*Math.sin(p4theta);
			p4x = crd + hypo*Math.cos(p4theta) / Math.cos(p3y * degrees2RadiansFactor);
			
			polygon = new GPolygon([
				new GLatLng(p1y, p1x),
				new GLatLng(p2y, p2x),
				new GLatLng(p3y, p3x),
				new GLatLng(p4y, p4x),
				new GLatLng(p1y, p1x)
			], brushColor, 1, 1, brushColor, 0.2);
			addPoly(polygon, e, 0);
			
			
			var point = new GLatLng(dd, 180 - rd);
			//addPoly(polygon, e, 0);
	}
	
	marker = new GMarker(point, options);
	
	
	
	switch (e) {
		case 'rem':
			remnants.push(marker);
			break;
		//case 'target':
			//target.push(marker);
		case 'True':
			observed.push(marker);
			break;
		case 'False':
			nobserved.push(marker);
			break;
		default:
			reserved.push(marker);
	}
	marker.bindInfoWindow('<div style="width:100; height: 30;"><strong><a href="/fields.asp?fieldpk='+p+'">'+p+'</a></strong> - '+thisStatus+'<br/>RA: '+r+', DEC: '+d+'<br/>FOV: '+w+'\' x '+h+'\'</div>');

}
	
function addPoly(tpolygon, e, test) {
	switch (e) {
		case 'rem':
			remnantsPoly.push(tpolygon);
			break;
		case 'target':
			targetPoly.push(tpolygon);
			break;
		case 'True':
			observedPoly.push(tpolygon);
			break;
		case 'False':
			nobservedPoly.push(tpolygon);
			break;
		default:
			reservedPoly.push(tpolygon);
	}
}

function drawCircle(lat, lng, radius, strokeColor, strokeWidth, strokeOpacity, fillColor, fillOpacity, e) {
	//if (e = 'rem') {
	//	strokeColor = '#00ff00';
	//	strokeWidth = 1;
	//	strokeOpacity = .1;
	//	fillColor = '#00ff00';
	//	fillOpacity = .1;
	//}
	var d2r = Math.PI/180;
	var r2d = 180/Math.PI;
	var Clat = radius / 60;  // Convert minutes into degrees latitude
	var Clng = Clat/Math.cos(lat*d2r); 
	var Cpoints = []; 
	var lftPoints = [];
	var rtPoints = [];
	extremeLeft = lng + (Clng * Math.cos(0));
	extremeRight = lng - (Clng * Math.cos(0));
	for (var i=0; i < 33; i++) { 
		var theta = Math.PI * (i/16); 
		Cy = lat + (Clat * Math.sin(theta)); 
		Cx = lng + (Clng * Math.cos(theta)); 
		var P = new GPoint(Cx,Cy); 
		Cpoints.push(P); 
	}
	if (     ( (extremeLeft > 180) && (extremeRight < 180) )     ||     ( (extremeLeft > -180) && (extremeRight < -180) )     ) {
		
		jQuery.each(Cpoints, function() {
			if ((this.x < -180) || (this.x > 0 && this.x < 180)) {
				lftPoints.push(this);
			} else {
				rtPoints.push(this);
			}
		});
		
		temp = rtPoints;
		rtPoints = temp.slice(temp.length/2).concat(temp.slice(1,(temp.length/2-1)));
		
		x1=rtPoints[rtPoints.length - 1].x;
		x2=lftPoints[0].x;
		y1=rtPoints[rtPoints.length - 1].y;
		y2=lftPoints[0].y;
		m = (y2-y1)/(x2-x1);
		if (x1 > 180) {newx = 180.001; newx2 = 179.999;}
		if (x1 < -180) {newx = -180.001; newx2 = -179.999}
		if (x1 > -180 && x2 < 0) {newx = -179.999; newx2 = -180.001;}
		if (x1 > 0 && x2 < 180) {newx = 179.999; newx2 = 180.001;}
		newy = y1-(x1-newx)*m;
		var P = new GPoint(newx,newy);
		rtPoints.push(P);
		var P = new GPoint(newx2,newy);
		lftPoints.unshift(P);
		
		x1=lftPoints[lftPoints.length - 1].x;
		x2=rtPoints[0].x;
		y1=lftPoints[lftPoints.length - 1].y;
		y2=rtPoints[0].y;
		m = (y2-y1)/(x2-x1);
		if (x1 > 180) {newx = 180.001; newx2 = 179.999; }
		if (x1 < -180) {newx = -180.001; newx2 = -179.999; }
		if (x1 > -180 && x2 < 0) {newx = -179.999; newx2 = -180.001; }
		if (x1 > 0 && x2 < 180) {newx = 179.999; newx2 = 180.001; }
		newy = y1-(x1-newx)*m;
		var P = new GPoint(newx,newy); 
		rtPoints.unshift(P);
		var P = new GPoint(newx2,newy); 
		lftPoints.push(P);
		//lftPoints.push(lftPoints[0]);
		//rtPoints.push(rtPoints[0]);
		
		var polygon = new GPolyline(rtPoints, strokeColor, strokeWidth, strokeOpacity);
		map.addOverlay(polygon);
		switch (e) {
			case 'rem':
				remnantsPoly.push(polygon);
				break;
			case 'target':
				targetPoly.push(polygon);
				break;
			case 'True':
				observedPoly.push(polygon);
				break;
			case 'False':
				nobservedPoly.push(polygon);
				break;
			default:
				reservedPoly.push(polygon);
		}
		
		var polygon = new GPolyline(lftPoints, strokeColor, strokeWidth, strokeOpacity);
		map.addOverlay(polygon);
		switch (e) {
			case 'rem':
				remnantsPoly.push(polygon);
				break;
			case 'target':
				targetPoly.push(polygon);
				break;
			case 'True':
				observedPoly.push(polygon);
				break;
			case 'False':
				nobservedPoly.push(polygon);
				break;
			default:
				reservedPoly.push(polygon);
		}
		
	} else {
		var polygon = new GPolygon(Cpoints, strokeColor, strokeWidth, strokeOpacity, fillColor, fillOpacity);
		map.addOverlay(polygon);
		switch (e) {
			case 'rem':
				remnantsPoly.push(polygon);
				break;
			case 'target':
				targetPoly.push(polygon);
				break;
			case 'True':
				observedPoly.push(polygon);
				break;
			case 'False':
				nobservedPoly.push(polygon);
				break;
			default:
				reservedPoly.push(polygon);
		}
		return polygon;
	}
	
 }
 
 function showMeThePoints(gPointArray) {
 	result = '';
 	jQuery.each(gPointArray, function() {
 		result = result + '[x:'+this.x+', y: '+this.y+'],   ';
 	});
 	alert(result);
 }
 
 
 
 
 
 
 
 