//
// NexTraq mobile web app javascript modules
//

window.nt = window.nt || {};

var dwmobile = function() {
	
	return {
		initializeMap: function() {
			var bounds = new google.maps.LatLngBounds();
			var allMarkers = new Array();
			if (nt.trackJson && nt.trackJson.length > 0) {
				var m = nt.maps.MarkerFactory.trackMarkerWithOptions(nt.trackJson[0], false, {zIndex:(google.maps.Marker.MAX_ZINDEX + 9000)});
				m.setZIndex((google.maps.Marker.MAX_ZINDEX + 9000));
				allMarkers.push(m);
				bounds.extend(m.getPosition());
			}
			if (nt.addressJson && nt.addressJson.length > 0) {
				var m = nt.maps.MarkerFactory.addressMarker(nt.addressJson[0]);
				m.setZIndex((google.maps.Marker.MAX_ZINDEX + 9000));
				allMarkers.push(m);
				bounds.extend(m.getPosition());
			}
			if (nt.closestMobilesJson && nt.closestMobilesJson.length > 0) {
				var len = nt.closestMobilesJson.length;
				for (var i=0; i < len; ++i) {
					var t = nt.closestMobilesJson[i];
					var mt = nt.maps.MarkerFactory.trackLetterMarker(t, i, {clickable:true});
					allMarkers.push(mt);
					bounds.extend(mt.getPosition());
				}
			}
			if (nt.closestLocationsJson && nt.closestLocationsJson.locations && nt.closestLocationsJson.locations.length > 0) {
				var len = nt.closestLocationsJson.locations.length;
				for (var i=0; i < len; ++i) {
					var l = nt.closestLocationsJson.locations[i];
					var ml = nt.maps.MarkerFactory.locationLetterMarker(l, i);
					allMarkers.push(ml);
					bounds.extend(ml.getPosition());
				}
			}
			var mapOpts = {
				showTraffic:false
			};
			if (navigator && navigator.userAgent) {
				var useragent = navigator.userAgent;
				if (useragent.indexOf('Android') != -1) {
					mapOpts.zoomControlOptions = {
						position: google.maps.ControlPosition.LEFT_TOP
					};
				}
			}
			if (allMarkers.length == 1) {
				mapOpts.center = new google.maps.LatLng(allMarkers[0].getPosition().lat(), allMarkers[0].getPosition().lng());
			} else if (allMarkers.length > 1) {
				mapOpts.center = bounds.getCenter();
			}
			function displayMap() {
				if (nt.map) return;
				var map = new nt.maps.BaseMap('map_canvas', mapOpts);
				nt.map = map;
				if (allMarkers.length > 1) map.fitBounds(bounds);
				if (allMarkers.length > 0) {
					for (var i=allMarkers.length-1; i >= 0; --i) {
						allMarkers[i].setMap(map);
					}
				}
				if (nt.mapState.trafficEnabled) {
					nt.trafficLayer = new google.maps.TrafficLayer();
					nt.trafficLayer.setMap(nt.map);
				}
			} // end displayMap()
			
			// Differ map init if map is not visible - o/w we get crazy zoom
			if ($('#map_canvas').is(":visible")) {
				displayMap();
			} else {
				function doDisplayMap() {
					$("#map-map").unbind('pageshow', doDisplayMap);
					displayMap();
				}
				$("#map-map").bind('pageshow', doDisplayMap);
			}
			
			$('#map-map').bind('pageshow', function(e, d){
				if (!nt || !nt.map) return;
				google.maps.event.trigger(nt.map, 'resize'); // tiles go missing when map hidden, this fixes it
			});
			
		}, // End function
		
		MAP_SLIP_TRAFFIC_KEY: 'mapSlip-showTraffic',
		
		initializeMapSettings: function() {
	        $('#map-opts-traffic').each(function() {
        		var traff = dwmobile.storage.get(dwmobile.MAP_SLIP_TRAFFIC_KEY);
        		if (traff == null) {
        			dwmobile.storage.put(dwmobile.MAP_SLIP_TRAFFIC_KEY, false);
        			traff = false;
        		}
        		if (traff) {
        			this.selectedIndex = 1;
        			nt.mapState.trafficEnabled = true;
        		}
	        });
	        $('#map-opts-apply').bind('vclick', function(e) {
				$('.ui-dialog').dialog('close');
				dwmobile.handleMapOptionsApply();
			});
			$('#map-opts-cancel').bind('vclick', function(e) {
				dwmobile.applyMapStateToOptions();
				$('.ui-dialog').dialog('close');
			});
			$('#flags-legend-slider').bind('change', function(e){
				var myswitch = $(this);
			    var show = myswitch[0].selectedIndex == 1 ? true:false;	
			    var idx = myswitch[0].title; // Using the title attribute to store the index
			    
			    if(show) {
			        $('#flags-legend-flags').fadeIn('slow');
			        $('#flags-legend-not-enabled').hide();
			    } else {
			        $('#flags-legend-flags').fadeOut();
			        $('#flags-legend-not-enabled').show();
			    }
			});
			$('#closest-locations-list-slider').bind('change', function(e){
				var enabled = this.selectedIndex == 1 ? true : false;
				nt.mapState.closestLocations = enabled;
				var url = 'map-slip.html?closestMobilesActive='+(nt.mapState.closestMobiles ? 'true':'false')+'&closestLocationsActive='+(nt.mapState.closestLocations ? 'true':'false');
				window.location = url;
			});
			$('#closest-mobiles-list-slider').bind('change', function(e){
				var enabled = this.selectedIndex == 1 ? true : false;
				nt.mapState.closestMobiles = enabled;
				var url = 'map-slip.html?closestMobilesActive='+(nt.mapState.closestMobiles ? 'true':'false')+'&closestLocationsActive='+(nt.mapState.closestLocations ? 'true':'false');
				window.location = url;
			});
        }, // End function
		
		handleMapOptionsApply: function(event) {
			var selects = $('select');
			var mobsChanged = false;
			var locsChanged = false;
			for (var i=0; i < selects.length; ++i) {
				var sel = selects[i];
				var enabled = sel.selectedIndex == 1 ? true : false;
				if (sel.id == "map-opts-traffic") {
					if (enabled && !(nt.mapState.trafficEnabled)) {
						nt.trafficLayer = nt.trafficLayer || new google.maps.TrafficLayer();
						nt.trafficLayer.setMap(nt.map);
					} else if (!enabled && nt.mapState.trafficEnabled) {
						if (nt.trafficLayer) nt.trafficLayer.setMap(null);
					}
					dwmobile.storage.put(dwmobile.MAP_SLIP_TRAFFIC_KEY, enabled);
					nt.mapState.trafficEnabled = enabled;
				} else if (sel.id == "map-opts-mobiles" && enabled != nt.mapState.closestMobiles) {
					mobsChanged = true;
					nt.mapState.closestMobiles = enabled;
				} else if (sel.id == "map-opts-locations" && enabled != nt.mapState.closestLocations) {
					locsChanged = true;
					nt.mapState.closestLocations = enabled;
				}
			}
			if (mobsChanged || locsChanged) {
				var url = 'map-slip.html?closestMobilesActive='+(nt.mapState.closestMobiles ? 'true':'false')+'&closestLocationsActive='+(nt.mapState.closestLocations ? 'true':'false');
				window.location = url;
			}
		}, // End function
		
		applyMapStateToOptions: function(event) {
			$('select').each(function(index, el) {
				if (el.id == "map-opts-traffic") {
					el.selectedIndex = nt.mapState.trafficEnabled ? 1 : 0;
				} else if (el.id == "map-opts-mobiles") {
					el.selectedIndex = nt.mapState.closestMobiles ? 1 : 0;
				} else if (el.id == "map-opts-locations") {
					el.selectedIndex = nt.mapState.closestLocations ? 1 : 0;
				}
				try {
					$(el).slider("refresh");
				} catch (err) {}
			});
		}, // End function
        
		initializeMapPageEventHandlers: function() {
      	    $('.ui-slider-handle').attr('title', '');  // Get rid of JQM slider button title attribute

	        $('select').each( function() { 
				$(this).change(function() {
				    var myswitch = $(this);
				    var show = myswitch[0].selectedIndex == 1 ? true:false;	
				    var idx = myswitch[0].title; // Using the title attribute to store the index
				    
				    if(show) {
				        $('#flags-div-' + idx).fadeIn('slow', function() { 
				        	$('.ui-slider-handle').attr('title', '');  // Get rid of JQM slider button title attribute
				        } );
				    } else {
				        $('#flags-div-' + idx).fadeOut('slow', function() {  
				        	$('.ui-slider-handle').attr('title', '');  // Get rid of JQM slider button title attribute
				        } );
				    }
				});		
		    } );
			
			$('#closest-mobiles-slider').change(function() {
			    var myswitch = $(this);
			    var show = myswitch[0].selectedIndex == 1 ? true:false;	
			    
			    if(show) {
			    	document.location.href = 'map.html?closestMobilesActive=true';
			    } else {
			    	document.location.href = 'map.html?closestMobilesActive=false';
			    }
			});

			$('#closest-locations-slider').change(function() {
			    var myswitch = $(this);
			    var show = myswitch[0].selectedIndex == 1 ? true:false;	
			    
			    if(show) {
			    	document.location.href = 'map.html?closestLocationsActive=true';
			    } else {
			    	document.location.href = 'map.html?closestLocationsActive=false';
			    }
			});	
			
			$('#purchasedate').bind('datebox', function (e, passed) { 
				  if ( passed.method === 'set' ) {
				    $('#purchasedate').datebox();
				  }
			});
        }, // End function

        submitFuelPurchase: function() {
        	dwmobile.formatPurchaseDate();
        	dwmobile.formatPurchaseTime();
        	$('#btnFuelPurchaseSave').val('save');
        	$('#FuelPurchaseForm').submit();        
        }, // End function
        
        formatPurchaseDate: function() {
        	var purchaseDate = $('#purchasedate').val();
        	
        	if (purchaseDate != null) {
        	    var purchaseDateArray = purchaseDate.split('-');
        	    $('#purchaseYear').val(purchaseDateArray[0]);
        	    $('#purchaseMonth').val(purchaseDateArray[1]);
        	    $('#purchaseDay').val(purchaseDateArray[2]);
        	}
        }, // End function
        
        formatPurchaseTime: function() {
        	var purchaseTime = $('#purchasetime').val();
        	
        	if (purchaseTime != null) {
        		var purchaseTimeArrayA = purchaseTime.split(':');
        	    $('#purchaseHours').val(purchaseTimeArrayA[0]);
        	    
        	    var purchaseTimeArrayB = purchaseTimeArrayA[1].split(' ');    	    
        	    $('#purchaseMinutes').val(purchaseTimeArrayB[0]);
        	    
        	    if (purchaseTimeArrayB[1] == 'AM') {
        	    	$('#purchaseAmPm').val(false);    	    	
        	    } else {
        	    	$('#purchaseAmPm').val(true);    	    	
        	    }
        	}
        }, // End function

        setFuelPurchaseButtons: function(saveBtn, deleteBtn, cancelBtn) {
        	$('#btnFuelPurchaseCancel').val((cancelBtn == true) ? 'cancel' : null);
        	$('#btnFuelPurchaseDelete').val((deleteBtn == true) ? 'delete' : null);
        	$('#btnFuelPurchaseSave').val((saveBtn == true) ? 'save' : null);
        }, // End function
        
        getDisplayInfo: function() {
        	   var display = { };
        	   
        	   if (screen.width <= 1280) {  // iPad width
        		   display.height = screen.height;
        		   display.width = screen.width;
        	   } else {
        		   display.height = 480; // Default to iPhone portrait
        		   display.width = 320;
        	   }

        	   if (window.orientation) {
        	   	if (window.orientation == 0) {
        	   		oridisplay.orientationntation = 'portrait';
        	   	} else if (window.orientation == 90 || window.orientation == -90) {
        	   		display.orientation = 'landscape';
        	   	}
        	   } else {
        		   display.orientation = 'portrait';
        	   }
        	   
        	   if (display.orientation == 'landscape') {
        		   // Swap dimensions
        		   var height = display.height;
        		   var width = display.width;
        		   
        		   display.height = width;
        		   display.width = height;
        	   }
        	   
        	   return display;
        }, // End function

        displayMap: function() {
        	$('.map').each( function() { 
        		var display = dwmobile.getDisplayInfo();
        	    var map = $(this);
        	    var src = map.attr('src');
        	    src = src.replace('320x480', display.width + 'x' + display.height);
        	    map.attr('src', src);
        	} );        	
        }, // End function
        
        formatLink: function(link) {
        	var address = link[0].innerHTML;
        	address = address.replace(/\n/g, '').replace(/\t/g, '').replace(/\"/g, '');
        	address = address.replace(/^\s\s*/, '').replace(/\s\s*$/, '');

        	var display = dwmobile.getDisplayInfo();
        	
        	if (display.width <= 320) {
        		if (address.length > 22) {
        		    address = address.substring(0, 22) + '...';
        		}
        		
        		link[0].innerHTML = address;
        	}
        }, // End function

        showLoadingMask: function() {
        	$.mobile.showPageLoadingMsg();        		
        }, // End function

        setApplicationDefaults: function(config) {
        	$.mobile.defaultPageTransition = 'none';
        	$.mobile.ajaxEnabled = false;
        	for (var prop in config) {
    			if (prop != 'defaultPageTransition' || prop != "ajaxEnabled") {
    				$.mobile[prop] = config[prop];
    			}
        	}
        }, // End function
        
        stopTouchMove: function (e){ 
			if (e.preventDefault != null) { 
				e.preventDefault(); 
			} 
		}, // End function
        
		storage: function(){ 
			return {
				NAMESPACE: "nextraq",

				isSupported: function() {
					try {
						return 'localStorage' in window && window['localStorage'] !== null && 'JSON' in window && window['JSON'] !== null;
					} catch (e) {
						return false;
					}
				},

				_getStorage: function() {
					if (!this.isSupported()) return null;
					var r = localStorage[dwmobile.storage.NAMESPACE];
					if (typeof(r) == "undefined" || r == null) {
						r = "{}";
						localStorage[dwmobile.storage.NAMESPACE] = r;
					}
					return window.JSON.parse(r);
				},
				
				_saveStorage: function(stor) {
					localStorage[dwmobile.storage.NAMESPACE] =  window.JSON.stringify(stor);
				},
				
				put: function(key, val) {
					if (!this.isSupported()) return;
					var s = this._getStorage();
					s[key] = val;
					this._saveStorage(s);
				},
				
				set: function(key, val) {
					this.put(key, val);
				},
				
				get: function(key) {
					if (!this.isSupported()) return;
					var s = this._getStorage();
					var r = s[key];
					if (typeof(r) == "undefined") return null;
					return r;
				}
			}; // End return
		}() // End storage
	}; // End return
}(); // End object

/*
 * Monkey patch TrackMarker "click" handler
 */
function __monkeyPatchTrackMarker() {
	nt.maps.TrackMarker.prototype.retrieveAndSetInfoWindowContent = function() {
		var t = this.get('track');
		if(t.mobile == null){
			var origResponse = { json: {data: t } };
			google.maps.event.trigger(this, 'handleclickfailure', this, origResponse);
			return;
		}
		var dt = new Date(t.date.time);
	
		var html = new Array();
		html.push("Mobile: " + t.mobile.name + "<br />");
		if(nt.mobileDriverName && nt.mobileDriverName.length > 0) {
			html.push("Driver: "+nt.mobileDriverName);
		} else {
			html.push("Driver: No driver");
		}
		html.push("<br/>");
		html.push("Date: " + t.dateDisplay + "<br />");
		html.push('<table cellpadding="0" cellspacing="0" style="margin-right:1em">');
		html.push('<tr><td>Location:&nbsp;</td><td><div style="width:210px; white-space:nowrap; overflow:hidden; text-overflow:ellipsis;">' + (t.location || t.address.street) + "</div></td></tr>");
		html.push('<tr><td></td><td style="text-overflow: ellipsis">' + t.address.city + " " +  t.address.stateDisplay + " " + t.address.zip + "</td></tr>");
		//html.push("<tr><td></td><td><a href='#' id='street-view' title='Open Street View'>Open Street View</a></td></tr>");
		html.push("</table>");
		html.push("Vehicle: ");
		if (t.inMotion) {
			html.push("Moving " + t.heading + " at " + t.speedDisplay + "<br />");
		} else if (this.showIdle == true && t.idle == true){
			html.push("Idling " + t.minutesIdleDisplay + "<br />");
			if (nt.maps.MarkerFactory.isShowFuelInfoPref() == true && typeof(t.mobile.gallonsPerHour) != "undefined" && typeof(t.mobile.pricePerGallon) != "undefined") {
				var val = (t.minutesIdle / 60) * t.mobile.gallonsPerHour * t.mobile.pricePerGallon;
				if (!isNaN(val) && val >= 0.01) {
					var allCents = Math.floor(val*100+0.50000000001);// Floating point fail, 4.1*100=409.999999999999943 - http://javascript.internet.com/forms/currency-format.html
					var cents = allCents % 100;
					if (cents < 10) cents = "0" + cents;
					var dols = Math.floor(allCents/100).toString();
					html.push("Cost of Idle Loss: $" + dols + "." + cents + "<br />");
				}
			}
		} else {
			html.push("Stopped " + t.minutesStoppedDisplay + "<br />");
		}
		if(nt.mobileDispatchStatus != null && nt.mobileDispatchStatus.length > 0){
			html.push("Dispatch Status: " + nt.mobileDispatchStatus + "<br />");
		}
		// On mobile speed bubble bottom is over top of text
		html.push('<div style="width:5px; height:7px"></div>');
		var mobileDiv = document.getElementById("infowindow-mobile");
		if(mobileDiv == null){
			mobileDiv = document.createElement("div");
			mobileDiv.setAttribute("id", "infowindow-mobile");
		}
		mobileDiv.style.backgroundColor = "white";
		mobileDiv.innerHTML = html.join("");
		
		this.setInfoWindowContent(mobileDiv);
	}
}
