//DEFAULTS
if ( typeof(mapOptions) == 'undefined' ) mapOptions = [];
if ( !mapOptions['lineColor'] ) mapOptions['lineColor'] = 'red';
if ( !mapOptions['lineWeight'] ) mapOptions['lineWeight'] = 2;
if ( !mapOptions['lineOpacity'] ) mapOptions['lineOpacity'] = 1;
if ( !mapOptions['fillColor'] ) mapOptions['fillColor'] = 'red';
if ( !mapOptions['fillOpacity'] ) mapOptions['fillOpacity'] = 0.2;

coordArray = new Array();
drawMode = "";

// Make IE learn Array.indexOf
if(!Array.indexOf){
    Array.prototype.indexOf = function(obj){
        for(var i=0; i<this.length; i++){
            if(this[i]==obj){
                return i;
            }
        }
        return -1;
    }
}	
	
function load( targetID )
{
	if(GBrowserIsCompatible())
	{
		map = new GMap2(document.getElementById( targetID ));
		map.enableContinuousZoom();
		map.enableScrollWheelZoom();
        map.setCenter(new GLatLng(60.6, -147.07), 8);
		map.addControl(new GLargeMapControl());
		map.addControl(new GMapTypeControl());
		map.addControl(new GOverviewMapControl());
		map.addControl(new GScaleControl());		
		map.setMapType(G_SATELLITE_MAP);
		
		GEvent.addListener(map, 'click', mapClick);
		//GEvent.addListener(map, 'dblclick', mapDoubleClick);

	/*	GEvent.addListener(map, 'mousemove', updateMouseLatLng);
		GEvent.addListener(map, 'mouseout', clearMouseLatLng);
	*/
		/*geocoder = new GClientGeocoder();*/
	}
}

function mapClick(clickedMarker, clickedPoint)
{
	if (drawMode == "")
		return;
	
	// Push onto coordArray of existing polygon
	if ( typeof(clickedPoint) != 'undefined')
		coordArray.push(clickedPoint);
			
	drawCoordinates();	
	
	if (drawMode == 'point')
		endDraw();	
	else
	{
		drawMarker();
	}
} 	

function mapDoubleClick(marker, clickedPoint)
{
	/*mapClick(marker, clickedPoint);*/
	alert(coordArray);
}
 
function drawCoordinates()
{   
	if (drawMode == "")
		return;

	if (coordArray.length > 1)
		map.removeOverlay(polyShape);
				
	switch(drawMode)
	{
		case "point":
			var pointOpts = {
				 title: "Drag to reposition."
				,draggable: true
			}
			polyShape = new GMarker( coordArray[0], pointOpts);
			break;
		case "polygon":
			polyShape = new GPolygon(coordArray,mapOptions['lineColor'],mapOptions['lineWeight'],mapOptions['lineOpacity'],mapOptions['fillColor'],mapOptions['fillOpacity']);
			break;
		case "line":
			polyShape = new GPolyline(coordArray,mapOptions['lineColor'],mapOptions['lineWeight'],mapOptions['lineOpacity']);
			break;
		default:
			return;
			break;
	}
	
	
	map.addOverlay(polyShape);
	
	logCoordinates();
}

function drawMarker()
{
	// Grab last point of polyPoints to add marker
	//if ( typeof("marker") != "undefined")
	
	var blueIcon = new GIcon(G_DEFAULT_ICON);
	blueIcon.image = "http://www.google.com/intl/en_us/mapfiles/ms/micons/blue-dot.png"; 
	blueIcon.iconSize = new GSize(32, 32);
	
	var markerOpts = {
		 title: ""	
		,draggable: true
		,icon:G_DEFAULT_ICON
	}
		
	if (coordArray.length > 1)
	{
		//not first point
		map.removeOverlay(marker);
		markerOpts.title = "Click to finish drawing." 
	}
	else
	{
		//first point
		markerOpts.icon = blueIcon;
		
	}

	marker = new GMarker(coordArray[coordArray.length -1], markerOpts);

	if (coordArray.length > 1)
	{
		GEvent.addListener(marker, 'click', endDraw );
		GEvent.addListener(marker, 'drag', dragEndPoint);		
	}
	else
	{
		GEvent.addListener(marker, 'click', function(){return;} );		
	}
			
	map.addOverlay(marker);
}

function deleteLastPoint()
{
	if (drawMode == "")
		return;
		
	map.removeOverlay(polyShape);
	// pop last element of polypoint array
	coordArray.pop();
	drawCoordinates();
	drawMarker();
}

function toggleDragging()
{
	if ( map.draggingEnabled() )
	{
		disableDragging();
	}
	else
	{
		enableDragging();
	}
}

function disableDragging()
{
	map.disableDragging();		
}

function enableDragging()
{
	map.enableDragging();
}

function startDraw()
{
	disableDragging();	
	coordArray.length = 0;
	logCoordinates();
	document.getElementById('cancelDrawButton').style.visibility = 'visible';
	document.getElementById('clearMapButton').disabled = true;	
}

function drawPoint()
{
	startDraw();
	disableOtherDrawButtons('point');
	drawMode = "point";		
	document.getElementById('drawPointButton').className = 'activeDrawMode';
}

function drawLine()
{
	startDraw();
	disableOtherDrawButtons('line');
	drawMode = "line";		
	document.getElementById('finishDrawButton').style.visibility = 'visible';
	document.getElementById('deleteLastPointButton').style.visibility = 'visible';
	document.getElementById('deleteLastPointButton').disabled = true;	
	document.getElementById('drawLineButton').className = 'activeDrawMode';
	
	GEvent.addListener(map, 'dblclick', mapDoubleClick);
}

function drawPolygon()
{
	startDraw();
	disableOtherDrawButtons('polygon');
	drawMode = "polygon";		
	document.getElementById('finishDrawButton').style.visibility = 'visible';
	document.getElementById('deleteLastPointButton').style.visibility = 'visible';
	document.getElementById('deleteLastPointButton').disabled = true;
	document.getElementById('drawPolygonButton').className = 'activeDrawMode';
	GEvent.addListener(map, 'dblclick', mapDoubleClick);
	if ( typeof(polyShape) != 'undefined')
	{
		GEvent.addListener(polyShape, 'click', polyShapeClick);
	}
}

function polyShapeClick()
{
	alert('hi');
}

function disableOtherDrawButtons(drawType)
{
	if (drawType != 'point')
		document.getElementById('drawPointButton').disabled = true;

	if (drawType != 'line')
		document.getElementById('drawLineButton').disabled = true;

	if (drawType != 'polygon')
		document.getElementById('drawPolygonButton').disabled = true;
}

function enableAllDrawButtons()
{
	document.getElementById('drawPointButton').disabled = false;
	document.getElementById('drawLineButton').disabled = false;
	document.getElementById('drawPolygonButton').disabled = false;	
}

function endDraw()
{
	if (drawMode == "polygon")
		coordArray.push( coordArray[0] );

	if (drawMode == "polygon" || drawMode == "line")
		map.removeOverlay(marker); 	
	
	logCoordinates();
	drawCoordinates();		
	resetDraw();	
}

function cancelDraw()
{
	if (coordArray.length > 1)
	{
		map.removeOverlay(polyShape);
		map.removeOverlay(marker);
	}
	resetDraw();
}


function resetDraw()
{
	drawMode = "";
	enableAllDrawButtons();
	enableDragging();
	coordArray.length = 0;
	//logCoordinates();
	document.getElementById('drawPointButton').className = '';
	document.getElementById('drawLineButton').className = '';
	document.getElementById('drawPolygonButton').className = '';
	
	document.getElementById('deleteLastPointButton').style.visibility = 'hidden';
	document.getElementById('finishDrawButton').style.visibility = 'hidden';
	document.getElementById('cancelDrawButton').style.visibility = 'hidden';

	document.getElementById('clearMapButton').disabled = false;
}

function test()
{

}

function logCoordinates()
{
	var parsedCoords = coordArray.join('\n,');
	document.getElementById('coordinates').innerHTML = "<pre> " + parsedCoords + "</pre>";	
}

function updateMouseLatLng(latlng)
{	
	document.getElementById('mouseLat').innerHTML = padLatLng( latlng.lat() );
	document.getElementById('mouseLng').innerHTML = padLatLng( latlng.lng() );		
}

function clearMouseLatLng()
{	
	document.getElementById('mouseLat').innerHTML = "";
	document.getElementById('mouseLng').innerHTML = "";		
}

function padLatLng(input)
{
	var input = input.toString();
	var nonDecimal = input.split(".");
	var targetLen = 4;
	var padStr = " ";

	if ( nonDecimal[0].length >= targetLen)
	{
		return input;	
	}
	else
	{
		return Array(targetLen + 1 - nonDecimal[0].length).join(padStr) + input;
	}	
}

function clearMap()
{	
	map.clearOverlays();
	coordArray.length = 0;
	logCoordinates();	
}

function mapDoubleClick(overlay,point)
{	
}

function dragEndPoint()
{
	map.removeOverlay(polyShape);
	// pop last element of polypoint array
	coordArray.pop();
	coordArray.push( marker.getLatLng() );
	drawCoordinates();
	logCoordinates();
}

