/* =======================================================
MAPPING APPLICATION
@author: bwright@organic.com
@date: 5/6/2009
=======================================================*/

/* ----------------------------------------------------------
VARIABLES
 ----------------------------------------------------------*/
var map = null;
var geocoder = null;
var directions = null; //Main Google directions variable
var markerArray = new Array();



/* Organic 5/6 */
var icon = new GIcon(); 
icon.image = "/shared/images/mapping_application/map_icon.png";
icon.shadow = "/shared/images/commercial/maps/shadow.png";
icon.iconSize = new GSize(73, 69); //icon.iconSize represents width/height of the image in pixels.
icon.shadowSize = new GSize(22, 20);
icon.iconAnchor = new GPoint(38, 69); //icon.iconAnchor should use the pixel (x,y) of the image that represents the anchor (width, height) 
icon.infoWindowAnchor = new GPoint(0, 0);


/* Organic 5/6 */
var mapping_application = {

	/* ----------------------------------------------------------
	MODEL
	 ----------------------------------------------------------*/
	model: {
	
		//DISPLAY CONTAINERS
		left_column_container:		"custom_left",
		map_container: 			"custom_map",
		
		directions_span:			"directions_span",
		directions_overview_container: 		"directions_overview_container",
		directions_container: 			"directions_container",
		directions_commands_container: 		"directions_commands_container",
		
		primary_selector_container: 	"primary-selector-box", // vehicle-selector-box
		current_primary_selection: 	"",
		secondary_selector_container: 	"secondary-selector-box", //upfit-selector-box
		current_secondary_selection:	"",
		
		directions_from_event: 		false,
		user_requested_location: 	"", //Directions address provided by the user
		
		printWindow: 			"", //This will be the print window object
		callBackActions:		[] //This will contain the string of actions that the print window should execute
	
		//SET CUSTOM PROPERTIES OF THIS OBJECT
		//Set properties for this object if necessary, like when loading in data via XML rather than JSON.
		//This will allow you to retain the results from those operations in the global mapping_application object
		//yet from the mapping_application_overrides.js object specific to your application.
		
	},	
	
	
	
  
	/* ----------------------------------------------------------
	VIEW
	 ----------------------------------------------------------*/
	view: {
		/* showInfo causes the marker window contents to appear on the map, above the corresponding plotted point */
		showInfo: function(id) { markerArray[id].showDetailWin();},

		
		/* Plot the point on the map */
		plotPoint: function (pointObject, customIcon) {
			var thisIcon = icon;
			(typeof customIcon == "undefined") ? thisIcon.image = icon.image : thisIcon.image = customIcon; //use the default icon
				
			// create point
			var point = new GLatLng(parseFloat(Number(pointObject.lat)),	parseFloat(Number(pointObject.lon)));
			
			// add new marker
			marker = new PdMarker(point, thisIcon);
			marker.setName(pointObject.id);
		
			// creat the html contents
			mapping_application.controller.createMarkerWindowContents(pointObject, marker); //This creates a display element, but it does not AFFECT the display.
			
			// add overlay to map
			map.addOverlay(marker);
			
			// push ino array for clean up later
			markerArray.push(marker);
			
			// zoom to markers
			map.zoomToMarkers(50);
			
			if(map.getZoom() == 4) map.setZoom(9);
			
		},
		
		//ABSTRACT
		setDirectionsOverview: function() {},
		
		
		// loop through and clean points up
		clearPoints: function() {
			for(var i=0; i<markerArray.length; i++) {
				markerArray[i].remove();
			}
			markerArray = new Array();
		}
	},
	
	
	
	
	/* ----------------------------------------------------------
	CONTROLLER
	 ----------------------------------------------------------*/
	controller: {
			
	
		/*----------------------------------------------------------
		initialize_map()  
		Loads the google api into the normal, default state. No markers are present, and no data is needed.
		----------------------------------------------------------*/
		initialize_map: function () {
			if (GBrowserIsCompatible()) {
				map = new GMap2(document.getElementById(mapping_application.model.map_container));
				map.addControl(new GLargeMapControl());
				map.addControl(new GMapTypeControl());
				directions = new GDirections(map, document.getElementById(mapping_application.model.directions_container));
				geocoder = new GClientGeocoder();
				map.setCenter(new GLatLng(37.0625, -95.677068), 4);
				GEvent.addListener(directions, "load", mapping_application.controller.loadDirections);
				GEvent.addListener(directions, "error", mapping_application.controller.handleErrors);
				var myArray = $$('img');
				myArray.each(function(item, index){
								  
					if( (item.getProperty('src')== "http://www.google.com/intl/en_us/mapfiles/lmc.png") || 
						(item.getProperty('src')== "http://www.google.com/intl/en_ALL/mapfiles/lmc.png") ) {
						item.setProperty('src', '/shared/images/commercial/maps/controls_top.png');
					}
					if( (item.getProperty('src')== "http://www.google.com/intl/en_us/mapfiles/lmc-bottom.png") || 
						(item.getProperty('src')== "http://www.google.com/intl/en_ALL/mapfiles/lmc-bottom.png") ) {
						item.setProperty('src', '/shared/images/commercial/maps/controls_bottom.png');
					}
					if( (item.getProperty('src')== "http://www.google.com/intl/en_us/mapfiles/slider.png") || 
						(item.getProperty('src')== "http://www.google.com/intl/en_ALL/mapfiles/slider.png") ) {
						item.setProperty('src', '/shared/images/commercial/maps/slider.png');
					}
				});
			}
		},
				
		
		/*----------------------------------------------------------
		createMarkerWindowContents()  
		 creates the marker window contents that will be shown by showInfo()
		----------------------------------------------------------*/
		createMarkerWindowContents: function (aPoint, marker) {
			
			var html = ""+
				"<div class='markerDetail'>"+

					"<div id='r1'>"+
						"<a class='infoWinCloseLink' href='#' onclick='javascript: map.pdMarkers["+(aPoint.listPosition - 1)+"].closeDetailWin();'>Close</a>"+
					"</div>";

		
					html 	+= "<div id='r2'>"+
						"	<div id='r2a'>"+
						"		<p id='r2aname' >"+aPoint.name+"</p>"+
						"		<p id='r2aaddress1' >"+aPoint.address1+"</p>"+
						"		<p id='r2aaddress2' >"+aPoint.city+", "+aPoint.state+" "+aPoint.zip+"</p>"+
						"<p><a href='#' onclick='javascript: mapping_application.controller.printMarker(); return false;'>Print Event</a></p>"+
						"	</div>"+
						"	"+
						"	<div id='r2b'>"+
						"		<p id='r2aevent' >Event Description</p>"+
						"		<p id='r2adesc' >"+aPoint.description+"</p>"+
						"	</div>"+
						"</div>";



					html 	+= "<div id='r3'>"+
							"<div id=\"directions-wrapper\">"+
								"<form action=\"javascript:mapping_application.controller.getDirections(document.directions.address.value, '" + mapping_application.controller.buildAddress(aPoint) + "', mapping_application.model.directions_from_event);\" name=\"directions\" method=\"get\">"+
									"<span class=\"info-window-subtitle\">Get Directions:</span> <a id=\"to-here\" class=\"off\" href=\"javascript:mapping_application.controller.toggleToFrom('to-here');\">To Here<\/a> - <a id=\"from-here\" class=\"on\" href=\"javascript:mapping_application.controller.toggleToFrom('from-here');\">From Here<\/a>"+
									"<p class='sleader'><span id=\"address-title\">Start Address<\/span>&nbsp;&nbsp;&nbsp;"+
									"<input id=\"fromAddress\" name=\"address\" ondblclick=\"mapping_application.controller.focusAllForm(this);\" onclick=\"mapping_application.controller.focusForm(this);\" type=\"text\" value=\"Enter Address\" name=\"from\" size=\"28\"\/><input id=\"arrow\" type=\"image\" value=\"go\" src=\"\/shared\/images\/mapping_application\/button.jpg\"/></p>"+
								"<\/form>"+
							"</div>"+
						"</div>";


					html += ""+
					"</div>"+
					"<div id='r4'>"+
						"&nbsp;"+
					"</div>"+
				"</div>";
			
			marker.setDetailWinHTML(html);
		},
		
		//ABSTRACT
		onMarkerClick: function(marker) {},
		
		
		handleErrors: function() {
			  if (directions.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
			  if($('error') == undefined) {
				var error = new Element('span', {'id': 'error'}).injectInside($('directions-wrapper'));
				error.setHTML("Please Try Again. The address you entered can not be found, this may be due to the fact that the address is relatively new, or it may be incorrect."); 
				
			  }
		},


		toggleToFrom: function(element) {
			if(element == "to-here") {
				linkTrack("map", "to-here");
				$('address-title').setText('Start Address');
				$('to-here').setProperty('class', 'off');
				$('from-here').setProperty('class', 'on');
				mapping_application.model.directions_from_event = false;
			} else {
				linkTrack("map", "from-here");
				$('address-title').setText('End Address');
				$('to-here').setProperty('class', 'on');
				$('from-here').setProperty('class', 'off');
				mapping_application.model.directions_from_event = true;
			}
			
			console.log(mapping_application.model.directions_from_event);
		},

		buildAddress: function(point) {
			//mapping_application.controller.buildAddress(mapping_data.primary_events.talladega.secondary_events.talladega_biscuits)
			return ""+point.address1+", "+point.city+", "+point.state+" "+point.zip;
		},

		getDirections: function(user_location, event_location, from_event) {
			linkTrack("map", "enter_directions");
			if(user_location != "Enter Address" && user_location != "") { //user_location was provided
				mapping_application.model.user_requested_location = user_location;
				if(from_event == true) {
					directions.load("from: " + event_location + " to: " + user_location);
				} else {
					directions.load("from: " + user_location + " to: " + event_location);
				}
				
			}
		},
		
		loadDirections: function() {
			closeOverlay.all();
			mapping_application.view.clearPoints();
			$('selectors_spans').setStyle('display', 'none');
			map.enableDragging();
			//Onloading Directions, we should put the point data into the directions overview container 
			mapping_application.view.setDirectionsOverview();
			$(mapping_application.model.directions_span).setStyle('display', 'block');
		},
		
		turnOffDirections: function() {
			directions.clear();
			$('selectors_spans').setStyle('display', 'block');
			$(mapping_application.model.directions_span).setStyle('display', 'none');
			$(mapping_application.model.directions_container).innerHTML = "";
			mapping_application_overrides.controller.onPrimarySelectorChange(mapping_application.model.current_primary_selection);
		},
		
		//PRINT 
		printDirections: function () {
			mapping_application.model.printWindow = window.open('print.html','print','width=800,height=850');
			mapping_application.model.callBackActions.push('mapping_application.controller.doOnloadPrintDirections()');
		},
		
		printMarker: function() {
			mapping_application.model.printWindow = window.open('print.html','print','width=800,height=850');
			mapping_application.model.callBackActions.push('mapping_application.controller.doOnloadPrintMarker()');
			linkTrack("map_marker", "print_event");
		},
		
		doOnloadAction: function() { //Called by the child print window.
			for (var i = 0; i < mapping_application.model.callBackActions.length; i++) {
				eval(mapping_application.model.callBackActions[i]);
			}
			mapping_application.model.callBackActions = [];
		},
		
		doOnloadPrintDirections: function() {
			var aPoint = mapping_data.primary_events[mapping_application.model.current_primary_selection].secondary_events[mapping_application.model.current_secondary_selection];			
			var current_event = mapping_application.controller.buildAddress(aPoint);
			var to = "";
			var from = "";
			mapping_application.model.printWindow.setPoint(aPoint);
			if(mapping_application.model.directions_from_event == true) {
				to = mapping_application.model.user_requested_location;
				from = current_event;
			} else {
				to = current_event;
				from = mapping_application.model.user_requested_location;
			}
			mapping_application.model.printWindow.writeOverview();
			mapping_application.model.printWindow.getDirections(to, from);
			
			//Print the window.
			setTimeout("mapping_application.model.printWindow.print();",2000);
		 
		},
		
		doOnloadPrintMarker: function() {
			mapping_application.model.printWindow.map.clearOverlays(); //Eliminate the google marker which is defaulted there.
			var aPoint = mapping_data.primary_events[mapping_application.model.current_primary_selection].secondary_events[mapping_application.model.current_secondary_selection];			
			mapping_application.model.printWindow.setPoint(aPoint);
			mapping_application.model.printWindow.writeOverview();
			var iconImage = '/shared/images/mapping_application/motorsports/marker'+aPoint.listPosition+'.png';
			mapping_application.model.printWindow.plotPoint(parseFloat(Number(aPoint.lat)), parseFloat(Number(aPoint.lon)), iconImage);	
				
			//Print the window.
			setTimeout("mapping_application.model.printWindow.print();",2000);
		},
		
		focusForm: function(form) {
			form.focus();
			if(form.value == "Enter Address") form.value = "";
		},

		focusAllForm: function(form) {
			form.focus();
			form.select();
		}

		
	}
	

};
