// Global Variables
google.load("maps", "2.x");
var map; var address; 
var origin_lat; var origin_lng;

// jQuery code
$(document).ready(function() {
	// Load Google Maps
	map = new google.maps.Map2(document.getElementById("google_map"));
	map.setUIToDefault();
	
	map.setCenter(new google.maps.LatLng(37.4419, -122.1419), 13);
	// Event - Google Map Store Locator submit
	$('div#store_locator input#submit').click(function() {
		// check to make sure either retail or wholesale is selected
		if ($("input[name=brands]").length < 1){ 
			alert('please choose either Retail or Wholesale locations.');
		} else {
			searchLocations();
		}
		
		return false;
	})
	
	// Trigger on form submit, not just submit button click, 
	//     some browsers (IE) doesn't fire if you press enter
	// Event - Google Map Store Locator submit
	$('#storelocator_form').submit(function() {
		// check to make sure either retail or wholesale is selected
		if ($("input[@name='brands']:checked").length < 1){ 
			alert('please choose either Retail or Wholesale locations.');
		} else {
			searchLocations();
		}
		
		return false;
	})
	
});
/**
 * Gets the form's address and geocodes it and submits it to 
 * searchLocationsNear() to find the near by locations.
 **/
function searchLocations() {
	// get the input values
	var address  = $('input#postalcode').val();
	var brand = $('input[name=brands]').val();
	// send the address to Google to Geocode the epicenter
	var geocoder = new GClientGeocoder();
	geocoder.getLatLng(address, function(latlng) {
		if (!latlng) {
			alert(address + ' not found');
		} else {
			searchLocationsNear(latlng, brand);
		}
	});
	return false;
}

/**
 * handleAjaxResponse
 **/
function searchLocationsNear(center, brand) {
	//var radius = document.getElementById('radiusSelect').value;
	var searchUrl = 'closestlocations.php?brands=' + brand + '&lat=' + center.lat() + '&lng=' + center.lng();
	// ---- ---- ---- ---- ---- ---- ----
	// Call the URL and return the data
	// ---- ---- ---- ---- ---- ---- ----
	GDownloadUrl(searchUrl, function(data, responseCode) {
		
		//alert(data);
		
		if(responseCode == 200) {
			/**/
			// ---- ---- ---- ---- ---- ---- ----
			// arse the JSON data
			// ---- ---- ---- ---- ---- ---- ----
			var response = JSON.parse(data);
			var markers = response.markers;
			// -= clear Google Map =-
			map.clearOverlays();
			
			// ---- ---- ---- ---- ---- ---- ----
			// sidebar is the HTML list of results
			// ---- ---- ---- ---- ---- ---- ----
			var sidebar = $('div#map_sidebar');
			sidebar.html('');
			
			// ---- ---- ---- ---- ---- ---- ----
			// No results, notify and set map to a default location
			// ---- ---- ---- ---- ---- ---- ----
			if (markers == null || markers.length == 0) {
				sidebar.html('<p>No results found.</p>');
				map.setCenter(new GLatLng(40, -100), 4);
				return;
			}
			
			var bounds = new GLatLngBounds();
			
			// set pagination variables
			var listlength  = 0;
			var lengthlimit = 6;
			
			// create the first unordered list element
			var ul = $(document.createElement('ul'));
			ul.addClass('gmarker_info');
			// ---- ---- ---- ---- ---- ---- ----
			// start adding markers to the list
			// ---- ---- ---- ---- ---- ---- ----
			for(val in response.markers) { 
				// get the store (loc)ation
				var loc = response.markers[val];
				// get the distance
				loc.distance = parseFloat(loc.distance);
				// create GLatLng point
				var point = new GLatLng(parseFloat(loc.lat), parseFloat(loc.lng));
				// create marker
				var marker = createMarker(point, loc, response.measure);
				// add marker to the map
				map.addOverlay(marker);
				// create the sidebar entry and append to list
				ul.append(createSidebarEntry(marker, loc, response.measure));
				// increment 
				listlength++;
				// set the bounds for the google map
				bounds.extend(point);
				// add list element to the document if it's full and start another one
				if(listlength == lengthlimit) {
					sidebar.append(ul);
					var ul = $(document.createElement('ul'));
					ul.addClass('gmarker_info');
					ul.css('display', 'none');
					listlength = 0;
				}			
			}
			// add any remaining list to the sidebar if there are list elements
			if($('li', ul).size() > 0) {
				sidebar.append(ul);
			}
			// ---- ---- ---- ---- ---- ---- ----
			// Add pagination HTML to sidebar if there's more than one <UL> list
			// ---- ---- ---- ---- ---- ---- ----
			if($('ul', sidebar).size() > 1) {
					sidebar.append(createSidebarPagination());
			}
			// give pagination links active javascript code
			$('div#locator_pagination a').live('click', changeLocatorPage);
			// ---- ---- ---- ---- ---- ---- ----
			// Center map on the results
			// ---- ---- ---- ---- ---- ---- ----
			map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
			//alert(sidebar.html())
			
			//*/
		}
		else if(responseCode == -1) {
			alert("Data request timed out. Please try later.");
		} else { 
			alert("Request resulted in error. Check XML file is retrievable.");
		}

	});
}

/**
 * Creates the GMarker object and sets a GEvent for when the marker is 'click'ed
 **/
function createMarker(point, loc, unitofmeasure) {
	var marker = new GMarker(point);
	GEvent.addListener(marker, 'click', function() {
		marker.openInfoWindowHtml('<div class="gmarker_info">' +  createMarkerInfoHTML(marker, loc, unitofmeasure) + '</div>');
	});
	return marker;
}

/**
 * Creates the HTML div object to insert into the side bar that shows the of locations
 **/
function createSidebarEntry(marker, loc, unitofmeasure) {
	
	var li = document.createElement('li');
	li.innerHTML = createMarkerInfoHTML(marker, loc, unitofmeasure);
	//div.style.cursor = 'pointer';
	li.style.marginBottom = '5px';
	GEvent.addDomListener(li, 'click', function() {
		GEvent.trigger(marker, 'click');
	});
	GEvent.addDomListener(li, 'mouseover', function() {
		li.style.backgroundColor = '#eee';
	});
	GEvent.addDomListener(li, 'mouseout', function() {
		li.style.backgroundColor = '#fff';
	});
	return li;
}

/**
 * Creates the HTML div object that contains the pagination for the number UL 
 * elements in the sidebar.
 **/
function createSidebarPagination(active_page) {
	// Set the default value for active_page
	// A "page" is a <UL> list of results the "active_page" is the one that's currently being shown
	active_page = typeof(active_page) != 'undefined' ? active_page : 1;
	// create the div that will contain the pagination HTML
	var div = $(document.createElement('div'));
	div.attr('id', 'locator_pagination');
	div.prepend('More: ')
	// count the number of "pages" which is equal to the number of UL elements
	var pageCount = $('#map_sidebar ul').size();
	// loop through the number of pages and create the page number elements
	for(var i=1; i<=pageCount; i++) {
		var page;
		if(i==active_page) {
			page = $(document.createElement('span'));
			page.html(i);
		} else {
			page = $(document.createElement('a'));
			page.html(i);
			page.attr('href','#'+i);
		}
		// add some decoration
		pageHTML = page.outerHTML();
		// append to the div
		div.append('[' + pageHTML + '] &nbsp; ');
	}
	
	return div;
}

function changeLocatorPage() {
	var id = parseInt($(this).html());
	//alert('you want me to switch to page ' + id + ' for you?');
	// turn off all pages
	$('#map_sidebar ul').css('display', 'none');
	// turn on new page
	$('#map_sidebar  ul:eq(' + (id-1) + ')').css('display', 'block');
	// change the pagination HTML
	var html = createSidebarPagination(id).html();
	$('div#locator_pagination').html(html);
	return false;
}

/**
 * Creates the HTML that can be used for the store location
 **/
function createMarkerInfoHTML(marker, loc, unitofmeasure) {
	var html = 	'<h4>' + loc.name + '</h4>' +
				'<span>' + loc.address_1 + '</span>' +
				(IsEmpty(loc.address_2) ? '' : '<span>' + loc.address_2 + '</span>') +
				'<span>' + loc.city + ', ' + loc.region + ' ' + loc.postal_code + '</span>' +
				(IsEmpty(loc.phone_1) ? '' : '<span>phone 1: ' + loc.phone_1 + '</span>') +
				(IsEmpty(loc.phone_2) ? '' : '<span>phone 2: ' + loc.phone_2 + '</span>') +
				(IsEmpty(loc.fax) ? '' : '<span>fax: ' + loc.fax + '</span>') +
				(IsEmpty(loc.website) ? '' : '<span>website: <a href="' + loc.website + '" target="_blank">' + loc.website + '</a></span>') +
				'<span>' + loc.distance.toFixed(1) + ' ' + unitofmeasure + '</span>';
	return html;
}

/**
 * Checks to see if a string is empty
 **/
function IsEmpty(sToCheck) {
	if (sToCheck == null || sToCheck.trim() == "") { return true }
	return false
}

/**
 * Removes white space from the front and back of a string.
 **/
String.prototype.trim = function () {
    return this.replace(/^\s*/, "").replace(/\s*$/, "");
}

// -----------------------------------------------------------------------------------------
// Debug Helpers
// -----------------------------------------------------------------------------------------
/**
 * Debug function for printing out an object.
 **/
 var MAX_DEPTH = 4;
function getObjectString(obj, padding, depth) {
	depth = typeof depth == 'undefined' ? 1 : depth;
	if(depth >= MAX_DEPTH) { return ''; }
	var padding = (padding == null) ? "" : padding;
	var str = '';
	for(prop in obj) { 
		str += padding + prop + "[" + typeof obj + "]:";
		if(typeof obj[prop] === 'object') {
			str += getObjectString(obj[prop], padding + "  ", depth++) + "\n";
		} else {
			str += obj[prop] + "\n";
		}
	}
	return str;
}
function printObject(obj, padding) {
	alert(getObjectString(obj, padding));
}
//*/
/*! Copyright (c) 2006 Brandon Aaron (brandon.aaron@gmail.com || http://brandonaaron.net)
* Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
* and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
*/
(function($) {
 // Returns whether or not a result set has results in it
 $.fn.outerHTML = function() {
   return $('<div>').append( this.eq(0).clone() ).html();
 };
})(jQuery);