/*******************************************************************************

	GENERAL

*******************************************************************************/

function popup(url,width,height) 
{
	window.open(url,'popup','width='+width+',height='+height+',scrollbars=yes,resizable=yes,toolbar=no,directories=no,menubar=no,status=no,left=100,top=100');
	return false;
}

/*******************************************************************************

	LIVE SEARCH

*******************************************************************************/

var live_search_escaped = false;
var panel_active        = false;
var observer            = null;
var live_search         = null;

function initSearchBox()
{	
	live_search = new Ajax.LiveSearch('search_box', 'search_results', '/search/live_search', 
		{
			paramName: "value",
			minChars: 2,
			callback: showLiveSearchPanel
		}
	);
	
	$('search_box').onfocus = function() {
		if (this.value == 'Find your next meal...') this.value = '';
		this.style.color = '#333';
		if (window.map) map._disableKeys = true;
	}

	$('search_box').onblur = function() {
		if (live_search.clickWithinSearchPanel()) {
			return false
		}
		else {
			hideLiveSearchPanel();
			if ($('search_box').value != '') return;
			$('search_box').style.color = '#666';
			$('search_box').value = 'Find your next meal...';
			if (window.map) map._disableKeys = false;			
		}
	}	
}

function showLiveSearchPanel(querystring)
{
	if (live_search_escaped == true) {
		live_search_escaped = false;
		return querystring;
	}
	if ($('live_search_panel').style.display == "none") {
		Element.show('live_search_panel');								
		Element.show('search_indicator');		
		live_search_escaped = false;
		panel_active = true;
		
		/* for IE */
		if (document.all && $('picture_this')) {
			$('picture_this').style.zIndex = -1;
		}
		if (document.all && $('welcome_back')) {
			$('welcome_back').style.zIndex = -1;
		}

		observer = Event.observe(window, 'mousedown', live_search.recordMousePosition.bindAsEventListener(live_search));					
	}
	
	return querystring;
}

function hideLiveSearchPanel()
{
	/* for IE */
	if ($('picture_this')) {$('picture_this').style.zIndex = 0;}
	if ($('welcome_back')) {$('welcome_back').style.zIndex = 0;}
	
	Element.hide('live_search_panel');						
	Element.hide('set_location_panel');	
	Event.stopObserving(window, 'mousedown', observer);				
	panel_active = false;
}

function showSetLocationPanel()
{
	Element.hide('search_indicator');
	Element.hide('live_search_results');
	Element.hide('all_results');
	Element.show('live_search_panel');
	Element.show('set_location_panel');
	$('new_location').focus();
}

function cancelSetLocationPanel()
{
	Element.show('live_search_results');
	Element.show('all_results');	
	Element.hide('set_location_panel');
	Element.hide('set_location_error');	
}

function searchWithNewLocation()
{
	Element.hide('set_location_panel');	
	Element.hide('set_location_error');
	Element.show('search_indicator');	
	$('new_location').value = "";
	live_search.getUpdatedChoices();
}

function submitSearchForm()
{
	$('search_form').submit();
}


/*******************************************************************************

	PHOTO PAGE

*******************************************************************************/

function toggleMapOverlay()
{
	if ($('map_overlay').style.display == "none") {
		$('toggle_map_trigger').innerHTML = "Hide map";
		Position.prepare();
		coords = Position.cumulativeOffset($('photo_info'));
		$('map_overlay').style.left = '0px';
		$('map_overlay').style.top   = '19px';
		$('map_overlay').style.display = 'block';
		
		if (map === null) {
			initMap();
		};
	}
	else {
		$('toggle_map_trigger').innerHTML = "Map this photo";
		$('map_overlay').style.display = 'none';
	}
	return false;
}

function observe_flickr_form()
{
	new Form.Element.EventObserver('photoset_id', 
		function(element, value) {
			Element.show('flickr_spinner'); 
			Element.hide('flickr_photoset_photos_wrapper');
			Element.hide('selected_flickr_photo_wrapper');
			
			new Ajax.Request('/photos/show_flickr_photos', {
				asynchronous:true, 
				evalScripts:true, 
				onComplete:function(request) {
					Element.hide('flickr_spinner')
				}, 
				parameters:'id=' + value
			}
		)}, 'change')
}

function showFlickrContainer()
{
	Element.show('flickr_container');
	Element.hide('computer_upload');
	$('uploading_flickr_photo').value = 1;
}

function hideFlickrContainer()
{
	Element.hide('flickr_container');
	Element.show('computer_upload');
	$('uploading_flickr_photo').value = 0;	
}

function chooseDifferentFlickrPhoto()
{
	Element.hide('selected_flickr_photo_wrapper');
	Element.show('flickr_photoset_photos');
}

function showSelectedFlickrPhoto()
{
	showFlickrContainer();
	Element.show('flickr_photoset_photos_wrapper');
  Element.show('selected_flickr_photo_wrapper');
  Element.hide('flickr_photoset_photos');	
}

function setFlickrPhotoID(value)
{
	$('flickr_photo_id').value = value;
}

function setFlickrPhotoUrl(url)
{
	$('flickr_photo_url').value = url;
}

function setFlickrPhotosetId(value)
{
	$('flickr_photoset_id').value = value;
}

function showUploadIndicator()
{
	Element.hide('upload_submit_wrapper');
	Element.show('upload_spinner_wrapper');
}




var geocoder = null;

function initMapHelper()
{
	if (GBrowserIsCompatible()) {
		map      = new GMap2(document.getElementById("map_helper"));
		geocoder = new GClientGeocoder();
	}
	showMapIfPossible();
}

function showMapIfPossible()
{	
	if (searchFieldsPopulated() /* && searchFieldsChanged()*/) {
		geocoder.getLatLng($F('photo_city') + ", " + $F('photo_state'), 
			function(point) {
				$('map_helper').style.backgroundImage = 'none';
				$('map_helper').style.backgroundColor = '#eeeeee';				
				loadMapSearch($F('photo_restaurant'), $F('photo_city') + ", " + $F('photo_state'), point);				
			}
		);
	};	
}

function searchFieldsPopulated()
{
	return ($F('photo_restaurant') != "" && $F('photo_city') != "" && $F('photo_state') != "");
}


function loadMapSearch(restaurant, location, point) 
{		
	map.addControl(new GSmallMapControl());
	var searchControl = new google.maps.LocalSearch(
		{
			searchFormHint : '"' + restaurant + '" loc: ' + location,		
      resultList : document.getElementById("search_results")
    }
	);
	map.addControl(searchControl);
	map.setCenter(point, 12);
	searchControl.formSubmit(searchControl.searchForm);
}

/*******************************************************************************

	MAPS

*******************************************************************************/

var defaultCenterLatitude  = 30.037030;
var defaultCenterLongitude = 10;
var centerLatitude  = null;
var centerLongitude = null;
var startDefaultZoomBig   = 2;
var startDefaultZoomSmall = 0;
var startZoomBig   = null;
var startZoomSmall = null;
var map            = null;
var map_div;

exact_icon = new GIcon();
exact_icon.image = "/images/icons/marker_exact.png";
exact_icon.shadow = "/images/icons/marker_shadow.png";
exact_icon.iconSize = new GSize(36, 40);
exact_icon.shadowSize = new GSize(36, 40);
exact_icon.iconAnchor = new GPoint(11, 40);
exact_icon.infoWindowAnchor = new GPoint(26, 5);

inexact_icon = new GIcon();
inexact_icon.image = "/images/icons/marker_inexact.png";
inexact_icon.shadow = "/images/icons/marker_shadow.png";
inexact_icon.iconSize = new GSize(36, 40);
inexact_icon.shadowSize = new GSize(36, 40);
inexact_icon.iconAnchor = new GPoint(11, 40);
inexact_icon.infoWindowAnchor = new GPoint(26, 5);

small_icon = new GIcon();
small_icon.image = "/images/icons/marker_small.png";
small_icon.iconSize = new GSize(11, 16);
small_icon.iconAnchor = new GPoint(6, 16);
small_icon.infoWindowAnchor = new GPoint(6, 5);


function initMapPage()
{
	map_div = document.getElementById("map_overlay");
}

function initMap()
{	
	map = new GMap2(map_div);
	map.addControl(new GLargeMapControl());
	map.addControl(new LegendControl());
	map.setCenter(new GLatLng(point.lat, point.lng), 12);    
	addMarker(point.lat , point.lng, specificBalloonContent(point), point.geocode_precision, true, "normal");
}

function initBigMap()
{
	if (centerLatitude == null) { centerLatitude = defaultCenterLatitude};
	if (centerLongitude == null) { centerLongitude = defaultCenterLongitude};
	if (startZoomBig == null) { startZoomBig = startDefaultZoomBig};
	
  map = new GMap2(document.getElementById("bigmap"));
  map.addControl(new GLargeMapControl());
  map.addControl(new LegendControl());
  map.setCenter(new GLatLng(centerLatitude, centerLongitude), startZoomBig);
    
  // loop through and add each store to the map
  for(i=0; i < points.length; i++) {
    addMarker(points[i].lat , points[i].lng, generalBalloonContent(points[i]), points[i].geocode_precision, false, "normal");
  }
}

function initSmallMap()
{
	if (centerLatitude == null) { centerLatitude = defaultCenterLatitude};
	if (centerLongitude == null) { centerLongitude = defaultCenterLongitude};
	if (startZoomSmall == null) { startZoomSmall = startDefaultZoomSmall};	
	
  map = new GMap2(document.getElementById("front_map"));
  map.addControl(new GSmallMapControl());
  map.setCenter(new GLatLng(centerLatitude, centerLongitude), startZoomSmall);
    
  // loop through and add each store to the map
  for(i=0; i < points.length; i++) {
    addMarker(points[i].lat , points[i].lng, generalBalloonContent(points[i]), points[i].geocode_precision, false, "small");
  }
}

function addMarker(latitude, longitude, description, precision, showBalloon, marker_size) {
	if (precision == "address" || precision == "zip" || precision == "zip+4") {
		var icon = marker_size == "small" ? small_icon : exact_icon;
  	var marker = new GMarker(new GLatLng(latitude, longitude), icon);		
	}
	else {
		var icon = marker_size == "small" ? small_icon : inexact_icon;		
  	var marker = new GMarker(new GLatLng(latitude, longitude), icon);				
	}

  GEvent.addListener(marker, 'click',
    function() {
      marker.openInfoWindowHtml(description);
    }
  );
  
  map.addOverlay(marker);

	if (showBalloon) {		
		marker.openInfoWindowHtml(specificBalloonContent(point));
	};
}

function generalBalloonContent(point)
{
	html = "";
	html += '<table cellpadding="0" cellspacing="6" border="0" width="100%">';
	html += '<tr>';
	html += '<td width="66" valign="top">';
	html += '<img height="60" width="60" src="' + point.image + '" /><br />';
	html += '<span style="color:#666;">';
	html += ratingToImage(point.rating) + "<br />";
	html += priceRangeToWords(point.meal_price);	
	html += '</span>';
	html += '</td>';
	
	html += '<td valign="top">';
	html += '<span style="font-size:13px;"><a href="/photos/show/'+point.id+'">'+point.name+'</a></span><br />';
	html += '<br />';	
	html += '<strong>' + point.restaurant + "</strong><br />";
	if (point.address != "") {		
		html += point.address + '<br />';
	};
	html += point.city + ', ' + point.state + '<br />'
	html += '<br />';	
	html += '<a href="http://maps.google.com/maps?f=d&hl=en&geocode=&saddr=&daddr=' +
	 				point.address + '+' + point.city + '+' + point.state +
					'&sll=' + point.lat + ',' + point.lng + 
					'&sspn=0.010321,0.01354&ie=UTF8&z=12" target="_blank">Get driving directions</a>';
	
	html += '</td>';
	html += '</tr>';
	html += '</table>';
			
	return html;
}

function priceRangeToWords(meal_price)
{
	html = "";
	
	switch(meal_price) {
		case "5":
			html = "under $5";
			break;
		case "5_10":
			html = "$5-$10";
			break;
		case "10_15":
			html = "$10-$15";
			break;
		case "15_20":
			html = "$15-$20";
			break;
		case "20_30":
			html = "$20-$30";
			break;
		case "30_50":
			html = "$30-$50";
			break;
		case "50":
			html = "$50+";
			break;		
	}
	
	return html;
	
}

function ratingToWords(rating)
{
	html = "";

	switch(parseInt(rating)) {
		case 5:
			html = "&frac12; star";
			break;
		case 10:
			html = "1 star";
			break;			
		case 15:
			html = "1 &frac12; stars";
			break;			
		case 20:
			html = "2 stars";
			break;			
		case 25:
			html = "2 &frac12; stars";
			break;			
		case 30:
			html = "3 stars";
			break;			
		case 35:
			html = "3 &frac12; stars";
			break;			
		case 40:
			html = "4 stars";
			break;			
		case 45:
			html = "4 &frac12; stars";
			break;			
		case 50:
			html = "5 stars";
			break;			
		default:
		 	html = "No rating";
	}
	
	return html;
}

function ratingToImage(rating)
{
	html = '<img src="/images/stars_' + rating + '_sm.gif" />';
	return html;
}

function specificBalloonContent(point)
{
	html = "<strong style='font-size:14px;color:#607315;'>"+point.restaurant+"</strong><br />";
	
	if (point.geocode_precision == "address" || point.geocode_precision == "zip" || point.geocode_precision == "zip+4") {
		html += point.address + "<br />";
		html += point.city + ", " + point.state;		
		html += "<br />";
		html += '<a href="http://maps.google.com/maps?f=d&hl=en&geocode=&saddr=&daddr=' +
		 				point.address + '+' + point.city + '+' + point.state +
						'&sll=' + point.lat + ',' + point.lng + 
						'&sspn=0.010321,0.01354&ie=UTF8&z=12" target="_blank">Get driving directions</a>';
	};

	
	if (point.geocode_precision != "address" && point.geocode_precision != "zip" && point.geocode_precision != "zip+4") {
		html += "<p style='margin-top: 8px;'>The exact address was not entered by the member.</p>";
	}
	return html;
}

function LegendControl() {
}

LegendControl.prototype = new GControl();

LegendControl.prototype.initialize = function(map) {
  var container = document.createElement("div");
  var legend    = document.createElement("div");
  container.appendChild(legend);

  img        = document.createElement("img");
  img.src    = "/images/icons/map_legend.png";
  legend.appendChild(img);

  map.getContainer().appendChild(container);
  return container;
}

LegendControl.prototype.getDefaultPosition = function() {
  return new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(7, 5));
}

/*******************************************************************************

	MISC

*******************************************************************************/

function activateTab(tab, section)
{
	//
	// first, deactivate everything
	//
	var tabs = $A($(section + '_nav').getElementsByTagName('li'));	
	
	tabs.each(function(node){
		Element.removeClassName(node, 'active');
	});

	var panels = $A(Element.getElementsByClassName($(section), section + '_panel'));	
	
	panels.each(function(node){
		Element.hide(node);
	});
	
	//
	// activate the right tab and panel
	//
	$(tab + "_trigger").className = "active";	
	Element.show(tab + "_wrapper");
}
