// create map object
var map;
// create geocoder object
var geocoder;
// current region
// check the official documentation to change region
// http://code.google.com/apis/maps/documentation/v3/services.html#CountryCodes
// requires a ccTLD (county code top-level domain)
// for a list of ccTLD's visit: http://en.wikipedia.org/wiki/CcTLD
var region = 'us';

// Create references to the mapping elements
var map;
var bounds;

// Create center of the US
var center = new GLatLng(39.8333333,-97.583333333);

// on dom ready
$(document).ready(function(){
	// Generate first map
	map = new GMap2(document.getElementById("map_canvas"));
	map.setMapType(G_NORMAL_MAP);
	map.addControl(new GSmallMapControl());
	map.addControl(new GScaleControl());
	map.enableContinuousZoom();
	map.enableScrollWheelZoom();
	
	// Create mini locator icon
	miniIcon = new GIcon();
	miniIcon.image = "http://"+top.location.host+"/imgs/markers/mini/mini_icon.png";
	miniIcon.shadow = "http://"+top.location.host+"/imgs/markers/mini/mini_icon_shadow.png";
	miniIcon.transparent = "http://"+top.location.host+"/imgs/markers/mini/mini_icon_transparent.png";
	miniIcon.iconSize = new GSize(16, 18);
	miniIcon.shadowSize = new GSize(16, 18);
	miniIcon.iconAnchor = new GPoint(8, 18);	
	// Add locations
	for( var i = 0; i<locArr.length; i++ ) {
		var locMarker = new GMarker(locArr[i],{icon:miniIcon});
		map.addOverlay(locMarker);
	}
	
	// Center Map 
	map.setCenter(center, 4);
	
	// if the store locator form is on the page
	if($('#store_locator').length) {		
		// take over submit action
		$('#store_locator').submit(function(){
			// get address
			var address = $('#address').val();
			var distance = $('#distance').val();

			// do lookup if address not empty
			if(address != '') {
				address_lookup(address, distance, region);
			} else {
				$('#ajax_msg').html("<ul class='flash_bad'><li>Please enter a full address or a Postcode</li></ul>");
			}
		return false;
		});
	}
});

/**
 * Sets the z-index of a map marker based on importance. Markers with the same importance will be layered from
 * north to south.
 * 
 * @param GMarker marker
 * @param unknown b
 */
function importanceOrder(marker, b) {
	return GOverlay.getZIndex(marker.getPoint().lat()) + marker.importance*1000000;
}

/**
 * Lookup an address
 * @param string address
 * @param int distance
 * @param string region
 */
function address_lookup(address,distance,region) {
	// set default region
	if(region==null || region == '') {
		region = 'us';
	}
	
	// address not empty
	if(address != '') {
		// Center Map on center of the US
//		map.setCenter(center, 4);
		
		// Create new geocoding object
	    geocoder = new GClientGeocoder();
	    
	    // Create bounding object to automatically set appropriate zoom level
	    bounds = new GLatLngBounds();
	    
		// Create a home icon
		homeIcon = new GIcon();
		homeIcon.image = "http://"+top.location.host+"/imgs/markers/home/home_icon.png";
		homeIcon.shadow = "http://"+top.location.host+"/imgs/markers/home/home_icon_shadow.png";
		homeIcon.transparent = "http://"+top.location.host+"/imgs/markers/home/home_icon_transparent.png";
		homeIcon.iconSize = new GSize(26, 39);
		homeIcon.shadowSize = new GSize(26, 39);
		homeIcon.iconAnchor = new GPoint(13, 39);
		homeIcon.infoWindowAnchor = new GPoint(13, 0);

		// Create location icon
		locKioskIcon = new GIcon();
		locKioskIcon.image = "http://"+top.location.host+"/imgs/markers/location_kiosk/location_kiosk_icon.png";
		locKioskIcon.shadow = "http://"+top.location.host+"/imgs/markers/location_kiosk/location_kiosk_icon_shadow.png";
		locKioskIcon.transparent = "http://"+top.location.host+"/imgs/markers/location_kiosk/location_kiosk_icon_transparent.png";
		locKioskIcon.iconSize = new GSize(26, 39);
		locKioskIcon.shadowSize = new GSize(26, 39);
		locKioskIcon.iconAnchor = new GPoint(13, 39);
		locKioskIcon.infoWindowAnchor = new GPoint(13, 0);

		// Create location icon
		locWirelessIcon = new GIcon();
		locWirelessIcon.image = "http://"+top.location.host+"/imgs/markers/location_wireless/location_wireless_icon.png";
		locWirelessIcon.shadow = "http://"+top.location.host+"/imgs/markers/location_wireless/location_wireless_icon_shadow.png";
		locWirelessIcon.transparent = "http://"+top.location.host+"/imgs/markers/location_wireless/location_wireless_icon_transparent.png";
		locWirelessIcon.iconSize = new GSize(26, 39);
		locWirelessIcon.shadowSize = new GSize(26, 39);
		locWirelessIcon.iconAnchor = new GPoint(13, 39);
		locWirelessIcon.infoWindowAnchor = new GPoint(13, 0);
		
		// Create the importance tracking (needed to stack home icon on top
		importance = 1;
		
		// Reset result set
		$('#result_set').html("");
		
	    // Retrieve location information, pass it to addToMap()
	    geocoder.getLatLng (
	    	    address,
	    	    function(point) {
	    	// If the address is found, add it to the map and load nearby stores
			if (point) {
				// Remove all the markers
				map.clearOverlays();
				
				// Add map marker
				map.setCenter(point, 15);
				
				// Add to bounds
				bounds.extend(point);
				
				// do ajax request to find nearby stores
				$.ajax({
					type:"POST",
					url:$('#store_locator').attr('action'),
					data:"ajax=1&action=get_nearby_stores&distance="+distance+"&lat="+point.lat()+"&lng="+point.lng(),
					success:function(msg) {
						// parse the JSON result
						if(!JSON) alert("JSON Not Supported");
						var results = JSON.parse(msg);
						// if request successful
						if( results.success ) {
							// Count results
							var i = 0;
							// loop through stores and display marker
							jQuery.each( results.stores,function(k,v){
								// Count Location
								i++;
								
								// Create location
								geolocation = new GLatLng(v.latitude,v.longitude);

								// Choose Icon
								var markerIcon = null;
								switch( v.vendor ) {
									case "RL":
									case "TT":
										markerIcon = locWirelessIcon;
										break;
									default:
										markerIcon = locKioskIcon;
								}
								
								
								// Create and add marker
								var locMarker = new GMarker(geolocation,{title:v.name,icon:markerIcon,zIndexProcess:importanceOrder});
								locMarker.importance = 2;
								map.addOverlay(locMarker);
								
								// Format the phone number
								if( v.phone == '0000000000' ) {
									var digits = "N/A";
								} else {
									var digits = "("+v.phone.substring(0,3)+") "+v.phone.substring(3,6)+"-"+v.phone.substring(6);
								}
								
								// Format postal code
								if( v.country == 'US' ) {
									while( v.zip.length < 5 ) {
										v.zip = '0'+v.zip;
									}
								}

								// Set the type emblem
								switch( v.type ) {
									case "Convention":
										var type = "convention";
										break;
									case "Airport":
										var type = "airport";
										break;
									default:
										var type = "hotel";
										break;
								}
								
								// Set the service emblem
								switch( v.vendor ) {
									case "SC":
										var service = "bizcenter";
										break;
									default:
										var service = "wireless";
										break;
								}
								
								// Add the info window data
								GEvent.addListener(locMarker, 'click', function() {
									var markup =  '<table><tr><td>';
										markup += '<div class="infoWindowImg"><img src="http://'+top.location.host+'/imgs/hotels/'+v.id+'.jpg" /></div>';
										markup += '</td><td>';
										markup += '<div class="infoWindowData"><span class="name">'+v.name+'</span><br />';
										markup += '<span class="address1">'+v.address1+'</span><br />';
										markup += '<span class="address2">'+v.city+', '+v.state+' '+v.zip+'</span><br />';
										markup += '<span class="distance">'+v.distance+' miles</span></div>';
										markup += '<img class="type" src="http://'+top.location.host+'/imgs/emblems/'+type+'_emblem.png" alt="'+type+'"/><img class="service" src="http://'+top.location.host+'/imgs/emblems/'+service+'_emblem.png" alt="'+service+'"/></td>';
										markup += '</div></td></tr></table>';
									locMarker.openInfoWindowHtml(markup);
								});  
								
								// Extend bounds
								bounds.extend(geolocation);
								
								// Add result to result set
								var	markup = '<div class="result">'
									markup += '<ul>'
									markup += '<li class="box1"></li>';
									markup += '<li class="box2"><img class="main" src="http://'+top.location.host+'/imgs/hotels/'+v.id+'.jpg"" alt="" /></li>';
									markup += '<li class="box3"><span class="name">'+i+'. '+v.name+'</span><br /><span class="address1">'+v.address1+'</span><br /><span class="address2">'+v.city+', '+v.state+' '+v.zip+'</span></li>';
									markup += '<li class="box4"><span class="phone"><strong>Phone:</strong> '+digits+'</span></br /><br /><img class='+type+' src="http://'+top.location.host+'/imgs/emblems/'+type+'_emblem.png" alt='+type+' /><img class='+service+' src="http://'+top.location.host+'/imgs/emblems/'+service+'_emblem.png" alt='+service+' /></span></li>';
									markup += '<li class="box5"><span class="distance">'+v.distance+' miles</span></li>';
									markup += '</ul></div>';
								$('#result_set').append(markup);
							});

							// Add the starting point
							homeMarker = new GMarker(point,{title:'Your Selected Location',icon:homeIcon,zIndexProcess:importanceOrder});
							homeMarker.importance = 10;
							map.addOverlay(homeMarker);
							
							// Adjust map zoom and center
							 map.setCenter(bounds.getCenter(),map.getBoundsZoomLevel(bounds));
							
							$('#ajax_msg').html("<p class='flash_good'>"+results.stores.length+" locations have been found</p>").fadeIn();
						} else {
							// Add the starting point
							homeMarker = new GMarker(point,{title:'Your Selected Location',icon:homeIcon,zIndexProcess:importanceOrder});
							homeMarker.importance = 10;
							map.addOverlay(homeMarker);

							// display error message
							$('#ajax_msg').html("<p class='flash_bad'>"+results.msg+"</p>").fadeIn();
						}
					}
				});				
			}
		});
	}
}