//predefined trips123 coverage region
var tripsMinX = -79.500000;
var tripsMaxX = -71.500000;
var tripsMinY = 37.000000;
var tripsMaxY = 45.000000;

//store temporary x and y of user click - only save if user clicks submit
var storeMapX = null;
var storeMapY = null;

//define markers
var origMarker = null;
var destMarker = null;

//have the markers already been placed
var origIconPlaced;
var destIconPlaced;

var baseIcon = null;

var markerDragged = null;

//functions in this file
//checkTripsRegionBoundsForMarkers()
//checkTripsRegionBounds()
//displayMarkers()
//clickMap()
//plotPoint()
//positionAndShowMapChoice()
//hideMapChoice()
//populatePointName()
//renamePoint()
//checkTripsRegionBoundsForMarkers()
//clearVariables()

function checkTripsRegionBoundsForMarkers(passedPoint) {
	//called when user tries to place a marker - check to see if within region bounds
	checkBounds();
	
	//detect click on map and make sure point added is within coverage region
	if ((passedPoint.lng() >= tripsMinX) && (passedPoint.lng() <= tripsMaxX) && (passedPoint.lat() >= tripsMinY) && (passedPoint.lat() <= tripsMaxY)) {   
		return true;
	}
	else {
		return false;
	}
}

function checkTripsRegionBounds(){
//called when user tries to pan on map - check to see if within region bounds	
			
    var mapZoomLevel = googleMap.getZoom(); 
	
	if ((maxx < tripsMinX) || (maxx > tripsMaxX)|| (miny < tripsMinY) || (miny > tripsMaxY)) {
        //Detect pan on map - alert user if they have panned outside the region
		//zoom level is set to 9 because when zoomed far out we do not need to alert the user
	    if (mapZoomLevel > 9) {
	        alert("You have panned outside of the Trips123 coverage area.");
	    }
	}
}

function displayMarkers() {
	//if markers have been plotted already, display them on the map. 
	if ((document.main.fromLatCoord.value != "") && (document.main.fromLongCoord.value != "")) {
	    //place origin pushpin on map
	    baseIcon.image = "/images/trip_planner/startflag.png";
        point = new GLatLng(document.main.fromLatCoord.value, document.main.fromLongCoord.value);
        origMarker = new PdMarker(point, {icon: baseIcon, draggable: true});
        origMarker.setId("orig");
        googleMap.addOverlay(origMarker);
        
        //marker dragging functionality		
		GEvent.addListener(origMarker, "dragend", function() {
			document.main.fromLongCoord.value = origMarker.getPoint().lng();
			document.main.fromLatCoord.value = origMarker.getPoint().lat();
			positionAndShowMapChoice('mapRename');
			markerDragged = "orig";
			clearVariables('start');
		});
    }
		
	if ((document.main.toLatCoord.value != "") && (document.main.toLongCoord.value != "")) {
	    //place destination push pin on map
	    baseIcon.image = "/images/trip_planner/endflag.png";
	    point = new GLatLng(document.main.toLatCoord.value, document.main.toLongCoord.value);
	    destMarker = new PdMarker(point, {icon: baseIcon, draggable: true});
	    destMarker.setId("dest");
	    googleMap.addOverlay(destMarker);	
	    
	    //marker dragging functionality		
		GEvent.addListener(destMarker, "dragend", function() {
			document.main.toLongCoord.value = destMarker.getPoint().lng();
			document.main.toLatCoord.value = destMarker.getPoint().lat();
			positionAndShowMapChoice('mapRename');
			markerDragged = "dest"
			clearVariables('end');
		});
	}
} //end function displayMarkers


function clickMap() {
//add functionality to move place, move, and remove markers on map

    GEvent.addListener(googleMap, 'click', function(overlay, point) {
    
		if (overlay) {
		//user clicked existing pushpin to remove from map
			
			var tempTarget = overlay.getId();
			
			//remove marker from map - user clicked on the existing marker
			googleMap.removeOverlay(overlay);
	        
	        //clear any variables related to the marker.
			if (tempTarget == "orig") {
				document.main.fromLongCoord.value = "";
				document.main.fromLatCoord.value = "";
				document.main.fromgeox.value = "";
				document.main.fromgeoy.value = "";
				document.main.startpoint.value = "";
				origMarker = null; 
				origIconPlaced = "false";
			}
			else {
				document.main.toLongCoord.value = "";
				document.main.toLatCoord.value = "";
				document.main.togeoy.value = "";
				document.main.togeoy.value = "";
				document.main.endpoint.value = "";
				destMarker = null;
				destIconPlaced = "false";
			}

			storeMapX = null;
			storeMapY = null;
		}
	
		else if (point) {
			//else we plot the point on the map and place the pushpin
			//depending on whether it is an origin or destination, place appropriate marker
			//and fill variables
			//also, if marker is already placed, move it to new location as desired by user
	        
			//show mapChoice div
			storeMapX = parseFloat(point.lng());
            storeMapY = parseFloat(point.lat());
			
			//check if point clicked is 
			//within trips123 coverage region - return true if within bounds, false if not.
			var isPointWithinBounds = checkTripsRegionBoundsForMarkers(point);
		    
			//alert("isPointWithinBounds: " + isPointWithinBounds);
		    
			if (isPointWithinBounds) {
				positionAndShowMapChoice('mapChoice');
            }
		    else {
				//point is not within bounds of coverage region
				var targetValue = document.main.target.value;
				if (targetValue == "orig") {
					targetValue = "a starting";
				}
				else {
					targetValue = "an ending";
				}
		        
				alert("You have chosen " + targetValue + " point that is not within the Trips123 coverage region.\nPlease choose " + targetValue + " point that is within the covered region."); 
		    }//end if within bounds
       }//end if point
    });//end GEvent
} //end function clickMap

function plotPoint() {
    //user clicked on Plot Point button - now store values whether origin or destination
    //made sure that the point chosen is within the trips123 coverage region
	        
	var tempTarget = "";
	        
	//get target value as selected by user - loop over radio buttons	
	for (var i=0; i < document.main.target.length; i++) {
		if (document.main.target[i].checked) {
			tempTarget = document.main.target[i].value;
		}
	}        
	
	//GLog.write("origMarker: " + origMarker + " , destMarker: " + destMarker + ", tempTarget: " + tempTarget);
	
	if (tempTarget.length != 0) {
	    //user selected origin or destination radio button
		//GLog.write("storeMapX: " + storeMapX + ", storeMapY: " + storeMapY);
		
		var tmpPoint = new GLatLng(parseFloat(storeMapY), parseFloat(storeMapX));

		//storeMapX and Y are coordinates of the mousepointer
		//on map click we store this x and y in form variables
		//depending on whether user wants to save as origin or destination.
		//if the marker already exists, we just move the marker to the new location
		if (tempTarget == "orig") {
			//origin marker does not exist, plot on map
			if (!origMarker) {
				baseIcon.image = "/images/trip_planner/startflag.png";
				origMarker = new PdMarker(tmpPoint, {icon: baseIcon, draggable: true});
				origMarker.setId("orig");
				googleMap.addOverlay(origMarker);
			}
			else {
				//move original marker somewhere else
				baseIcon.image = "/images/trip_planner/startflag.png";
				googleMap.removeOverlay(origMarker);
				origMarker = new PdMarker(tmpPoint, {icon: baseIcon, draggable: true});
				origMarker.setId("orig");
				googleMap.addOverlay(origMarker);
			}
					
			//marker dragging functionality		
			GEvent.addListener(origMarker, "dragend", function() {
			    document.main.fromLongCoord.value = origMarker.getPoint().lng();
			    document.main.fromLatCoord.value = origMarker.getPoint().lat();
			    positionAndShowMapChoice('mapRename');
			    markerDragged = "orig";
			});
					
			document.main.fromLongCoord.value = storeMapX;
			document.main.fromLatCoord.value = storeMapY;
			clearVariables('start');
			origIconPlaced = "true";
		}
		else {
			if (!destMarker) {
				//destination does not exist, plot on map
				baseIcon.image = "/images/trip_planner/endflag.png";
				destMarker = new PdMarker(tmpPoint, {icon: baseIcon, draggable: true});
				destMarker.setId("dest");
				googleMap.addOverlay(destMarker);
			}
			else {
				//move destination marker somewhere else
				baseIcon.image = "/images/trip_planner/endflag.png";
				googleMap.removeOverlay(destMarker);
				destMarker = new PdMarker(tmpPoint, {icon: baseIcon, draggable: true});
				destMarker.setId("dest");
				googleMap.addOverlay(destMarker);
			}
			
			//marker dragging functionality		
			GEvent.addListener(destMarker, "dragend", function() {
			    document.main.toLongCoord.value = destMarker.getPoint().lng();
			    document.main.toLatCoord.value = destMarker.getPoint().lat();
			    positionAndShowMapChoice('mapRename');
			    markerDragged = "dest";
			});
			
			document.main.toLongCoord.value = storeMapX;
			document.main.toLatCoord.value = storeMapY;
			clearVariables('end');
			destIconPlaced = "true";
		}
		
		//add point name to either start or end based on user input
		populatePointName(tempTarget, 'pointName');
		//hide map choice window
		hideMapChoice('mapChoice');
		
		//clear globals for next use
		storeMapX = null;
		storeMapY = null;
		tmpPoint = null;
		tempTarget = "";
	}
	else {
	    //user did not select origin or destination radio
	    alert("Please select either origin or destination for your new location.");
	    return false;    
	}
	
	
}

function renamePoint() {
   //change name in startpoint or endpoint box
   populatePointName(markerDragged, 'pointRename');
   
   if (document.main.pointRename.value != "") {
       //user must rename point if they click the rename button
       hideMapChoice('mapRename')
       markerDragged = null;
   }
   else {
       alert("Please enter a new name for your point or click cancel to close");
       document.main.pointRename.focus();
       return false;
   }
}

function positionAndShowMapChoice(newDiv){
    //user clicked on map. position and display map choice window
    var mapChoice = document.getElementById(newDiv); //map choice element
    var tmpMap = document.getElementById('map'); //map element
    
    //get map x,y first to display map choice dialog properly, use findPos function
    var xPos = findPosX(new getObj('map'));
	var yPos = findPosY(new getObj('map'));
    
    //get width of mapChoice element
    var mapChoiceWidth = mapChoice.clientWidth;
    var mapChoiceHeight = mapChoice.clientHeight;
    //width of map element
    var mapWidth = tmpMap.clientWidth;
    var mapHeight = tmpMap.clientHeight;
    
    //center mapChoice div over map - calculate half way points of map and map choice and center around
    //mid x and mid y of map
    var halfMapX = mapWidth*.5;
    var halfMapY = mapHeight*.5;
    
    var halfMapChoiceX = mapChoiceWidth*.5;
    var halfMapChoiceY = mapChoiceHeight*.5;
    
    mapChoice.style.left = xPos + halfMapX - halfMapChoiceX + "px";
    mapChoice.style.top = yPos + halfMapY - halfMapChoiceY + "px";
    
    document.main.target.value = "";
    //show div
    mapChoice.style.visibility = "visible";
    
}

function populatePointName(tempTarget, inputBox){
    //populate start or end point from user selection with either user selected name or 
    //start point from map - use asterisk to denote selected from map
    var pointName = document.main.elements[inputBox].value;
    
    if (tempTarget == "orig") {
        if (pointName == "") {
		    document.main.startpoint.value = "*Start Point From Map";
		}
		else {
            document.main.startpoint.value = '*' + pointName;
		}
		clearVariables('start');
	}
	else if (tempTarget == "dest") {
	    if (pointName == "") {
		    document.main.endpoint.value = "*End Point From Map";
		}
		else { 
		    document.main.endpoint.value = '*' + pointName;
		} 
		document.main.endcity.value = "";
		document.main.endzip.value = "";
	}
}

function hideMapChoice(newDiv){
    var mapChoice = document.getElementById(newDiv); //map choice element
    mapChoice.style.visibility = "hidden";
    
    //clear point name text box
    document.main.pointName.value = "";
    document.main.pointRename.value = "";
    
    //clear target selection
    for (var i=0; i < document.main.target.length; i++) {
		document.main.target[i].checked = false;
	} 
	
    //need to add "Cancel without saving?"
    //clear stored map click, user did not save
    storeMapX = null;
    storeMapY = null;
}

function clearVariables(pointType) {
    //clear out variables
    document.main.elements[pointType + 'city'].value = "";
	document.main.elements[pointType + 'zip'].value = "";
	document.main.elements[pointType + 'state'].options[0].selected = "true";
	
}
