$(function() {
    $("label.required").append(" <small>(Required)</small>");
	Cufon.replace('h2');
	Cufon.replace('h3');
	Cufon.replace('#header .last');
	Cufon.replace('#current-season a span');
	Cufon.replace('#footer h4');
	$(".clicker").focus(function() {
	   $(this).removeClass("clicker");
       $(this).val("");
       $(this).unbind("click");
    });
    
    if ($("body").attr("id") == "pages-index") {
        $("#widget").show();
        prev_next(currentShows[startShow]);
    }
    
    $('#nav li').hover(function() {
        if (obj) {
            if(document.all) {
                obj.find('ul').hide();
            } else {
                obj.find('ul').fadeOut('fast');
            }
        obj = null;
        } //if

        if(document.all) {
            $(this).find('ul').show();
        } else {
            $(this).find('ul').fadeIn('fast');
        }
    }, function() {
    obj = $(this);
    setTimeout(
        "checkHover()",
        400);
    });
    
    $("#hider").click(function() {
       $("#next, #previous").hide();
       $("#widget").slideToggle("slow", function() {
           if ($(this).css("display") != "block") {
               $("#widget").text("");
           } else {
               prev_next(currentShows[startShow]);
           }
       });
    });
    
    $("blockquote").find("p:last").addClass("bottom");
    
    $("#trustee").each(function() {
        if($(this).val()) {
            $("html, body").scrollTo("#trustee_"+$(this).val());
        }
    });    
    $("#biography").each(function() {
        if($(this).val()) {
            $("html, body").scrollTo("#biography_"+$(this).val());
        }
    });
});

function isDefined(object) {
    return (typeof(eval(object)) != 'undefined');
}

var obj = null;

function checkHover() {
    if (obj) {
        if(document.all) {
            obj.find('ul').hide();
        } else {
            obj.find('ul').fadeOut('fast');
        }
    } //if
} //checkHover
 
function prev_next (id) {
    $("#widget").load("/shows/random/"+id, null, function() {
        Cufon.replace('#widget h4');
        $("#widget div p, #widget div img, #widget div h4").hide();
        $("#widget div p, #widget div img, #widget div h4").fadeIn("slow");
        $("#next, #previous").fadeIn("slow");
        $("#next, #previous").unbind("click");
        $("#next").click(function() {
          prev_next(next(id));
        });
        $("#previous").click(function() {
          prev_next(prev(id));
        });   
        $('#nav ul ul').children('li').each(function(i){
              jQuery(this).css({"z-index":30000000-i});
              // jQuery(this).css({"display":"none"});
        }); 
    });
}

function prev(current) {
    for (var i = currentShows.length - 1; i >= 0; i--){
        if (currentShows[i] == current) {
            if (i == 0) {
               return currentShows[currentShows.length -1];
            } else {
                return currentShows[i-1];               
            }
        };
    };
}

function next(current) {
    for (var i = currentShows.length - 1 ; i >= 0; i--){
        if (currentShows[i] == current) {
            if (i == currentShows.length - 1) { // items[2] when the length is 3
              return currentShows[ 0 ];
            } else {
              return currentShows[ i + 1 ];
            }
        };
    };
}

var ThreeMen = {

	office: null,
	map: null,
	icon: null,
	marker: null,
	directionsPanel: null,
	directions: null,

	debug: function(str) {
		var console = window.console || false;
		if(console) {
			if(console.debug) {
				console.debug(str);
			} else if(console.log) {
				console.log(str);
			}
		}
	},

	init: function() {
		ThreeMen.office = new GLatLng(50.840717,-1.777682);
	},


	load: function() {
		// Initialise the map data
		ThreeMen.map = new GMap2(
			document.getElementById("map"),
			{mapTypes:[G_HYBRID_MAP, G_NORMAL_MAP]}
		);
		with(ThreeMen.map) {
			addControl(new GSmallZoomControl());
			// addControl(new GMapTypeControl());
			enableContinuousZoom();
			enableScrollWheelZoom();
		}
		ThreeMen.icon = new GIcon(G_DEFAULT_ICON, '/images/marker.png');
		with(ThreeMen.icon) {
			shadow = '/images/marker_shadow.png';
			iconSize = new GSize(32,32);
			shadowSize = new GSize(59,32);
			iconAnchor = new GPoint(5, 26);
			transparent = null;
			mozPrintImage = null;
			printImage = null;
			printShadow = null;
		}
		ThreeMen.marker = new GMarker(ThreeMen.office, {icon: ThreeMen.icon})
		// Set the map to its initial state
		ThreeMen.resetMap(ThreeMen.map);

		ThreeMen.directionsPanel = document.getElementById("map_directions_text");
		ThreeMen.directions = new GDirections(ThreeMen.map, ThreeMen.directionsPanel);
		with(GEvent) {
			addListener(ThreeMen.directions, 'error', ThreeMen.directionsUnsuccessful);
			addListener(ThreeMen.directions, 'load', ThreeMen.directionsSuccessful);
		}
	},

	Google: {
		// Geocodes a UK location by performing a Google local search and taking the
		//     location of the first result.
		// 
		// The search is asynchronous and the result will be passed as a GLatLng to
		//     the supplied callback function. null will be passed if no matching result
		//     could be found.
		geocode: function(place, callback) {
			ThreeMen.debug("Geocoding");
			var localSearch = new GlocalSearch();
			localSearch.setSearchCompleteCallback(null,
				function() {
					if (localSearch.results[0]) {
						var resultLat = localSearch.results[0].lat;
						var resultLng = localSearch.results[0].lng;
						var point = new GLatLng(resultLat,resultLng);
						callback(point);
					} else {
						callback(null);
					}
				}
			);

			localSearch.execute(place + ", UK");
		}
	},

	// Recentre the map on the ThreeMenmedia office
	resetMap: function() {
		ThreeMen.debug("Resetting map");
		with(ThreeMen.map) {
			if(ThreeMen.directions) {
				ThreeMen.directions.clear();
			}
			checkResize();
			setCenter(ThreeMen.office, 16);
			setMapType(G_HYBRID_MAP);
			removeOverlay(ThreeMen.marker);
			addOverlay(ThreeMen.marker);
			// checkResize();
		}
	},
	
	// Expand the small map to fill a bigger space. Also moves other elements out of
	// the way. Calls the callback function when finished
	expandMap: function(callback) {
		ThreeMen.debug("Expanding map");
		ThreeMen.map.removeOverlay(ThreeMen.marker);
		
		// Need a bigger container to fit the expanded map and directions panel
		$("#map_container").css({width: "870px", marginLeft: "-540px"});

		// a) Grow the map to a bigger size
		$("#map").animate(
			{ width: "500px", height: "440px"},
			800,
			null,
			function() { ThreeMen.map.checkResize(); if(callback){callback()} }
			// Also make the directions panel the same height (although it should still
			//       be 0-width)
		).siblings('#map_directions').animate({ height: "450px" }, 800);

		// b) Push the left-hand side down so there's no overlap
		// 
		// This selector deals with the case when we've got errors from a form
		//     submission on screen
		$(".errorExplanation,#nature").eq(0).animate({ marginTop: "500px" }, 800);
	},

	// Shrink the map back into its small spot, and hide the directions panel if
	// required
	contractMap: function(callbackFunc) {
		ThreeMen.debug("Contracting map");
	 // If someone clicks on a directions waypoint the infowindow opens and
	 // doesn't close again by itself even when directions.clear is called
		ThreeMen.map.closeInfoWindow();
		ThreeMen.hideDirectionsPanel(function() {
			$("#map_directions").animate({ height: "200px" }, 500)
			$("#map").animate({ width: "320px", height: "190px" }, 500, null, function() {
				ThreeMen.resetMap();
				$("#map_container").css({width: "330px", marginLeft: "0px"});
				if(callbackFunc){callbackFunc();}
			});

			// This selector deals with the case when we've got errors from a form
			//     submission on screen
			$(".errorExplanation,#nature").eq(0).animate({ marginTop: "0px" }, 500, null, function() {
			});
		});
	},
	
	showDirectionsPanel: function(callback) {
		ThreeMen.debug("Showing directions panel");
		$("#map_directions_container").css("overflow", "hidden");
		$("#map_directions").animate({ width: "360px" }, 500, null, function() {
		  $("#map_directions_container").css("overflow", "auto");
		  if(callback) {
  		  callback();
		  }
		})
	},
	
	hideDirectionsPanel: function(callback) {
		ThreeMen.debug("Hiding directions panel");
    $("#map_directions_container").css("overflow", "hidden");
		$("#map_directions").animate({ width: "0px" }, 500, null, callback)
	},
	
	showLoading: function() {
		// TODO: Show a "loading" indicator
		// e.g. replace the Go button with a throbber
	},
	
	hideLoading: function() {
		// TODO: Hide the "loading" indicator
	},	
	
	hideError: function(callback) {
        // $("#map_directions_error").slideUp(150, callback);
	},
	
	showError: function(msg) {
		ThreeMen.debug("Showing error " + msg);
		ThreeMen.hideError(function() {
			$("#map_directions_error p").html(msg);
			$("#map_directions_error").slideDown();
		})
	},
	
	// Called when the user enters a search term
	getDirectionsFrom: function(place) {
		ThreeMen.showLoading();
		ThreeMen.map.closeInfoWindow();
		ThreeMen.hideError();
		ThreeMen.debug("Searching for "+place);
		if(place == ""){
			ThreeMen.contractMap();
			ThreeMen.showError("Please enter something - I don't know where you're coming from!");
			return;
		};
		ThreeMen.hideDirectionsPanel(function() {
			ThreeMen.directions.clear();
			ThreeMen.Google.geocode(place, function(point) {
				if(point) {
					var directionsString = point.y+','+point.x + " to " + ThreeMen.office.y+','+ThreeMen.office.x;
					ThreeMen.directions.load(directionsString);
				} else {
					ThreeMen.directionsUnsuccessful();
				}
			});
		});
	},

	// Called when directions have successfully loaded 
	directionsSuccessful: function() {
		ThreeMen.hideLoading();
		ThreeMen.debug("Directions found");
		ThreeMen.map.setMapType(G_NORMAL_MAP);
		ThreeMen.expandMap(function() {
			ThreeMen.showDirectionsPanel();
			with(ThreeMen.directions) {
        // getMarker(1).hide();
				ThreeMen.map.setCenter(getBounds().getCenter());
				ThreeMen.map.setZoom(ThreeMen.map.getBoundsZoomLevel(getBounds()));
			}
		});
		window.location.hash = '#directions'
		$('#saddr').focus();
	},

	// Called when there's any problem loading directions 
	directionsUnsuccessful: function() {
		ThreeMen.hideLoading();
		error = "We couldn't find directions to ThreeMen from here. Please ensure you"+
		" have supplied a UK location &ndash; a postcode will give best"+
		" results.";

		ThreeMen.contractMap(function() {
			ThreeMen.showError(error);
		});
		
		$('#saddr').blur();
		$('#saddr').focus();
	}
};

$.fn.idle = function(time)
  {
      var o = $(this);
      o.queue(function()
      {
         setTimeout(function()
         {
            o.dequeue();
         }, time);
      });
      return this;              //****
  }