// venue rating set-up
	$(function(){
		
		$("#rat").children().not("select, #rating_title").hide();
		
		// Create caption element
		var $caption = $('<div id="caption"/>');
		
		// Create stars
		$("#rat").stars({
			inputType: "select",
			oneVoteOnly: true,
			captionEl: $caption,
			callback: function(ui, type, value)
			{
				// Display message to the user at the begining of request
				$("#messages").text("Saving...").fadeIn(30);
				
				// Send request to the server using POST method
				/* NOTE: 
					The same PHP script is used for the FORM submission when Javascript is not available.
					The only difference in script execution is the returned value. 
					For AJAX call we expect an JSON object to be returned. 
					The JSON object contains additional data we can use to update other elements on the page.
					To distinguish the AJAX request in PHP script, check if the $_SERVER['HTTP_X_REQUESTED_WITH'] header variable is set.
					(see: demo4.php)
				*/ 
				$.post("/venue_ratings/ajax_vote", {rate: value, venue: venueId }, function(json)
				{
					// Change widget's title
					//$("#rating_title").text("Average rating");
					
					// Select stars from "Average rating" control to match the returned average rating value
					ui.select(Math.round(json.avg));
					
					// Update widget's caption
					$caption.text("Votes: " + json.votes + ", Score: " + json.avg );
					
					// Display confirmation message to the user
					if (json.err_msg)
						$("#messages").text(json.err_msg).stop().css("opacity", 1).fadeIn(30);
					else
						$("#messages").text("Rating saved (" + value + "). Thanks!").stop().css("opacity", 1).fadeIn(30);
							
					// Hide confirmation message after 2 sec...
					setTimeout(function(){
						$("#messages").fadeOut(1000)
					}, 2000);

				}, "json");
			}
		});

		// Since the <option value="3"> was selected by default, we must remove this selection from Stars.
		//$("#rat").stars("selectID", -1);

		// Append caption element !after! the Stars
		$caption.appendTo("#rat");

		// Create element to use for confirmation messages
		$('<div id="messages"/>').appendTo("#rat");
	});
	
/* dialog boxes */
$(document).ready(function(){

	// set-up dialog boxes
	$('#comment_dialog').dialog({ autoOpen: false, width: 355, height: 520, modal: true });
	$('#error_dialog').dialog({ autoOpen: false, width: 355, height: 450, modal: true });
	
	// send recommendation	
	$("#VenueCommentAjaxAddForm").validate({
		submitHandler: function(form) {
			$('form#VenueCommentAjaxAddForm :input[type=submit]').val('Saving...').attr("disabled", "true").fadeOut('slow');
			$(form).ajaxSubmit({
				target: "#viewer_comments",
				success: function() { 
					alert('Thanks for your recommendation! Recommendations will appear shortly.'); $(form).resetForm();
					$('#comment_dialog').dialog('close');
					$('#viewer_comments').fadeIn('slow');
				}
			});
		}
	});

	// send error report , target: "#errorReport_msg",
	$("#VenueErrorAjaxAddForm").validate({
		submitHandler: function(form) {
			$('form#VenueErrorAjaxAddForm :input[type=submit]').val('Saving...').attr("disabled", "true").fadeOut('slow');
			$(form).ajaxSubmit({
				success: function() { 
					alert('Thanks for your error report'); 
					$(form).resetForm();
					$('#error_dialog').dialog('close');
					
					return false;	
				}
			});
		}
	});
	

/* Venue hours */
	// hi-light current day
	// tr#sun td { font-weight: bold; color: black;}
	var d=new Date(); 
	var today = 'day_' + d.getDay() // Sunday = 0;
	$('tr#' + today + ' td strong').removeClass('grey3');
	$('tr#' + today + ' td').css( {'font-weight': 'bold', 'color': 'black'} );


	
	$('.recommend_link').click( function () {
								$('#VenueCommentAddForm').resetForm();
								$('#comment_dialog').dialog('open'); 
								return(false);
							} );
							
	$('#reportError_link').click( function () {
								$('#VenueCommentAddForm').resetForm();
								$('#error_dialog').dialog('open'); 
								return(false);
							} );							


/* nearby venues */
	$('#nearbyVenues_dialog').dialog({ autoOpen: false, width: 530, height: 560, modal: true, resizable: false });
	
	$('.nearbyVenues_link').click( function() {
								$('#nearbyVenues_dialog').dialog('open'); 
								showNearbyVenues();
								$('.ui-widget-overlay').click(function() { $('#nearbyVenues_dialog').dialog("close"); });
								return(false);
							} );

});

/* Support functions for nearby venues on profile page */
function showNearbyVenues() {
		
		if (GBrowserIsCompatible()) { 
			
			// Create a Map
			var map = new GMap2(document.getElementById('search_map'));
			map.setCenter(new GLatLng( venueLatt,venueLong),15);
			map.setUIToDefault();
			
			var points = Array();
			var mapSize = new GLatLngBounds();
			
			// add the current venue to the map 
			var point = new GLatLng( venueLatt, venueLong);
			var marker = new GMarker(point);
			var tooltip = new Tooltip(marker, venueName,5);
			marker.tooltip = tooltip;
			map.addOverlay(marker);
			map.addOverlay(tooltip);

			GEvent.addListener(marker,"mouseover",function(){
				this.tooltip.show();
			});
			GEvent.addListener(marker,"mouseout",function(){
				this.tooltip.hide();
			});			
			
			for (var i=0; i< nearbyVenues.length; i++) {
				var point = new GLatLng( nearbyVenues[i].lat, nearbyVenues[i].lng);
				//console.log( nearbyVenues[i].lat, nearbyVenues[i].lng );
				points.push(point);
				mapSize.extend(point);
				var marker = new GMarker(point);
				
				// now the overlay
				var tooltip = new Tooltip(marker, nearbyVenues[i].label,5);				
				marker.tooltip = tooltip;

				marker.url = nearbyVenues[i].url;
				map.addOverlay(marker);
				map.addOverlay(tooltip);
				
				GEvent.addListener(marker,"click", function() {
				  this.tooltip.hide();
				  location.href = this.url
				});
						
				GEvent.addListener(marker,"mouseover",function(){
					this.tooltip.show();
				});
				GEvent.addListener(marker,"mouseout",function(){
					this.tooltip.hide();
				});
				
			}
			
		bounds = new GBounds( points );		

		zoomLevel = best_zoom( bounds, $('#search_map') );
		zoomLevel = 16 - zoomLevel + 1;

		if ( nearbyVenues.length == 1 )
			zoomLevel = 16;
		
		mapCentre = mapSize.getCenter();
		map.setCenter(mapCentre, zoomLevel );
	}
};

	/**
	 * Utility function to calculate the appropriate zoom level for a
	 * given bounding box and map image size. Uses the formula described
	 * in the Google Mapki (http://mapki.com/).
	 *
	 * @param  bounds  bounding box (GBounds instance)
	 * @param  mnode   DOM element containing the map.
	 * @return         zoom level.
	 */
	function best_zoom(bounds, mnode) {
		var width = $('#search_map').attr('offsetWidth'); //mnode.offsetWidth;
		var height = $('#search_map').attr('offsetHeight'); //mnode.offsetHeig

		var dlat = Math.abs(bounds.maxY - bounds.minY);
		var dlon = Math.abs(bounds.maxX - bounds.minX);
			
		if(dlat == 0 && dlon == 0)
			return 4;
	
		// Center latitude in radians
		var clat = Math.PI*(bounds.minY + bounds.maxY)/360.;
	
		var C = 0.0000107288;
		var z0 = Math.ceil(Math.log(dlat/(C*height))/Math.LN2);
		var z1 = Math.ceil(Math.log(dlon/(C*width*Math.cos(clat)))/Math.LN2);
				
		return (z1 > z0) ? z1 : z0;
	} 	

	// A function to create the marker and set up the event window
	function createMarker(point,name,html) {
		var marker = new GMarker(point);
		return marker;
	}
	
	// -----------------------------------------------------


// Tooltip.js
/**
 * @author Marco Alionso Ramirez, marco@onemarco.com
 * @url http://onemarco.com
 * @version 1.0
 * This code is public domain
 */

/**
 * The Tooltip class is an addon designed for the Google Maps GMarker class. 
 * @constructor
 * @param {GMarker} marker
 * @param {String} text
 * @param {Number} padding
 */

	function Tooltip(marker, text, padding){
		this.marker_ = marker;
		this.text_ = text;
		this.padding_ = padding;
	}

	Tooltip.prototype = new GOverlay();
	
	Tooltip.prototype.initialize = function(map){
		var div = document.createElement("div");
		div.appendChild(document.createTextNode(this.text_));
		div.className = 'tooltip';
		div.style.position = 'absolute';
		div.style.visibility = 'hidden';
		map.getPane(G_MAP_FLOAT_PANE).appendChild(div);
		this.map_ = map;
		this.div_ = div;
	}
	
	Tooltip.prototype.remove = function(){
		this.div_.parentNode.removeChild(this.div_);
	}
	
	Tooltip.prototype.copy = function(){
		return new Tooltip(this.marker_,this.text_,this.padding_);
	}
	
	Tooltip.prototype.redraw = function(force){
		if (!force) return;
		var markerPos = this.map_.fromLatLngToDivPixel(this.marker_.getPoint());
		var iconAnchor = this.marker_.getIcon().iconAnchor;
		var xPos = Math.round(markerPos.x - this.div_.clientWidth / 2);
		var yPos = markerPos.y - iconAnchor.y - this.div_.clientHeight - this.padding_;
		this.div_.style.top = yPos + 'px';
		this.div_.style.left = xPos + 'px';
	}
	
	Tooltip.prototype.show = function(){
		this.div_.style.visibility = 'visible';
	}
	
	Tooltip.prototype.hide = function(){
		this.div_.style.visibility = 'hidden';
	}



	
	
