/*
 * Created on July 12, 2005
 *
 * Main javascript file for CTI Google Maps Interface.
 * 
 *
 */
 
var geocoder = null;
var map; 
var bDoubleClickHappened = false;
var startMarker;
var xArray = new Array(0);
var yArray = new Array(0);
var locationArray = new Array(0);
var legArray = new Array(0);
var pointArray = new Array(0);
var gPointArray = new Array(0);
var selectedProperty = new Array(0); //{mlsnum, lat, long}
var listingMarkers = new Array(0);
var landMarkers = new Array(0);
var localeMarkers = new Array(0);
var mainMarker;//Main location marker that will always be "selected"
var mainMarkerBubbleHtml;
var loadingDiv; //This is set in loadControl.js

/*
 * This array will hold information
 * on the listings that are selected by the user
 */
var selectedListingMarkers = new Array(0); 										   

/*
 * This is the outline a user is allowed to draw on the 
 * map to query properties by lat/lng.
 */										   
var outlinePolyline = new Array(0); 

/*
 * The outline array the user draws on the map
 */						
var routePolyline;
var bRecordPoints = false;
var bIsIE;
var statusMessage = document.getElementById("message");

//Initialize the navigation engine	
if (navigator.appName == 'Microsoft Internet Explorer'){

	document.ondblclick = handleDblClick;
	bIsIE = true;
	
} else {

	window.ondblclick = handleDblClick;
	bIsIE = false;
	
}

/*
 * Initializes map.  This should be called in the
 * <body> tag. 
 *
 * ie. <body onload="initializeMap();">
 *
 */
function initializeMap(){

	//initialize the map
	map = new GMap2(document.getElementById("map"));
	geocoder = new GClientGeocoder();
	
	if(!arguments[0])
	{	
		map.setCenter(new GLatLng(42.068078, -75.3249191), 7, G_NORMAL_MAP);
		//map.centerAndZoom(new GPoint(-75.751286, 43.068078),6);
		//alert("Your address was not found.  Please try again");
		plot_locale = false;
	}
	else
	{
		map.setCenter(new GLatLng(arguments[0], arguments[1]), 7, G_NORMAL_MAP);
		plot_locale = true;
			//if parameters have been passed in to prepop location and route, parse them and display correct values
		rehydrateMapFromUrl(arguments[0], arguments[1]);
	}
		
	map.addControl(new GLargeMapControl());
	map.addControl(new GMapTypeControl());
	map.addControl(new GScaleControl());
	map.addControl(new GOverviewMapControl());
	//map.addControl(new LoadingControl());
	 
	GEvent.addListener(map, "moveend", function() {
		if (bDoubleClickHappened){
			if(bRecordPoints)
			{
				addLeg(map.getCenterLatLng().x, map.getCenterLatLng().y);
				drawPolyLine(gPointArray);
			}
    
		} 
	
		bDoubleClickHappened = false;
    
	});

	if(plot_locale == true)
	{
		//var marker = new GMarker(new GPoint(arguments[1], arguments[0]), icon);
		info = new Array(arguments[0], arguments[1], arguments[2]);
		//var mainMarker = new ctMarker(new GPoint(arguments[1], arguments[0]), info);
		mainMarker = new LocationMarker(new GLatLng(arguments[0], arguments[1]), info);
		
		locale_address = arguments[2];
		//Event listener for clicking on the listing marker on the map
		GEvent.addListener(mainMarker, "click", function() {
			//map.removeOverlay(marker);
			//var land_html = view_diagram + getLandHTML(info);
			
			mainMarker.openInfoWindowHtml(locale_address);
		});
	}


	//getMarkerHtml("Hey");
	requestListings();
	refreshMenu(true);
	document.getElementById("loading").style.display = "none";
}

/*
 * Double click handler
 */	
function handleDblClick(e) {
	bDoubleClickHappened = true;	
}

/*
 * Puts new lat/long coordinates into their
 * associated arrays.
 *
 * @param xCoord   
 * @param yCoord   
 */	
function addLeg(xCoord, yCoord) {
		
	if (bRecordPoints) { 
		xArray.push(xCoord);
		yArray.push(yCoord);
		pointArray.push(xCoord + ',' + yCoord);
		gPointArray.push(new GPoint(xCoord, yCoord));
		
		//updateDistances(xArray, yArray, ADD);
	}
}

/*
 * Returns distance between two points.
 *
 * @param point1y      
 * @param point1x   
 * @param point2y   
 * @param point2x   
 *
 */
function returnDistanceInMiles(point1y, point1x, point2y, point2x) {
	var a =(3963.0 * Math.acos(Math.sin(point1y/57.2958) * Math.sin(point2y/57.2958) + Math.cos(point1y/57.2958) * Math.cos(point2y/57.2958) *  Math.cos((point2x/57.2958) - (point1x/57.2958))));
	//alert(a);
	return a;
}


/*
 * Initializes the string array
 *
 * @param nameOfParameter     name 
 * @param defaultValue		  value of parameter
 */
function initializeParameter(nameOfParameter, defaultValue){

	var returnVal = '';
	var qstringVal = getQuerystringParameter(nameOfParameter);

	if (qstringVal.length > 0) {
	
		returnVal = qstringVal;
		
	} else {
	
		returnVal = defaultValue;

	}
	
	return returnVal;	
}

/*
 * Refreshes map interface.
 */
function rehydrateMapFromUrl(lng, lat) {

	//recenter and zoom...
//	var lng = -75.3456115722656;
//	var lat =  43.1360676395563;
	var curCenterX = parseFloat(initializeParameter('centerX', lng));
	var curCenterY = parseFloat(initializeParameter('centerY', lat));
	
	var zoomLevel = parseInt(initializeParameter('zl',2));

	map.setCenter(new GLatLng(curCenterX, curCenterY), 9);				
}

/*
 * Removes the last polyline drawn by the user.
 */	
function removeLastLeg() {

	if (xArray.length > 0) {
		
		xArray.pop();
		yArray.pop();			
		pointArray.pop();
		gPointArray.pop();
		
		drawPolyLine(gPointArray);

	} else {

		alert('No points to remove');

	}	
}

/*
 * Returns parameters given in the address bar.
 *
 * @param paramName     name of the parameter to fetch
 */
function getQuerystringParameter(paramName){

	var sReturnStr = '';
	
	var queryStringObj = new String(location.href)
	var paramNameObj = new String(paramName+'=');
	//queryStringObj = queryStringObj.toLowerCase();
	paramNameObj = paramNameObj.toLowerCase();
		
	//parameters were sent
	if (queryStringObj.indexOf('?') > -1) {
		
		var qStringArray = queryStringObj.split('?');

		if (qStringArray[1].length > 0) {
	
			var allParams = qStringArray[1]
			var paramArray = allParams.split("&");
	
			for (i=0; i<= paramArray.length-1; i++){
				
				var origCaseFullParam = paramArray[i];
				var lcaseFullParam = paramArray[i].toLowerCase();

				if (lcaseFullParam.indexOf(paramNameObj) > -1)
				
					sReturnStr =  unescape(origCaseFullParam.substr(paramNameObj.length));
				
			}		
		}	
	}
	
	return sReturnStr;

}

/*
 * This function draws each line as the user
 * double clicks on the map.  The example below will
 * allows the user to double click 3 times, essentially
 * drawing a rectangle.
 *
 * @param gPointArray     global array that stores the lat/long
 *						  coordinates that should be drawn
 *
 */
function drawPolyLine(gPointArray){
	map.removeOverlay(routePolyline);
    
	//this function may be called from removeLastLeg, in which case 
	//we still want to clear points (above) but don't want to draw a new one.
	if (gPointArray.length > 0) {
		
		//start
		if(gPointArray.length == 1)
		{
  			startMarker = new GMarker(gPointArray[0]);
  			map.addOverlay(startMarker);
			statusMessage.innerHTML = "Now that you have a starting point, double click on the map again to draw a line";

  		}
  		else
  		{
  			statusMessage.innerHTML = "Continue double clicking on the map until you have drawn a rectangle";
		  	map.removeOverlay(startMarker);
		}
  			
  			//document.getElementById("message").innerHTML = gPointArray;
	
		//Turn the polyline into a complete parallellogram here
		if(gPointArray.length == 4)
		{
			//alert(gPointArray[0]);
			gPointArray.push(gPointArray[0]);
			drawPolyLine(gPointArray);
			stopDrawing();
			
			//alert(xArray);
		}
		else
		{
			routePolyline = new GPolyline(gPointArray);
			map.addOverlay(routePolyline);	
		}
		

	}

}

/*
 * This event is called when the user has completed
 * drawing an outline.  An outline around the user
 * generated rectangle is then drawn.
 *
 */
function stopDrawing()
{
	statusMessage.innerHTML = "Congratulations!  Your outline is complete.  All locations inside the rectangle are shown";
	plotOutline(xArray, yArray, gPointArray);
	bRecordPoints=false;
}

/*
 * Draw polylines on the map by parsing a string
 * array.  This will usually be called using an
 * external file or database entry that contains 
 * coordinates in this way.
 *
 * ie. "(-75.2808952331543, 43.07628618331304),(-75.27231216430664, 43.07089421067248)"
 *     This is an array containing 2 points.  This is what is passed
 *	   into the "polyArray" argument.
 *
 *
 * @param polyArray     string representation of an array
 * @param zoom  		zoom level after the polylines are drawn
 * @param color			color of the polylines
 */
function drawPolylines(polyArray, zoom, color)
{
	//document.getElementById("message").innerHTML = gPointArray;

	var tokenArray = polyArray.split("),(");
	var polyPointArray = new Array(0);
	var lastLat;
	var lastLng;
	
	for(var i=0; i<tokenArray.length; i++)
	{
		//alert(tokenArray[i]);
		tokenArray[i] = tokenArray[i].replace("(", "");
		tokenArray[i] = tokenArray[i].replace(")", "");
		var coordinates = tokenArray[i].split(",");

		//createPropertyMarker(new GPoint(-75.184349, 43.090206));

		if(i==0)
		{
			map.setCenter(new GLatLng(coordinates[0], coordinates[1]), zoom);
		}	
		else
		{
				
			var polyline = new GPolyline([new GPoint(lastLat, lastLng),
                         new GPoint(coordinates[0], coordinates[1])],
                          color, 3);
			map.addOverlay(polyline);
		}		
		
					
		lastLat = coordinates[0];
		lastLng = coordinates[1];
		polyPointArray.push(new GPoint(coordinates[0], coordinates[1]));
	}		
}

/*
 * Starts the drawing mode.  A user can double click
 * on the map, each time they will create a line 
 * connecting their current click pixel to the previous
 * one.
 *
 * 
 *
 *
 */
function startDrawingOutline()
{	
	if(!bRecordPoints)
	{
		if(confirm("Drawing an outline will remove everything from the map.  Do you want to continue?"))
		{
			map.clearOverlays();
			clearSelectionMarkers(true);
			refreshMenu();
			
			map.removeOverlay(outlinePolyline);
			gPointArray = new Array(0);
			xArray = new Array(0);
			yArray = new Array(0);
			bRecordPoints=true;
			statusMessage.innerHTML='To start the outline, double click on the map where you would like to begin.';
		}
		//btn.style.display = 'none';
	}
	else
	{
		alert("Already drawing.  Double click on the map to continue drawing.");
	}
}

/*
 * Resets the polyline array to null, then redraws
 * this line.  Essentially, deleting the polyline from
 * the map.
 *
 */	
function deletePolyline()
{
		gPointArray = new Array(0);
		xArray = new Array(0);
		yArray = new Array(0);
		drawPolyLine(gPointArray);
}

/*
 * Refreshes the "selection menu"
 */
function refreshMenu()
{
	//document.getElementById("menu").src = "/website/power_lines/menu/menu.php?numListings=" + selectedProperty.length;	
}


/**
 * Run an HTTP request to get the HTML for the bubble
 
 */
function getMarkerHtml(addr){
	var request = GXmlHttp.create();
	request.open("GET", "/website/power_lines/getLocationMarkerHtml.php?address="+addr, true);

	request.onreadystatechange = function() {
	  if (request.readyState == 4) {
	  	//alert(request.responseText);
	  	mainMarkerBubbleHtml = request.responseText;
	  }
	}

	request.send(null);	
}