//
// View Challenge functions

// Init 'global' vars
//
var mainMap = new MegosiMap(); // Map object
//Initialize the GeoCoder for Address lookup
var geocoder = new GClientGeocoder();

//
// When page is done loading, add the Google map
//
$(document).ready( function() {

	//Show a boxy window with the loading indicator when ajax requests fire
	$().ajaxStart(function(){
		var loading = new Boxy("<div id='loading'><h3>Loading</h3></div>",{
			closeable:false,
			draggable:false,
			center:true,
			modal:true,
			unloadOnHide:true
		});
		// We want the modality, but not the blackout, so we make the blackout div see-thru
		$(".boxy-modal-blackout").css("opacity","0");
	});


	// Hide the loading indicator
	$().ajaxStop(function(){
			Boxy.get("#loading").hide();
			// Put the blackout div opacity back to normal just to be safe.
			$(".boxy-modal-blackout").css("opacity","0.1");
	});		
	
	// Initialize Google Map
	mainMap.initMap( "wpMap" );
	mainMap.map.addControl( new GSmallZoomControl() );
	mainMap.map.addControl( new GMapTypeControl() );

	// Store all the Google Map Overlays in an array so they can be dynamically enabled/disabled
	var kmlPtArray = [];
	var type = $("#ways").attr("challengetype");
	
	// --------------------------------------------------------
	// Set up event calls here
    //

	// To handle events in the waypoint list (and draw waypoints in the map)
	$("#ways tr").each(
		function(){
			var waypointId = $(this).attr("waypoint");
			var latlon = $("#address_" + waypointId).html();
			
//			// Add addresses to table of waypoints
//			geocoder.getLocations( new GLatLng( latlon.split(" ")[0], latlon.split(" ")[1] ), 
//				function( response ) {
//				    if ( response && 
//					     response.Placemark[0] && 
//					     response.Placemark[0].address && 
//					     response.Placemark[0].AddressDetails &&
//					     response.Placemark[0].AddressDetails.Country &&
//					     response.Placemark[0].AddressDetails.Country.AdministrativeArea &&
//					     response.Placemark[0].AddressDetails.Country.AdministrativeArea.Locality && 
//					     response.Placemark[0].AddressDetails.Country.AdministrativeArea.Locality.LocalityName) {
//				   		$("#address_" + waypointId ).html( "Near " + response.Placemark[0].AddressDetails.Country.AdministrativeArea.Locality.LocalityName);
//				    	$("#address_" + waypointId ).toggle();
//				    }
//				}
//			);
			
			//Add button events:
			$(".map", this).click(
				function(){
					loadAdvancedMenu( waypointId );
					return false;
				}
			);
		
			// Event for 'highlight' button
			$("td.title,td.bullet", this).click(
				function(){
					toggleRows( waypointId, kmlPtArray );
				}
			);
		
			// Make the titles in the waypoint list act like links.
			// I am sorry for this hack.
			$("td.title,td.bullet", this).hover(
				function () {
					$(this).css({'cursor' : 'pointer'});
				}, 
				function () {
					$(this).css({'cursor' : ''});
				}
			);
		
			// Add 2 KML images for each point, an 'off' image and an 'on' image
			// ALSO... if this is the only point on the map.. zoom to it!
			if ( $("#ways tr").length == 1 ) {
				kmlPtArray[ waypointId + "off" ] = mainMap.loadKMLPoint( mainMap, waypointId, "off", true, 12 );
			} else {
				kmlPtArray[ waypointId + "off" ] = mainMap.loadKMLPoint( mainMap, waypointId, "off", false );
			}
			kmlPtArray[ waypointId + "on"  ] = mainMap.loadKMLPoint( mainMap, waypointId, "on", false );
		}
	);	
	// --------------------------------------------------------
	
	// Load Challenge object (be it line or polygon)
	var challengeId = $("#challengeId").val();

	// Only draw the map object (line/polygon) if there is more than one point
	if ( $("#ways tr").length > 1 ) {
		mainMap.loadKMLObject( mainMap, challengeId );
	}

	// When a point is clicked, update the table and map (but be sure to close the info window!)
    mainMap.listener = GEvent.addListener( mainMap.map, "click", 
		function( iwtabs ) { 
			if ( iwtabs ) { 
				toggleRows( iwtabs.name, kmlPtArray ); 
				if ( /\d+/.test( iwtabs.name ) ) { 
					iwtabs.closeInfoWindow(); 
					loadAdvancedMenu( iwtabs.name );
				} 
			} 
		}	
	);

	// Toggle row display based on what waypoint was clicked on
	function toggleRows( waypointId, kmlPtArray ) {
			
		for ( var x in kmlPtArray ) {
			if ( /on/.test( x ) ) {
				var wpt = /\d+/.exec( x );
				var row = document.getElementById( "pattern" + wpt );
				var bullet = $("#waypoint-no" + wpt);
				
				if ( wpt == waypointId ) {
					mainMap.map.addOverlay( kmlPtArray[ wpt + "on" ] );
					mainMap.map.removeOverlay( kmlPtArray[ wpt + "off" ] );
					row.setAttribute( "style", "color: #eb980a" );
					$(bullet).addClass("active");
				} else {
					mainMap.map.removeOverlay( kmlPtArray[ wpt + "on" ] );
					mainMap.map.addOverlay( kmlPtArray[ wpt + "off" ] );
					row.setAttribute( "style", "color: black;" );
					$(bullet).removeClass("active");
				}
			} 
		}
	}

	// Create Waypoint Advanced Map functions
	//
	// Load the 'edit/advanced settings' menu in the lightbox when either the monkeywrench icon
	// or the "add waypoint" button is clicked.
	//
	function loadAdvancedMenu( waypointId ){
				
		// --------------- Start Servlet request ---------------------- //
		form = $.post("../app/waypointServlet", {id:waypointId}, function( data ) {
			
				//
				// Then, when we have that, we pipe the newly-loaded page into a Boxy lightbox
				var formBox = new Boxy( data,{
					title: "Waypoint Details",
					closeable: true,
					draggable: true,
					y:50,
					modal: true,
					// unloadOnHide means boxy gets erased from the dom every time the 'close' button is pressed
					// If it's loading slow, turn this to false but be prepared to debug 
					unloadOnHide: true
				});
					
				// Initialize the advanced map, and add map events
				initAdvancedMap( );
			
				// --------------- Events are handled below ---------------- //
				//
				// Attach behavior to the Save & Close button (in the Advanced map aka lightbox)
				//
				$("#close", $("#advanced-menu")).click( function(){
					// close boxy window
					formBox.hide();		
				});
			
				// --------------- End Event handling ---------------- //
		});
		// --------------- End Servlet request ---------------------- //

		//
		//View Advanced Map functions
		//
		function initAdvancedMap() {
			// Initialize 'global' vars (used by the advanced map)
			var advancedMap = new MegosiMap(); // map object
	
			// Preset the default map location
			advancedMap.defaultLng = waypointLongitude;
			advancedMap.defaultLat = waypointLatitude;
			advancedMap.defaultZoom = 16;
			
			// Initialize Google Map
			advancedMap.initMap( "map_canvas" );
			    	
			advancedMap.loadKMLChallenge( advancedMap, challengeId, waypointId );
			advancedMap.loadKMLPoint( advancedMap, waypointId, "zoom" );

		    // Add Map controls
	    	advancedMap.map.addControl( new GSmallMapControl() );
	    	advancedMap.map.addControl( new GScaleControl() );
		   	advancedMap.map.addControl( new GMapTypeControl() );
			//advancedMap.map.addControl( new GOverviewMapControl() );

		}
	}
});

// Add a challenge to a user's myChallengeCollection
function addChallenge(e,challengeId){
	$.post("../app/myChallengeServlet?SERVLET_METHOD_CALL=addChallenge",{id:challengeId, redirect:"/challenge/"+ challengeId},
	    function( data, textStatus ){
			$("#messages").html( $("#messages",data).html());
			$("#huh").html( $("#huh",data).html());
			$("#addremove").html( $("#addremove",data).html());
			//$(".add").replaceWith("<button class='button floatRight action remove' id='removeButton' onClick=\"Boxy.confirm('Are you sure you want to leave this challenge?  All of your progress on this challenge will be lost forever.', function(){removeChallenge(this," + challengeId + ");}, {title: 'Confirm Your Action'});return false;\">Remove Challenge</button>");
	    }, "html");
}

// Remove a challenge from a users myChallengeCollection
function removeChallenge( e,challengeId ) {
	$.post("../app/myChallengeServlet?SERVLET_METHOD_CALL=removeChallenge",{id:challengeId, redirect:"/challenge/"+ challengeId},
        function( data, textStatus ){ 
			$("#messages").html( $("#messages",data).html());
			$("#huh").html( $("#huh",data).html());
			$("#addremove").html( $("#addremove",data).html());
			//$(".remove").replaceWith("<button class='button floatRight action add' id='addButton' onClick='addChallenge(this," + challengeId + ");return false;'>Sign me up!</button>");
        }, "html" );
}


//
// Before page is closed, undo some things (mainMap)
//
$(document).unload( function(){
	mainMap.map.removeListener( mainMap.listener );
	GUnload();
});