var hM = {};

hM.TYPE_GF = 'search-user-submitted';
hM.TYPE_YELP = 'search-yelp';
hM.TYPE_FOURSQUARE = 'search-foursquare';
hM.TYPE_GOOGLE = 'search-google';
hM.TYPE_YAHOO = 'search-yahoo';
hM.TYPE_MORE = 'search-more';
hM.CATEGORY_UNKNOWN = 0;
hM.CATEGORY_RESTAURANT = 1;
hM.CATEGORY_BAKERY = 2;
hM.CATEGORY_STORE = 3;
hM.CATEGORY_OTHER = 4;

hM.DEFAULT_LATITUDE = 40.078072;
hM.DEFAULT_LONGITUDE = -101.689453;
hM.DEFAULT_ADDRESS = 'United States';
hM.DEFAULT_ZOOM = 11;

hM.baseUrl = 'http://' + window.location.hostname;
hM.map = null;
hM.markers = [];
hM.infoWindow = null;
hM.geocoder = null;
hM.searchType = hM.TYPE_GF;
hM.zoom = hM.DEFAULT_ZOOM;
hM.location = null;
hM.address = '';
hM.isSearching = true;
hM.searchEnabled = true;

/***
 *
 */
hM.init = function() {
	// initialize tabs and get heights based on viewport size
	hM.loadTabs();
	hM.resize();
	
	// initialize map
	hM.infoWindow = new google.maps.InfoWindow({maxWidth:400});
	var options = {
		zoom: hM.DEFAULT_ZOOM,
		navigationControl: true,
		navigationControlOptions: {
			style: google.maps.NavigationControlStyle.ZOOM_PAN,
			position: google.maps.ControlPosition.LEFT
		},
		mapTypeControl: true,
		mapTypeControlOptions: {
			style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR,
			position: google.maps.ControlPosition.RIGHT
		},
		mapTypeId: google.maps.MapTypeId.ROADMAP
	};
	hM.map = new google.maps.Map(document.getElementById('map'), options);
	
	google.maps.event.addListener(hM.map, 'click', hM.closeInfoWindow);
	google.maps.event.addListener(hM.map, 'tilesloaded', function() {
		//alert('tilesloaded');
		if (hM.isSearching){
			// show location
			if (document.getElementById('txt-location')){
				document.getElementById('txt-location').value = hM.address;
			}
			// get results
			hM.search();
		}
	});
	google.maps.event.addListener(hM.map, 'zoom_changed', function() {
		if (hM.map.getZoom() < 3) {
			hM.map.setZoom(3);
		}
	});

	
	// initialize zoom-search bar
	var zoomSearchControlDiv = document.createElement('DIV');
	var zoomSearchControl = new hM.zoomSearchControl(zoomSearchControlDiv, hM.map);
	zoomSearchControlDiv.index = 1;
	hM.map.controls[google.maps.ControlPosition.TOP_LEFT].push(zoomSearchControlDiv); // set it to both TOP_RIGHT and TOP_LEFT to force google controls down
	hM.map.controls[google.maps.ControlPosition.TOP_RIGHT].push(zoomSearchControlDiv);
	
	// detect and initialize client location
	hM.loadLocation();
	
	// post map initialization
	hM.wireEvents();
};

/***
 *
 */
hM.loadLocation = function() {

	try{
		// get location from cookie
		if (hM.locationFromCookie()){
			hM.getAddressFromCoords(hM.location);

		/*
		// get location from navigator
		} else if (navigator.geolocation){
			try{
				navigator.geolocation.getCurrentPosition(
					function(position) {
						alert('it worked?');
						if (position.coords.latitude && position.coords.longitude){
							hM.location = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
							hM.getAddressFromCoords(hM.location);
						} else {
							hM.handleNoGeolocation();
						}
					}, 
					function() {
						alert('error detecting location');
						hM.handleNoGeolocation();
					}
				);
			} catch(e){
				alert('caught getCurrentPosition error');
				hM.handleNoLocation();
			}
		*/
		// get location from gears
		} else if (google.gears){
			var geo = google.gears.factory.create('beta.geolocation');
			geo.getCurrentPosition(
				function(position) {
					if (position.gearsAddress){
						if (position.gearsAddress.city && position.gearsAddress.region && position.gearsAddress.countryCode){
							hM.address = position.gearsAddress.city + ', ' + position.gearsAddress.region + ', ' + position.gearsAddress.countryCode;
						} else if (position.gearsAddress.city && position.gearsAddress.region){
							hM.address = position.gearsAddress.city + ', ' + position.gearsAddress.region;
						} else if (position.gearsAddress.region && countryCode){
							hM.address = position.gearsAddress.region + ', ' + position.gearsAddress.countryCode;
						} else {
							hM.address = 'Unable to display location address';
						}
					}
					hM.location = new google.maps.LatLng(position.latitude,position.longitude);
					hM.finishLocationLoad();
				}, 
				function() {
					hM.handleNoGeolocation();
				},
				{gearsRequestAddress:true}
			);

		// get location from ClientLocation
		} else if (google.loader.ClientLocation){
			if (google.loader.ClientLocation.latitude && google.loader.ClientLocation.longitude){
				if (google.loader.ClientLocation.address.city) {
					hM.address = google.loader.ClientLocation.address.city;
					if (google.loader.ClientLocation.address.region) {
						hM.address = hM.address + ', ' + google.loader.ClientLocation.address.region;
					}
				} else {
					if (google.loader.ClientLocation.address.region) {
						hM.address = google.loader.ClientLocation.address.region;
					}		
				}
				hM.location = new google.maps.LatLng(google.loader.ClientLocation.latitude,google.loader.ClientLocation.longitude);	
				hM.finishLocationLoad();
			} else {
				hM.handleNoGeolocation();
			}
		
		// nothing worked! load default
		} else {
			hM.handleNoGeolocation();
		}
	}
	catch(e){
		hM.handleNoGeolocation();
	}


};

/***
 *
 */
hM.getAddressFromCoords = function(location){
	if (location) {
		var geocoder = new google.maps.Geocoder();
		geocoder.geocode({'latLng':location}, function(results, status) {
			if (status == google.maps.GeocoderStatus.OK) {
				var city = '';
				var state = '';
				var country = '';
				$.each(results[0].address_components, function(){
					//str +="<li>"+this.types.join(", ")+": "+this.long_name+"</li>";
					if (this.types[0] == 'country') {
						//alert('country: ' + this.short_name);
						country = this.short_name;
					}
					if (this.types[0] == 'administrative_area_level_1') {
						//alert('state: ' + this.short_name);
						state = this.short_name;
					}
					if (this.types[0] == 'locality') {
						//alert('city: ' + this.short_name);
						city = this.short_name;
					}
				});
				if (city && state && country){
					hM.address = city + ', ' + state + ', ' + country;
				} else if (city && state){
					hM.address = city + ', ' + state;
				} else if (state && country){
					hM.address = state + ', ' + country;
				} else {
					hM.address = results[0].formatted_address;
				}
			} else {
				hM.address = '';
			}
			hM.finishLocationLoad();
		});
	} else {
		hM.handleNoGeolocation();
	}
};

/***
 *
 */
hM.handleNoGeolocation = function(){
	hM.location = new google.maps.LatLng(hM.DEFAULT_LATITUDE,hM.DEFAULT_LONGITUDE);
	hM.address = hM.DEFAULT_ADDRESS;
	hM.zoom = 3;
	hM.searchEnabled = false;
	// set center
	hM.map.setCenter(hM.location);
	hM.map.setZoom(hM.zoom);
	// reset zoom in case it was changed from cookie
	hM.zoom = hM.DEFAULT_ZOOM;
};

/***
 *
 */
hM.finishLocationLoad = function(){
	$('#search-results').attr('innerHTML', 'Loading Map...');
	// set center
	hM.map.setCenter(hM.location);
	hM.map.setZoom(hM.zoom);
	// reset zoom in case it was changed from cookie
	hM.zoom = hM.DEFAULT_ZOOM;
	// add search marker
	hM.setSearchMarker(hM.location, hM.address);
};

/***
 *
 */
hM.setSearchMarker = function(location, address){
	if (hM.searchMarker) {
		// move marker, don't create it
		hM.searchMarker.setPosition(location);
		hM.searchMarker.setTitle(address);
	} else {
		// create marker
		var iconImageUrl = 'http://maps.google.com/mapfiles/ms/micons/POI.png';	
		var iconSize = new google.maps.Size(32,32);
		var iconPosition = new google.maps.Point(0, 0);
		var iconHotSpotOffset = new google.maps.Point(24,24);
		var markerImage = new google.maps.MarkerImage(iconImageUrl, iconSize, iconPosition, iconHotSpotOffset);
		hM.searchMarker = new google.maps.Marker({
			map: hM.map, 
			position: location,
			title: address,
			icon: markerImage,
			draggable: false
		});
	}
};

/***
 *
 */
hM.locationFromCookie = function() {
	var result = false;
	if (document.cookie.length>0){
		var key = "p=";
		var vs =document.cookie.indexOf("p=");
		if (vs!=-1){
			vs=vs+key.length;
			var ve=document.cookie.indexOf(";",vs);
			if (ve==-1) {
				ve=document.cookie.length;
			}
			var c = unescape(document.cookie.substring(vs,ve));
			var a = c.split('|');
			// set search location
			hM.location = new google.maps.LatLng(parseFloat(a[0]),parseFloat(a[1]));
			hM.zoom = parseFloat(a[2]);
			// success
			result = true;
		}
	}
	return result;
};

/***
 *
 */
hM.closeInfoWindow = function() {
	hM.infoWindow.close();
};

/***
 *
 */
hM.openInfoWindow = function(marker, result) {
	
	var markerLatLng = marker.getPosition();
	
	// create div element
	var e = document.createElement("div");
	e.style.width = "95%";
	e.className ="placeInfo";

	// format awareness
	var aware = '<div class="awareness">'	
		+ '<span><b>Gluten-Free Awareness</b><br />'	
		+ ((result.gf_menu == 1) ? '<span style="margin-left:5px">&middot;</span> Gluten-Free Menu</span><br />' : '')
		+ ((result.gf_subs == 1) ? '<span style="margin-left:5px">&middot; Special Ordering Instructions</span><br />' : '')
		+ ((result.gf_staff == 1) ? '<span style="margin-left:5px">&middot; Knowledgeable Staff</span><br />' : '')
		+ ((result.gf_cross == 1) ? '<span style="margin-left:5px">&middot; Cross-Contamination Prevention</span><br />' : '')
		+ ((result.gf_total == 1) ? '<span style="margin-left:5px">&middot; 100% Gluten-Free</span><br />' : '')
		+ '</div>';
	// format "more info" link
	var encodedDirections = encodeURI('http://maps.google.com/maps?saddr=&daddr=' + result.address);
	var link = '<p><a href="' + encodedDirections + '" class="udark" target="_blank">directions</a>&nbsp;|&nbsp;<a href="/i/' + result.web_id + '" class="udark">more info...</a></p>';
	
	// build inner html for created div
	var htm = '<div class="venueName" style="padding:10px 0px;">'
	+ '<h1 style="color:#444444;font-size:17px;margin:0px;"><a href="/i/' + result.web_id + '" class="dark">' + result.name + '</a></h1>'
	+ '</div>'
	
	+ '<div style="padding:10px 0px">'
	+ '<p>' + result.address + '</p>'
	+ '<p>' + ((result.country == 'US') ? hM.formatUsPhone(result.phone) : result.phone) + '</p>'
	+ '</div>'
	+ aware
	+ link;
	
	e.innerHTML = htm;
	hM.infoWindow.setContent(e);
	hM.infoWindow.open(hM.map, marker);

};

/***
 *
 */
hM.formatUsPhone = function(ph) {
	var result = '';
	if(ph && ph.length == 10){
		result = '(' + ph.slice(0,3) + ') ' + ph.slice(3,6) + '-' + ph.slice(6,10);
	}
	return result;
};

/***
 *
 */
hM.loadTabs = function() {
	$('.tab-content').hide(); //Hide all content
	$('#tab-strip li:first').addClass('active').show(); //Activate first tab
	$('.tab-content:first').show(); //Show first tab content
	$('#tab-strip li').click(function() {
		$('#tab-strip li').removeClass('active'); //Remove any "active" class
		$(this).addClass('active'); //Add "active" class to selected tab
		$('.tab-content').hide(); //Hide all tab content
		var activeTab = $(this).find('a').attr('href'); //Find the rel attribute value to identify the active tab + content
		$(activeTab).fadeIn(); //Fade in the active content
		hM.changeSearchType($(this).attr('id'));
		return false;
	});
};

/***
 *
 */
hM.changeSearchType = function(searchType) {
	hM.searchType = searchType;
	//hM.logSearchType(searchType);
	hM.search();
};

hM.logSearchType = function(searchType){
	// send the action request to the server
	$.ajax({
		type: 'GET',
		url: hM.baseUrl + '/search/type/' + searchType,
		success: function(actionResponse) {
			return;
		},
		error: function(XMLHttpRequest, textStatus, errorThrown) {
			return;
		}
	});
};

/***
 *
 */
 hM.search = function(){;
	//alert(hM.searchType)
	if (hM.searchEnabled){
		switch(hM.searchType){
			case hM.TYPE_GF:
				hM.gfSearch(500);
				break;
			case hM.TYPE_YELP:
				hM.yelpSearch();
				break;
			case hM.TYPE_GOOGLE:
				hM.googleSearch();
				break;
			case hM.TYPE_FOURSQUARE:
				hM.fsSearch();
				break;
			case hM.TYPE_YAHOO:
				yahoo_search();
				break;
			case hM.TYPE_MORE:
				hM.moreSearch();
				break;
		}
	}
	hM.isSearching = false;
	hM.searchEnabled = true; // turn search back on. we just wanted to stop initial search
 };

/***
 *
 */
hM.gfSearch = function(distance){
	hM.resize();
	hM.clearMap();
	$('#search-results').attr('innerHTML', '');
	if (hM.location){
		hM.insertSearchIndicatorAfter('#title-gf-search');
		// build url
		var url = hM.baseUrl + '/search/map/bounds_min/'
		+ hM.location.lat() + '/'
		+ hM.location.lng() + '/'
		+ hM.map.getBounds().getSouthWest().lat() + '/' 
		+ hM.map.getBounds().getSouthWest().lng() + '/' 
		+ hM.map.getBounds().getNorthEast().lat() + '/'
		+ hM.map.getBounds().getNorthEast().lng() + '/'
		+ distance + '/'
		+ hM.listCategories() + '/'
		+ hM.listTags();
		//alert(url);
		
		// hit the db for some results
		$.getJSON(url, function(places){
		
			// loop through the results and create a marker for each
			if (places.length > 0) {
				for (i=0; i<places.length;i++) {
					var p = hM.place(places[i]);
					hM.addGfSearchResult(i,p);
				}
			} else {
				$('#search-results').attr('innerHTML', 'No results found.');
			}
			hM.removeSearchIndicator('#gf-searching');
		});
	}
 };
 
/***
 *
 */
hM.place = function(r){
	var p = {};
	p.web_id = r.a;
	p.alt_place_id = r.b;
	p.latitude = r.c;
	p.longitude = r.d;
	p.name = r.e;
	p.address = r.f;
	p.phone = r.g;
	p.gf_total = r.h;
	p.gf_menu = r.i;
	p.gf_subs = r.j;
	p.gf_staff = r.k;
	p.gf_cross = r.l;
	p.category = parseInt(r.m);
	p.country = r.n;
	p.phrase = r.o;
	p.distance = r.p;
	p.comment_count = r.q;
	return p;
}; 
 
 /***
 *
 */
 hM.addGfSearchResult = function(i, result){

	//var iconImageUrl = 'http://gmaps-samples.googlecode.com/svn/trunk/markers/green/blank.png';
	//var iconImageUrl = 'http://chart.apis.google.com/chart?cht=mm&chs=24x32&chco=FFFFFF,00E64D,000000&ext=.png';
	var iconImageUrl = hM.categoryImageUrl(result.category, false);
	var iconImageFocusUrl = hM.categoryFocusImageUrl(result.category, false);
	//var iconImageFocusUrl = 'http://chart.apis.google.com/chart?cht=mm&chs=24x32&chco=FFFFFF,DEDEDE,000000&ext=.png';
	var iconSize = new google.maps.Size(24,32);
	var iconPosition = new google.maps.Point(0, 0);
	var iconHotSpotOffset = new google.maps.Point(9, 34); // Should this be (9, 34)?
	var iconShadowOffset = new google.maps.Point(7, 36);

	var iconShadowUrl = 'http://www.google.com/mapfiles/shadow50.png';
	var iconShadowSize = new google.maps.Size(37, 34);
	
	var markerImage = new google.maps.MarkerImage(iconImageUrl, new google.maps.Size(24, 32), iconPosition, iconHotSpotOffset);
	var markerShadow = new google.maps.MarkerImage(iconShadowUrl, iconShadowSize, iconPosition, iconShadowOffset);
	var markerImageFocus = new google.maps.MarkerImage(iconImageFocusUrl, new google.maps.Size(24, 32), iconPosition, iconHotSpotOffset);

	// Third random marker
	var marker = new google.maps.Marker({
		map: hM.map,
		position: new google.maps.LatLng(result.latitude, result.longitude),
		title: result.name + ' - ' + result.address,
		icon: markerImage,
		shadow: markerShadow,
		draggable: false
	});
   
	// Register event listeners to each marker to open a shared info window displaying the marker's position when clicked or dragged.
	google.maps.event.addListener(marker, 'click', function() {
		hM.openInfoWindow(marker, result);
	});
	google.maps.event.addListener(marker, "mouseover", function() {
		marker.setIcon(markerImageFocus);
	});
	google.maps.event.addListener(marker, "mouseout", function() {
		marker.setIcon(markerImage);
	});
	
	hM.markers.push(marker);

	addResultListItem(marker, result);

	function addResultListItem(marker, result){
		var distance = parseFloat(result.distance).toFixed(1);
		var li = document.createElement('li');
		var img = hM.categoryImageUrl(result.category, true);
		li.innerHTML = '<img src="' + img + '" height="16" width="12" />' + result.name + '<span class="distance">' + distance + ' mi</span>';
		google.maps.event.addDomListener(li, 'click', function() {
			google.maps.event.trigger(marker, 'click');
		});
		google.maps.event.addDomListener(li, 'mouseover', function() {
			google.maps.event.trigger(marker, 'mouseover');
		});
		google.maps.event.addDomListener(li, 'mouseout', function() {
			google.maps.event.trigger(marker, 'mouseout');
		});
		document.getElementById('search-results').appendChild(li);
	}
	
};

hM.categoryImageUrl = function(category, isMini){
	var size = '24x32';
	if (isMini){
		size = '12x16';
	}
	var url = 'http://chart.apis.google.com/chart?cht=mm&chs=' + size + '&chco=FFFFFF,CCCCCC,000000&ext=.png';
	switch (category) {
		case hM.CATEGORY_UNKNOWN :
			url = 'http://chart.apis.google.com/chart?cht=mm&chs=' + size + '&chco=FFFFFF,CCCCCC,000000&ext=.png';
			break;
		case hM.CATEGORY_RESTAURANT :
			url = 'http://chart.apis.google.com/chart?cht=mm&chs=' + size + '&chco=FFFFFF,00E64D,000000&ext=.png';
			break;
		case hM.CATEGORY_BAKERY :
			url = 'http://chart.apis.google.com/chart?cht=mm&chs=' + size + '&chco=FFFFFF,E661AC,000000&ext=.png';
			break;
		case hM.CATEGORY_STORE :
			url = 'http://chart.apis.google.com/chart?cht=mm&chs=' + size + '&chco=FFFFFF,F59B0E,000000&ext=.png';
			break;
		case hM.CATEGORY_OTHER :
			url = 'http://chart.apis.google.com/chart?cht=mm&chs=' + size + '&chco=FFFFFF,FDF569,000000&ext=.png';
			break;
	}
	return url;
};
hM.categoryFocusImageUrl = function(category, isMini){
	var size = '24x32';
	if (isMini){
		size = '12x16';
	}
	var url = 'http://chart.apis.google.com/chart?cht=mm&chs=' + size + '&chco=FFFFFF,efefef,000000&ext=.png';
	switch (category) {
		case hM.CATEGORY_UNKNOWN :
			url = 'http://chart.apis.google.com/chart?cht=mm&chs=' + size + '&chco=FFFFFF,efefef,000000&ext=.png';
			break;
		case hM.CATEGORY_RESTAURANT :
			url = 'http://chart.apis.google.com/chart?cht=mm&chs=' + size + '&chco=FFFFFF,82ffab,000000&ext=.png';
			break;
		case hM.CATEGORY_BAKERY :
			url = 'http://chart.apis.google.com/chart?cht=mm&chs=' + size + '&chco=FFFFFF,ffa0d6,000000&ext=.png';
			break;
		case hM.CATEGORY_STORE :
			url = 'http://chart.apis.google.com/chart?cht=mm&chs=' + size + '&chco=FFFFFF,ffc05e,000000&ext=.png';
			break;
		case hM.CATEGORY_OTHER :
			url = 'http://chart.apis.google.com/chart?cht=mm&chs=' + size + '&chco=FFFFFF,fffccd,000000&ext=.png';
			break;
	}
	return url;
};

 /***
  *
  */
 hM.clearMap = function(){
	hM.closeInfoWindow();
	hM.clearMarkers();
 };

 /***
  *
  */ 
 hM.clearMarkers = function(){
	while(hM.markers[0]){
		hM.markers.pop().setMap(null);
	}
 };

 /***
  *
  */  
 hM.listCategories = function(){
	var result = '';
	$('.category').each( function () {
		if (this.checked == true) {
			result += $(this).val() + '-';
		}
	});
	if (result.length > 0) {
		result = result.slice(0,-1);
	} else {
		result = '1-2-3-4';
	}
	return result;
};

/***
 *
 */
hM.listTags = function(){
	var result = '';
	var e = document.getElementById('gf-txt-filter');
	if(e){
		result = e.value.replace('-','_');
		result = result.replace(' ','-');
	}
	return result;
};

/***
 *
 */
hM.insertSearchIndicatorAfter = function(selector){
	$('<img id="gf-searching" src="/images/searching.gif" style="vertical-align:text-middle;bottom;margin-left:5px" />').insertAfter(selector);
};

/***
 *
 */
hM.removeSearchIndicator = function(selector){
	$(selector).remove();
};
 
/***
 *
 */
hM.resize = function() {
	var viewport = window.innerHeight ? window.innerHeight : $(window).height();
	//var viewportWidth = window.innerWidth ? window.innerWidth : $(window).width();
	var navBar = $('#site-navbar').height();
	//var socialBar = $('#site-socialbar').height();
	var subHeader = $('#site-subheader').height();
	var banner = $('#site-banner').height();
	var footer = $('#site-footer').height();
	var padding = 52;
	var body = viewport - (navBar + subHeader + banner + footer) - padding;
	$('#page-body').css('height', body);
	$('#page-content').css('height',body-20);
	$('#map-panel').css('height', body-20);
	$('#tab-panels').css('height', body-55);
	
	var tabContainerHeight = $('#tab-panels').height();
	
	$('#page-content').css('display', 'block');
	
	var tabHomeHeader = $('#tab-gf-header').height() + 30;
	var tabHomeFilter = $('#tab-gf-filter').height() + 11;
	var tabHomeResults = $('#tab-panels').height() - (tabHomeHeader + tabHomeFilter);
	$('#tab-gf-results').css('height', tabHomeResults);
	
	var tabYelpHeader = $('#tab-yelp-header').height() + 40;
	var tabYelpResults = tabContainerHeight - tabYelpHeader;
	$('#tab-yelp-results').css('height', tabYelpResults);

	/*
	var tabGoogleHeader = $('#tab-google-header').height() + 40;
	var tabGoogleResults = tabContainerHeight - tabGoogleHeader;
	$('#tab-google-results').css('height', tabGoogleResults);
	*/
	
	var tabFsHeader = $('#tab-fs-header').height() + 50;
	var tabFsResults = tabContainerHeight - tabFsHeader;
	$('#tab-fs-results').css('height', tabFsResults);
};

/***
 *
 */
hM.wireEvents = function() {
	// wire up the resize event
	$(window).resize(function(){
		hM.resize();
	});

	$('#searchbar').keypress(function(e){
		keyPress(e);
	});

	// wire up the search event
	$('#btn-gf-refresh').click(function(e) {
		hM.search();
		//searchMapBoundsByLatLng(_searchMarker.getLatLng(), _map.getZoom(), true, false, false, true, true, false);
	});
	
	// wire up the search event
	/*
	$('#btn-location').click(function(e) {
		var a = document.getElementById('txt-location');
		searchAddress(a.value, _zoom, addressCallback);
		//searchByQuery('txt-location',_zoom,true,false);
		//searchMapBoundsByTextbox('txt-location', 11, true, true, false, true, true, false);
	});
	*/
	// wire up the add marker button
	$('#btn-add').click(function(e) {
		e.preventDefault();
		var src = hM.baseUrl + '/dialog/login/place';
		$('<img id="btn-add-hg" src="/images/btn-add-hg.gif" style="margin-left:5px" />').insertAfter('#btn-add-label');
		$.ajax({
			type: "GET",
			url: src,
			dataType:"html",
			success:function(response){
				if (response.length > 0) {
					// open the response as a modal dialog
					$(response).modal({
						overlayClose:true,
						escClose:true
					});
					// handle the cancel button on the allocation form
					$("#modal-login-close").click(function() {
						$.modal.close();
					});
					$("input[name='login-type']").click(function (){
						if ($("input[name='login-type']:checked").val() == "default") {
							$("#login-type-default").show();
							$("#login-type-facebook").hide();
						} else if ($("input[name='login-type']:checked").val() == "facebook") {
							$("#login-type-facebook").show();
							$("#login-type-default").hide();
						}
					});
				} else {
					window.location = hM.baseUrl + '/place/add';
				}
				$('#btn-add-hg').remove();
			},
			error:function (XMLHttpRequest, textStatus, errorThrown){
				$('#btn-add-hg').remove();
				alert("textStatus: " + textStatus);
			}    
		});
	});
};

/**
 * The ZoomSearchControl adds a control to the map that simply
 */
hM.zoomSearchControl = function(controlDiv, map) {

	// Set CSS styles for the DIV containing the control
	// Setting padding to 5 px will offset the control
	// from the edge of the map
	controlDiv.style.padding = '0px';
	controlDiv.style.width = '100%';
	controlDiv.style.height = '34px';
	controlDiv.id = 'zoombar';
	//controlDiv.style.height = '50px';

	// Set CSS for the control border
	var controlOpacity = document.createElement('DIV');
	controlOpacity.id = 'zoombar-op';
	controlDiv.appendChild(controlOpacity);

	var controlContent = document.createElement('DIV');
	controlContent.id = 'zoombar-content';
	controlDiv.appendChild(controlContent);

	var searchbar = document.createElement('DIV');
	searchbar.id = 'searchbar';
	controlContent.appendChild(searchbar);

	var txtLocationWrapper = document.createElement('DIV');
	txtLocationWrapper.id = 'txt-location-wrapper';
	searchbar.appendChild(txtLocationWrapper);

	var txtLocation = document.createElement('INPUT');
	txtLocation.id = 'txt-location';
	txtLocation.type = 'text';
	txtLocation.value = 'Search Location';
	txtLocationWrapper.appendChild(txtLocation);

	var btnLocation = document.createElement('DIV');
	btnLocation.id = 'btn-location';
	btnLocation.innerHTML = 'Search';
	searchbar.appendChild(btnLocation);

	var clear = document.createElement('DIV');
	clear.className = 'clear';
	searchbar.appendChild(clear);

	google.maps.event.addDomListener(btnLocation, 'click', function() {
		hM.searchAddress();
	});

	// Setup the click event listeners: simply set the map to
	// Chicago
	
	google.maps.event.addDomListener(controlDiv, 'keypress', function(e) {
		var id = document.activeElement.id;
		if ((id == 'txt-location')){
			var key;
			if(window.event) {
				key = event.keyCode;
			} else {
				key = e.which;
			}
			if (key == 13) {
				hM.searchAddress();
			}		
		}
	});
};

/**
 *
 */
hM.searchAddress = function(){
	var address = document.getElementById('txt-location').value;
	if (address.length > 0) {
		if (!hM.geocoder) {
			hM.geocoder = new google.maps.Geocoder();
		}
		hM.geocoder.geocode({'address':address}, function(results, status) {
			if (status == google.maps.GeocoderStatus.OK) {
				hM.location = results[0].geometry.location;
				hM.address = address;
				hM.zoom = hM.DEFAULT_ZOOM;
				hM.finishLocationLoad();
				hM.search();
			}
		});
	} else {
		alert("Please enter a location to search!\r\n(ex: address, city, latitude/longitude, etc.)");
		document.getElementById('txt-location').value = 'Enter location...';
	}
};

/**
 * 
 */
hM.unloadMap = function(setCookie){
	if (hM.map){
		//alert('_map is an object');
		if (setCookie === true){
			//alert('setting cookie: ' + _trueLatLng.lat() + ',' + _trueLatLng.lng());
			var latlng = hM.location;
			document.cookie = "p=" 
			+ latlng.lat() + "|" 
			+ latlng.lng() + "|" 
			+ hM.map.getZoom() 
			+ ";expires=";		
		}
		//GUnload();
	}
};

/***
 *
 */
hM.yelpSearch = function(){
	if ($('#yelp').attr('innerHTML') == ''){
		// lazy load the tab container
		_getContainer(hM.baseUrl + '/content/yelp', '#yelp', function(){
			loadScript();
		});
	} else {
		loadScript();
	}
	
	// lazy load the helper script
	function loadScript(){
		if ($('#yelp-help').length){
			doYelpSearch();
		} else {
			_getScript(hM.baseUrl + '/js/yelp.js','yelp-help',function(){
				doYelpSearch();
			});
		}
		hM.resize();
	}
};

/***
 *
 */
hM.googleSearch = function(){
	if ($('#google').attr('innerHTML') == ''){
		// lazy load the tab container
		_getContainer(hM.baseUrl + '/content/google', '#google', function(){
			hM.resize();
			loadScript();
		});
	} else {
		loadScript();
	}
	
	// lazy load the helper script
	function loadScript(){
		if ($('#google-help').length){
			doGoogleSearch();
		} else {
			_getScript(hM.baseUrl + '/js/google.js','google-help',function(){
				doGoogleSearch();
			});
		}
		hM.resize();
	}
};

/***
 *
 */
hM.fsSearch = function(){
	if ($('#foursquare').attr('innerHTML') == ''){
		// lazy load the tab container
		_getContainer(hM.baseUrl + '/content/foursquare', '#foursquare', function(){
			hM.resize();
			loadScript();
		});
	} else {
		loadScript();
	}
	
	// lazy load the helper script
	function loadScript(){
		if ($('#fs-help').length){
			doFsSearch();
		} else {
			_getScript(hM.baseUrl + '/js/fs.js','fs-help',function(){
				doFsSearch();
			});
		}
		hM.resize();
	}
};

/***
 *
 */
hM.moreSearch = function(){
	if ($('#more').attr('innerHTML') == ''){
		// lazy load the tab container
		_getContainer(hM.baseUrl + '/content/more', '#more', function(){
			hM.resize();
		});
	}
};

function _getScript(url,id,callback){
	var head = document.getElementsByTagName('head')[0] || document.documentElement;
	var script = document.createElement('script');
	script.src = url;
	script.type = 'text/javascript';
	script.id = id;

	// Attach handlers for all browsers
	var done = false;
	script.onload = script.onreadystatechange = function() {
		if (!done && (!this.readyState || this.readyState === 'loaded' || this.readyState === 'complete')) {
			done = true;
			callback();
		}
	};
	
	head.appendChild(script);

	// We handle everything using the script element injection
	return undefined;
}

function _getContainer(src,parent,callback){
	$.ajax({
		type:'GET',
		url: src,
		dataType:'html',
		success:function(response){
			if (response.length > 0) {
				$(parent).attr('innerHTML', response);
				callback();
			}
		},
		error:function (XMLHttpRequest, textStatus, errorThrown){
			// do nothing
		}    
	});
}

function gfRegistry(){
	window.location = "http://www.glutenfreeregistry.com/gluten-free-world-map.jsp?params=" + hM.location.lat() + "," + hM.location.lng() + ",0,'ALL'";
}

var _baseUrl = 'http://' + window.location.hostname + '/';
$(function(){
	wireModalLogin();
	hM.init();
});

