//<![CDATA[

var map;
var polyShape;
var drawMode;
var mode;
var polygonDepth = "20";
var GPoints = [];
var marker;
var itemPoints = []; // the array where all data will be enter from the frontend
var gmarkers = [];
var GMStretched = false;

var fillColor = "#0000FF"; // blue fill
var lineColor = "#000000"; // black line
var opacity = .3;
var lineWeight = 2;

var kmlFillColor = "7dff0000"; // half-opaque blue fill

function load(mode) {
  if (GBrowserIsCompatible()) {
	//map = new GMap2(document.getElementById("map"),{draggableCursor:'url(../images/mouse_draggable_pointer.png) 11 11 ,crosshair', draggingCursor: 'pointer'});
	map = new GMap2(document.getElementById("map"));
	map.setCenter(new GLatLng(43.078556,25.627157), 15);
	//map.addControl(new GLargeMapControl());
	map.addControl(new GSmallMapControl());
	//map.setMapType(G_HYBRID_MAP);
	
	if (this.mode = 'cms'){
		mode = 'cms';
		GEvent.addListener(map, 'click', mapClick);
	} else {addMarkersGroup()}
	
	}
}

// mapClick - Handles the event of a user clicking anywhere on the map
// Adds a new point to the map and draws either a new line from the last point
// or a new polygon section depending on the drawing mode.
function mapClick(marker, clickedPoint) {
	switch (drawMode){
		case 'marker':
			map.clearOverlays();
			// convert from polygon to polyline to able to add poin inside the poly area
			if (document.getElementById('polygon_points_area').value != ''){
				recreatePolyline(document.getElementById('polygon_points_area').value)
			}
			toggleDrawMode('marker');
			drawCoordinates(clickedPoint);
			DrawModeOff();
		break;	
		case 'polyline':
			map.clearOverlays();
			if (document.getElementById('latbox').value != ''){
				var point = new GLatLng(document.getElementById("latbox").value,document.getElementById("lonbox").value);
				toggleDrawMode('marker');
				drawCoordinates(point);
				toggleDrawMode('polyline');
			}
			GPoints.push(clickedPoint);
			drawCoordinates();
		break;
		case 'polygon':
			map.clearOverlays();
			if (document.getElementById('latbox').value != ''){
				var point = new GLatLng(document.getElementById("latbox").value,document.getElementById("lonbox").value);
				toggleDrawMode('marker');
				drawCoordinates(point);
				toggleDrawMode('polygon');
			}
			GPoints.push(clickedPoint);
			drawCoordinates();
		break;
	}
 }

// Toggle from Polygon PolyLine mode
function toggleDrawMode(mode){
	drawMode = mode;
}

// Turn Drawing Mode off
function DrawModeOff(){
	toggleDrawMode('off');
	polyShape = null;
	GPoints = [];
}

// Close polygon
function closePolygon() {
	map.clearOverlays();
	if (GPoints.length > 2){
		// check if there has already been added a point and add it if there hasn't
		if (document.getElementById('latbox').value != ''){
			// GLatLng converts from strings to Google Map geographic cooirdinates
			var point = new GLatLng(document.getElementById("latbox").value,document.getElementById("lonbox").value);
			toggleDrawMode('marker');
			drawCoordinates(point);
		}
		// add the first point of the GPoints array as a last element in order to close the polygon
		GPoints.push(GPoints[0]);
		toggleDrawMode('polygon');
		drawCoordinates();
		// add all the coordinates to the text area
		document.getElementById('polygon_points_area').value ='';
		for (var i = 0; i<GPoints.length; i++) {
			var lat = GPoints[i].lat();
			var longi = GPoints[i].lng();
			document.getElementById('polygon_points_area').value += longi + "," + lat;
			if (i < GPoints.length -1){document.getElementById('polygon_points_area').value += ":"}
		}
		// if there hasn't been added a marker so far it adds the center of the points area otherwise leave the previos marker coordinates
		if (document.getElementById('latbox').value == ''){
			document.getElementById("latbox").value=getBoundsCenter(GPoints).y;
			document.getElementById("lonbox").value=getBoundsCenter(GPoints).x;
		}
		DrawModeOff();
	} else {alert('You need at least 3 points on the map!')}
}


// recreate polygon
function recreatePolygon(str){
	toggleDrawMode('polygonRecreation');
	GPoints = str.split(':');
	for (i=0; i<GPoints.length; i++){
		temp = GPoints[i].split(',');
		point = new GLatLng(temp[1],temp[0],true);
		GPoints[i] = point;
	}
	drawCoordinates();
	if (mode != 'cms'){
		setZoomLevel(GPoints);
		setMapCenter(GPoints);
		}
}

// recreate polyline
function recreatePolyline(str){
	toggleDrawMode('polylineRecreation');
	GPoints = str.split(':');
	for (i=0; i<GPoints.length; i++){
		temp = GPoints[i].split(',');
		// GLatLng converts from strings to Google Map geographic cooirdinates
		point = new GLatLng(temp[1],temp[0],true);
		GPoints[i] = point;
	}
	drawCoordinates();
	if (mode != 'cms'){
		setZoomLevel(GPoints);
		setMapCenter(GPoints);
		}
}

// get Bounds ZoomLevel
function getZoomBoundsLevel(pointsArray) {
	var bounds = new GLatLngBounds();
	for(i=0; i < pointsArray.length; i++){
		bounds.extend(pointsArray[i]);
		}
	return map.getBoundsZoomLevel(bounds);
}

// get Bounds Center
function getBoundsCenter(pointsArray) {
	var bounds = new GLatLngBounds();
	for(i=0; i < pointsArray.length; i++){
		bounds.extend(pointsArray[i]);
		}
	return bounds.getCenter();
}

// get zoom level around a cluster of points. Calculates the level of zoom that all the points fit into it.
function setZoomLevel(pointsArray){
	map.setZoom(getZoomBoundsLevel(pointsArray) - 1);
}

// gat the center of a cluster of points. Calculates the center of the points area.
function setMapCenter(pointsArray){
	map.setCenter(getBoundsCenter(pointsArray));
}

// Clear current Map
function clearMap(){
	map.clearOverlays();
	GPoints = [];
	document.getElementById('polygon_points_area').value = '';
	document.getElementById('latbox').value = '';
	document.getElementById("lonbox").value = '';
}



// Delete last Point
// This function removes the last point from the Polyline/Polygon and redraws
// map.

function deleteLastPoint(){
  map.removeOverlay(polyShape);

  // pop last element of polypoint array
  GPoints.pop();
  drawCoordinates();
 }

// drawCoordinates
function drawCoordinates(clickedPoint){
	
	// custom icon for polygon, polyline dragable point
	var icon = new GIcon();
	icon.image = "../images/polygon_point.png";
	//icon.shadow = "http://www.google.com/mapfiles/turkeyshadow.png";
	icon.iconSize = new GSize(10, 10);
	//icon.shadowSize = new GSize(91, 62);
	icon.iconAnchor = new GPoint(5, 5);
	icon.infoWindowAnchor = new GPoint(5, 5);
	
	switch (drawMode){
		case 'marker':
			var marker = new GMarker(clickedPoint);
			map.addOverlay(marker);
			document.getElementById("latbox").value=clickedPoint.y;
			document.getElementById("lonbox").value=clickedPoint.x;
		break;
		case 'polyline':
			polyShape = new GPolyline(GPoints,lineColor,lineWeight,opacity);
			/* Grab last point of GPoints to add marker */
			marker = new GMarker(GPoints[GPoints.length -1], icon); /* REMOVE ICON attr to not use custom marker */
			for(i=0; i<GPoints.length;i++){
				marker = new GMarker(GPoints[i], icon); /* REMOVE ICON attr to not use custom marker */
				map.addOverlay(marker);
			}
			if (GPoints.length > 1){map.addOverlay(polyShape)}
		break;
		case 'polygon':
			polyShape = new GPolygon(GPoints,lineColor,lineWeight,opacity,fillColor,opacity);
			/* Grab last point of GPoints to add marker */
			for(i=0; i<GPoints.length;i++){
				marker = new GMarker(GPoints[i], icon); /* REMOVE ICON attr to not use custom marker */
				map.addOverlay(marker);
			}
			if (GPoints.length > 1){map.addOverlay(polyShape)}
		break;
		case 'polygonRecreation':
			polyShape = new GPolygon(GPoints,lineColor,lineWeight,opacity,fillColor,opacity);
			map.addOverlay(polyShape);
		break;
		case 'polylineRecreation':
			polyShape = new GPolyline(GPoints,lineColor,lineWeight,opacity);
			map.addOverlay(polyShape);
		break;
	}
}


// draw polygon and/or marker if exist
function drawPolygonMarker(){
	map.clearOverlays();
	if (document.getElementById('polygon_points_area').value != ''){
		recreatePolyline(document.getElementById('polygon_points_area').value);
		setZoomLevel(GPoints);
		setMapCenter(GPoints);
	}
	if (document.getElementById('latbox').value != ''){
		var point = new GLatLng(document.getElementById("latbox").value,document.getElementById("lonbox").value);
		toggleDrawMode('marker');
		drawCoordinates(point);
		toggleDrawMode('polygon');
		drawCoordinates();
		setZoomLevel(GPoints);
		setMapCenter(GPoints);
	}
}


// onLoad CMS event
function onCMSLoad() {
	drawPolygonMarker();
	DrawModeOff();
}


// add a new element to the item array from the frontend
// like this: addNewItem('37.4385429144958:::-122.1925163269043:::<b>Property ID: 1234567</b><br><img src="pics/03_brenda_100658.jpg" width="200" border="1" />');

function addNewItem(value){
	var ifCoordinate = value.split('{|}');
	if (ifCoordinate[1] != ''){
		itemPoints.push(value)
	}
}

// add marker with html info
function addInfoMarker(arrayValue){
	var points = arrayValue.split('{|}');
	var point = new GLatLng(points[1],points[2]);
	var marker = new GMarker(point);
	map.addOverlay(marker);
	var message = points[3];
	marker.bindInfoWindowHtml(message,{maxWidth:100});
	gmarkers[points[0]] = marker;
}

// read all theelements from propertyPoints Array
function addMarkersGroup(){
	for (i=0; i<itemPoints.length; i++){
		addInfoMarker(itemPoints[i]);
		var points = itemPoints[i].split('{|}');
		var point = new GLatLng(points[1],points[2]);
		itemPoints[i] = point;
	}
	//setZoomLevel(itemPoints);
	setMapCenter(itemPoints);
}

var previousMarkerNum;
// open marker InfoWindow
function openMarkerInfoWindow(markerNum){
	if (markerNum != previousMarkerNum){
		if (gmarkers[markerNum] != undefined){
			GEvent.trigger(gmarkers[markerNum], "click");
		} else {map.closeInfoWindow()}
	}
	previousMarkerNum = markerNum;
}

resizeGoogleMap = function(){
	if (!GMStretched){
		document.getElementById('items_container').style.display = 'none';
		document.getElementById('map').style.width = '799';
		document.getElementById('stretchGM').value = 'Stretch Map '+String.fromCharCode(9668);
		GMStretched = true;
		} else {
		document.getElementById('items_container').style.display = 'block';
		document.getElementById('map').style.width = '400';
		document.getElementById('stretchGM').value = 'Stretch Map '+String.fromCharCode(9658);
		GMStretched = false;
		}
}
//]]>
