// global map object
var map = null;
// make an array for the markers
var all_markers = new Array;
// the home marker
var home_marker = "";
// make an array for the infoBoxes
var all_info_boxes = new Array;

var directionsDisplay = new google.maps.DirectionsRenderer();
var directionsService = new google.maps.DirectionsService();

/******************************************************************************
 * The main ready function
 ============================================================================*/

$(document).ready(function(){
	
	// set up variables from the widget; get them from the data elements on the div
	// var widget_data = $('#widget-google-map').data(); // console.log(widget_data);
	var widget_data = {
		"map_canvas"			: $('#widget-google-map').attr('data-map_canvas'),
		"show_map_controls"		: $('#widget-google-map').attr('data-show_map_controls'),
		"show_map_types"		: $('#widget-google-map').attr('data-show_map_types'),
		"show_map_traffic"		: $('#widget-google-map').attr('data-show_map_traffic'),
		"show_satellite_map"	: $('#widget-google-map').attr('data-show_satellite_map'),
		"show_hybrid_map"		: $('#widget-google-map').attr('data-show_hybrid_map'),
		"show_normal_map"		: $('#widget-google-map').attr('data-show_normal_map'),
		"map_height"			: $('#widget-google-map').attr('data-map_height'), 
		"local_search"			: $('#widget-google-map').attr('data-local_search'),
		"zoom_level"			: $('#widget-google-map').attr('data-zoom_level'),
		"auto_info_window"		: $('#widget-google-map').attr('data-auto_info_window'),
		"show_direction_search"	: $('#widget-google-map').attr('data-show_direction_search')
	};
	
	var map_id		= widget_data.map_canvas;
	
	// console.log(widget_data);
	
	// if(!widget_data.length){
	// 	map_id = $('#widget-google-map').attr('data-map_canvas');
	// }

	// additional map settings
	var map_height				= parseFloat(widget_data.map_height);
	var zoom_level				= parseFloat(widget_data.zoom_level);
	
	// set the start location
	var initialLocation = new google.maps.LatLng(39.50, -98.35); // geographic center of the US
	var browserSupportFlag = new Boolean();
	
	// create the map options
	var myOptions = {
		zoom: zoom_level,
		maxZoom: 17,
		mapTypeId: google.maps.MapTypeId.ROADMAP,
		panControl: widget_data.show_map_controls,
		zoomControl: widget_data.show_map_controls,
		mapTypeControl: widget_data.show_map_types,
		scaleControl: widget_data.show_map_controls,
		streetViewControl: widget_data.show_map_controls
	};
	
	// create the map
	// console.log(map_id);
	// console.log(myOptions);
	
	map = new google.maps.Map(document.getElementById(map_id), myOptions);
	// create a geocoder object
	var geocoder = new google.maps.Geocoder();
	// set a boundary object
	var bounds = new google.maps.LatLngBounds();
	// create an InfoWindow
	var info_window = new google.maps.InfoWindow();
	// direction renderer
	//var directionsDisplay = new google.maps.DirectionsRenderer();
	//var directionsService = new google.maps.DirectionsService();
	
	// check for the print link and handle it in a special way for the zoom
	google.maps.event.addListener(map, 'zoom_changed', function() {
		if($('#map-directions-list-print-link').length > 0)
		{
			var old_href = $('#map-directions-list-print-link').attr('href');
			$('#map-directions-list-print-link').attr('href', old_href.replace(/z=\d+/,'z='+map.getZoom()));
		}
	});
	
	function get_markers(){
		clear_markers();
		if($('#map-locations-list li').length > 0){
			// get all the addresses
			$('#map-locations-list li').each(function(i, loc){
				// get the data provided by the address
				// var ldata = $(this).data();
				var ldata = {
					"latlng"			: $(this).attr('data-latlng'),
					"location_title"	: $(this).attr('data-location_title'),
					"address"			: $(this).attr('data-address'),
					"address1"			: $(this).attr('data-address1'),
					"address2"			: $(this).attr("data-address2"),
					"city"				: $(this).attr('data-city'),
					"state"				: $(this).attr('data-state'),
					"zip"				: $(this).attr('data-zip'),
					"phone"				: $(this).attr('data-phone'),
					"url"				: $(this).attr('data-url')
				};
				var li_id = $(this).attr('id');
				
				// check if we have lat/lng defined for a building -- typeof yourvar != 'undefined'
				if(typeof ldata.latlng != 'undefined' && ldata.latlng !== '')
				{
					// split a lat/long in a format: 35.983242, -91.2341234
					var splitted = ldata.latlng.split(',');
					jQuery.each(splitted, function(i, item){ splitted[i] = jQuery.trim(item); });
					
					var myLatLng = new google.maps.LatLng(splitted[0], splitted[1]);
					set_marker({ 
						loc: ldata,
						latlng: myLatLng,
						li_id:  li_id,
						auto_info_window: (i < 1?widget_data.auto_info_window:false)
					});
				}
				// we need to geocode the address if there is no lat/long
				else
				{
					var geo_address = ldata.address;
					if(typeof ldata.address1 != 'undefined' && ldata.address1 !== ''){
						var address2_new = ldata.address2?',+'+ldata.address2:'';
						geo_address = ldata.address1+address2_new+',+'+ldata.city+',+'+ldata.state+',+'+ldata.zip;
					}
					
					geocoder.geocode( { 'address': geo_address }, function(results, status) {
						if (status == google.maps.GeocoderStatus.OK) {
							set_marker({
								loc: ldata,
								latlng: results[0].geometry.location,
								li_id: li_id,
								auto_info_window: (i < 1?widget_data.auto_info_window:false)
							});
						}
					}); // geocoder.geocode
				}
			});
		}
		else{
			map.setCenter(initialLocation);
		}
	}
	
	function set_marker(options){
		// check if a zoom level was defined
		if(typeof(options.zoom) != 'undefined')
		{
			map.setCenter(options.latlng);
			map.setZoom(options.zoom);
		}
		// no zoom level, so we will do it with the bounds
		else
		{
			bounds.extend(options.latlng);
			map.fitBounds(bounds);
		}
		
		// place the marker
		var marker = new google.maps.Marker({
			map: map, 
			position: options.latlng
		});
		
		// store the marker for later
		all_markers.push(marker);
		
		var loc 	= options.loc;
		var latlng 	= options.latlng;

		var address_string = loc.address1+'<br>'+(loc.address2!=''?loc.address2+'<br>':'')+loc.city+', '+loc.state+' '+loc.zip+'<br>';
		var phone_string = '';
		var link_string = '';
		var title_string = '<strong>'+loc.location_title+'</strong>';

		if(loc.address1 == '' || loc.address1 == undefined){
			address_string = loc.address+'<br>';
		}
		
		if(loc.phone != '' && loc.phone != undefined){
			phone_string = loc.phone+'<br>';
		}
		
		if(loc.url != '' && loc.url != undefined){
			link_string = '<a href="'+loc.url+'">'+loc.url+'</a><br>';
			title_string = '<a href="'+loc.url+'">'+title_string+'</a>';
		}
		
		var content_string = '';
		content_string = 
			'<div id="bubble-close">'+
				'<a href="#" onclick="close_boxes(); return false;">X</a>'+
			'</div>'+
			'<p class="bubble-text">'+title_string+'<br>'+
				address_string+
				phone_string+
				link_string+
			'</p>'+
			'<div class="directions-form-wrap">'+
				'<form name="bubble-'+options.li_id+'" id="bubble-'+options.li_id+'" action="#" method="post" data-destination="' 
					+ options.latlng
					+ '" class="directions-form" onsubmit="get_directions(\'bubble-'+options.li_id+'\'); return false;">'
					+ 'Get Directions<br>'
					+ '<input type="text" placeholder="Start Address" title="Start Address" value="" class="start-address"><input type="submit" name="go-submit" value="GO">'
				+ '</form>'
			+ '</div>';
		
		var infoBox = new InfoBubble({
			position: marker.getPosition(), 
			map: map, 
			content: content_string,
			shadowStyle: 0,
			padding: 0,
			backgroundColor: '#777',
			borderRadius: 5,
			arrowSize: 10,
			borderWidth: 1,
			borderColor: '#CCC',
			disableAutoPan: false,
			hideCloseButton: false,
			arrowPosition: 30,
			backgroundClassName: 'map-bubble',
			arrowStyle: 0,
			minWidth: 300,
			minHeight: 150,
			maxHeight: 'none',
			maxWidth: 400
		});
		
		all_info_boxes.push(infoBox);
		
		// set up the event listener for the click
		google.maps.event.addListener(marker, 'click', function() {
			close_boxes();
			
			$("#"+options.li_id).addClass('act');
			
			// open the new window
			infoBox.open(map, marker);
		});
		
		// set up the click on the listed location li's
		$("#"+options.li_id).click(function(){
			close_boxes();
			
			$(this).addClass('act');
			
			// open the new window
			infoBox.open(map, marker);
			
			scroll_to_loctions_map();
		});
		
	}
	
	$('#map-locations-list-show .back-to-list').click(function(e){
		e.preventDefault();
		
		$('#map-directions-list').html('');
		$('#map-locations-list-show').hide();
		$('#map-locations-list').show();
		
		directionsDisplay.setMap(null);
		
		get_markers();
		
		return false;
	});
	
	$('#map-locations-list li > a').click(function(e){
		$(this).next().slideToggle('fast');
		return false;
	});
	
	$('#widget-google-map .start-address').live('focus', function(){
		if($(this).val() == 'start address' || $(this).val() == 'Start Address'){
			$(this).val('').css('color', '#000');
		}
		return false;
	});
	
	$('#widget-google-map .start-address').bind('click', function(e){
		e.preventDefault;
		return false;
	});
	
	// FORM FIND FACILITIES NEAR YOU
	$('form#find-facilities-near-you').submit(function(){
		close_boxes();
		
		// get zip val
		var input_zip = $(this).find('#map-input-zipcode').val();
		
		var near_bounds = new google.maps.LatLngBounds();
		
		geocoder.geocode( { 'address': input_zip }, function(results, status) {
			if (status == google.maps.GeocoderStatus.OK) {
				//rewrite markers array and order them by distance
				var markers_array = new_markers_array_by_distance(results[0].geometry.location);
				
				near_bounds.extend(results[0].geometry.location);
				
				if(home_marker){
					home_marker.setMap(null);
				}
				
				home_marker = new google.maps.Marker({
					position: results[0].geometry.location,
					map: map,
					icon: "http://globalinc.prod.ehc.com/design/icons/house-map.png",
					title: 'You (or where you are now)'
				});
				
				var count = 0;
				jQuery.each(markers_array, function(key,val){
					if(count < 3){
						near_bounds.extend(val);
					}
					count++;
				});
				
				map.fitBounds(near_bounds);
			}
		}); //geocoder.geocode

		return false;
	});
	
	// initialize
	get_markers();
	
}); // document ready

function rad(x) { return x*Math.PI/180; }

function distHaversine(p1, p2) {
	var R = 6371; // earth's mean radius in km
	var dLat  = rad(p2.lat() - p1.lat());
	var dLong = rad(p2.lng() - p1.lng());
	
	var a = Math.sin(dLat/2) * Math.sin(dLat/2) + Math.cos(rad(p1.lat())) * Math.cos(rad(p2.lat())) * Math.sin(dLong/2) * Math.sin(dLong/2);
	var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
	var d = R * c;
	
	return d.toFixed(3);
}

function sortObj(arr){
	// Setup Arrays
	var sortedKeys = new Array();
	var sortedObj = {};
	
	// Separate keys and sort them
	for (var i in arr){
		i = parseFloat(i);
		sortedKeys.push(i);
	}
	
	sortedKeys.sort(function(a, b) {
		if (a < b) { return -1; }
		if (a > b) { return  1; }
		return 0;
	});
	
	// Reconstruct sorted obj based on keys
	for (var i in sortedKeys){
		sortedObj[sortedKeys[i]] = arr[sortedKeys[i]];
	}
	
	return sortedObj;
}

function new_markers_array_by_distance(my_location){
	var new_markers_array = Array();
	for( i=0;i<all_markers.length; i++ ) {
		var dis = Math.round( parseFloat( distHaversine(my_location,all_markers[i].position) )*100 );
		new_markers_array[dis] = all_markers[i].position;
    }
    // sort array
    new_markers_array = sortObj(new_markers_array);
 	return new_markers_array;
}

function scroll_to_loctions_map(){
	$('html, body').animate({
		scrollTop: $("#widget-google-map h2").offset().top
	}, 400);
}

function close_boxes(){
	$(all_info_boxes).each(function(){
		this.close();
	});
	
	// remove the class from all other list items
	$('#map-locations-list li').removeClass('act');
}

function clear_markers(){
	$(all_markers).each(function(){
		this.setMap(null);
	});
	
	if(home_marker){
		home_marker.setMap(null);
	}
	
	all_markers = new Array;
	all_info_boxes = new Array;
	
	$('.map-bubble').remove();
}

function get_directions(directions_form_id){
	close_boxes();
	var directions_form = $('#'+directions_form_id);
	var end = $('#'+directions_form_id).attr('data-destination');
	var start = $('#'+directions_form_id).find('.start-address').val();
	var request = {
		origin: start, 
		destination: end,
		travelMode: google.maps.DirectionsTravelMode.DRIVING
	};
	directionsService.route(request, function(result, status) {
		if (status == google.maps.DirectionsStatus.OK) {
			$('#map-locations-list li').removeClass('act');
			clear_markers();
			directionsDisplay.setMap(map);
			directionsDisplay.setDirections(result);
			directionsDisplay.setPanel(document.getElementById("map-directions-list"));
			// create the print link
			$('#map-locations-list-show .print-link').html('<a id="map-directions-list-print-link" href="http://maps.google.com/maps?z='+map.getZoom()+'&pw=2&saddr='+start+'&daddr='+end+'" target="_blank">Print These Directions</a>');
			$('#map-locations-list').hide();
			$('#map-locations-list-show').show();
		}
	});
	
	return false;
}
