

/**
 * jQuery lightBox plugin
 * This jQuery plugin was inspired and based on Lightbox 2 by Lokesh Dhakar (http://www.huddletogether.com/projects/lightbox2/)
 * and adapted to me for use like a plugin from jQuery.
 * @name jquery-lightbox-0.5.js
 * @author Leandro Vieira Pinho - http://leandrovieira.com
 * @version 0.5
 * @date April 11, 2008
 * @category jQuery plugin
 * @copyright (c) 2008 Leandro Vieira Pinho (leandrovieira.com)
 * @license CC Attribution-No Derivative Works 2.5 Brazil - http://creativecommons.org/licenses/by-nd/2.5/br/deed.en_US
 * @example Visit http://leandrovieira.com/projects/jquery/lightbox/ for more informations about this jQuery plugin
 */

// Offering a Custom Alias suport - More info: http://docs.jquery.com/Plugins/Authoring#Custom_Alias
(function($) {
	/**
	 * $ is an alias to jQuery object
	 *
	 */
	$.fn.lightBox = function(settings) {
		// Settings to configure the jQuery lightBox plugin how you like
		settings = jQuery.extend({
			// Configuration related to overlay
			overlayBgColor: 		'#000',		// (string) Background color to overlay; inform a hexadecimal value like: #RRGGBB. Where RR, GG, and BB are the hexadecimal values for the red, green, and blue values of the color.
			overlayOpacity:			0.8,		// (integer) Opacity value to overlay; inform: 0.X. Where X are number from 0 to 9
			// Configuration related to navigation
			fixedNavigation:		false,		// (boolean) Boolean that informs if the navigation (next and prev button) will be fixed or not in the interface.
			// Configuration related to images
			imageLoading:			site_domain+'public/images/lightbox/lightbox-ico-loading.gif',		// (string) Path and the name of the loading icon
			imageBtnPrev:			site_domain+'public/images/lightbox/lightbox-btn-prev.gif',			// (string) Path and the name of the prev button image
			imageBtnNext:			site_domain+'public/images/lightbox/lightbox-btn-next.gif',			// (string) Path and the name of the next button image
			imageBtnClose:			site_domain+'public/images/lightbox/lightbox-btn-close.gif',		// (string) Path and the name of the close btn
			imageBlank:				site_domain+'public/images/lightbox/lightbox-blank.gif',			// (string) Path and the name of a blank image (one pixel)
			// Configuration related to container image box
			containerBorderSize:	10,			// (integer) If you adjust the padding in the CSS for the container, #lightbox-container-image-box, you will need to update this value
			containerResizeSpeed:	400,		// (integer) Specify the resize duration of container image. These number are miliseconds. 400 is default.
			// Configuration related to texts in caption. For example: Image 2 of 8. You can alter either "Image" and "of" texts.
			txtImage:				'Image',	// (string) Specify text "Image"
			txtOf:					'of',		// (string) Specify text "of"
			// Configuration related to keyboard navigation
			keyToClose:				'c',		// (string) (c = close) Letter to close the jQuery lightBox interface. Beyond this letter, the letter X and the SCAPE key is used to.
			keyToPrev:				'p',		// (string) (p = previous) Letter to show the previous image
			keyToNext:				'n',		// (string) (n = next) Letter to show the next image.
			// Donīt alter these variables in any way
			imageArray:				[],
			activeImage:			0
		},settings);
		// Caching the jQuery object with all elements matched
		var jQueryMatchedObj = this; // This, in this context, refer to jQuery object
		/**
		 * Initializing the plugin calling the start function
		 *
		 * @return boolean false
		 */
		function _initialize() {
			_start(this,jQueryMatchedObj); // This, in this context, refer to object (link) which the user have clicked
			return false; // Avoid the browser following the link
		}
		/**
		 * Start the jQuery lightBox plugin
		 *
		 * @param object objClicked The object (link) whick the user have clicked
		 * @param object jQueryMatchedObj The jQuery object with all elements matched
		 */
		function _start(objClicked,jQueryMatchedObj) {
			// Hime some elements to avoid conflict with overlay in IE. These elements appear above the overlay.
			$('embed, object, select').css({ 'visibility' : 'hidden' });
			// Call the function to create the markup structure; style some elements; assign events in some elements.
			_set_interface();
			// Unset total images in imageArray
			settings.imageArray.length = 0;
			// Unset image active information
			settings.activeImage = 0;
			// We have an image set? Or just an image? Letīs see it.
			if ( jQueryMatchedObj.length == 1 ) {
				settings.imageArray.push(new Array(objClicked.getAttribute('href'),objClicked.getAttribute('title')));
			} else {
				// Add an Array (as many as we have), with href and title atributes, inside the Array that storage the images references		
				for ( var i = 0; i < jQueryMatchedObj.length; i++ ) {
					settings.imageArray.push(new Array(jQueryMatchedObj[i].getAttribute('href'),jQueryMatchedObj[i].getAttribute('title')));
				}
			}
			while ( settings.imageArray[settings.activeImage][0] != objClicked.getAttribute('href') ) {
				settings.activeImage++;
			}
			// Call the function that prepares image exibition
			_set_image_to_view();
		}
		/**
		 * Create the jQuery lightBox plugin interface
		 *
		 * The HTML markup will be like that:
			<div id="jquery-overlay"></div>
			<div id="jquery-lightbox">
				<div id="lightbox-container-image-box">
					<div id="lightbox-container-image">
						<img src="../fotos/XX.jpg" id="lightbox-image">
						<div id="lightbox-nav">
							<a href="#" id="lightbox-nav-btnPrev"></a>
							<a href="#" id="lightbox-nav-btnNext"></a>
						</div>
						<div id="lightbox-loading">
							<a href="#" id="lightbox-loading-link">
								<img src="../images/lightbox-ico-loading.gif">
							</a>
						</div>
					</div>
				</div>
				<div id="lightbox-container-image-data-box">
					<div id="lightbox-container-image-data">
						<div id="lightbox-image-details">
							<span id="lightbox-image-details-caption"></span>
							<span id="lightbox-image-details-currentNumber"></span>
						</div>
						<div id="lightbox-secNav">
							<a href="#" id="lightbox-secNav-btnClose">
								<img src="../images/lightbox-btn-close.gif">
							</a>
						</div>
					</div>
				</div>
			</div>
		 *
		 */
		function _set_interface() {
			// Apply the HTML markup into body tag
			$('body').append('<div id="jquery-overlay"></div><div id="jquery-lightbox"><div id="lightbox-container-image-box"><div id="lightbox-container-image"><img id="lightbox-image"><div style="" id="lightbox-nav"><a href="#" id="lightbox-nav-btnPrev"></a><a href="#" id="lightbox-nav-btnNext"></a></div><div id="lightbox-loading"><a href="#" id="lightbox-loading-link"><img src="' + settings.imageLoading + '"></a></div></div></div><div id="lightbox-container-image-data-box"><div id="lightbox-container-image-data"><div id="lightbox-image-details"><span id="lightbox-image-details-caption"></span><span id="lightbox-image-details-currentNumber"></span></div><div id="lightbox-secNav"><a href="#" id="lightbox-secNav-btnClose"><img src="' + settings.imageBtnClose + '"></a></div></div></div></div>');	
			// Get page sizes
			var arrPageSizes = ___getPageSize();
			// Style overlay and show it
			$('#jquery-overlay').css({
				backgroundColor:	settings.overlayBgColor,
				opacity:			settings.overlayOpacity,
				width:				arrPageSizes[0],
				height:				arrPageSizes[1]
			}).fadeIn();
			// Get page scroll
			var arrPageScroll = ___getPageScroll();
			// Calculate top and left offset for the jquery-lightbox div object and show it
			$('#jquery-lightbox').css({
				top:	arrPageScroll[1] + (arrPageSizes[3] / 10),
				left:	arrPageScroll[0]
			}).show();
			// Assigning click events in elements to close overlay
			$('#jquery-overlay,#jquery-lightbox').click(function() {
				_finish();									
			});
			// Assign the _finish function to lightbox-loading-link and lightbox-secNav-btnClose objects
			$('#lightbox-loading-link,#lightbox-secNav-btnClose').click(function() {
				_finish();
				return false;
			});
			// If window was resized, calculate the new overlay dimensions
			$(window).resize(function() {
				// Get page sizes
				var arrPageSizes = ___getPageSize();
				// Style overlay and show it
				$('#jquery-overlay').css({
					width:		arrPageSizes[0],
					height:		arrPageSizes[1]
				});
				// Get page scroll
				var arrPageScroll = ___getPageScroll();
				// Calculate top and left offset for the jquery-lightbox div object and show it
				$('#jquery-lightbox').css({
					top:	arrPageScroll[1] + (arrPageSizes[3] / 10),
					left:	arrPageScroll[0]
				});
			});
		}
		/**
		 * Prepares image exibition; doing a imageīs preloader to calculate itīs size
		 *
		 */
		function _set_image_to_view() { // show the loading
			// Show the loading
			$('#lightbox-loading').show();
			if ( settings.fixedNavigation ) {
				$('#lightbox-image,#lightbox-container-image-data-box,#lightbox-image-details-currentNumber').hide();
			} else {
				// Hide some elements
				$('#lightbox-image,#lightbox-nav,#lightbox-nav-btnPrev,#lightbox-nav-btnNext,#lightbox-container-image-data-box,#lightbox-image-details-currentNumber').hide();
			}
			// Image preload process
			var objImagePreloader = new Image();
			objImagePreloader.onload = function() {
				$('#lightbox-image').attr('src',settings.imageArray[settings.activeImage][0]);
				// Perfomance an effect in the image container resizing it
				_resize_container_image_box(objImagePreloader.width,objImagePreloader.height);
				//	clear onLoad, IE behaves irratically with animated gifs otherwise
				objImagePreloader.onload=function(){};
			};
			objImagePreloader.src = settings.imageArray[settings.activeImage][0];
		};
		/**
		 * Perfomance an effect in the image container resizing it
		 *
		 * @param integer intImageWidth The imageīs width that will be showed
		 * @param integer intImageHeight The imageīs height that will be showed
		 */
		function _resize_container_image_box(intImageWidth,intImageHeight) {
			// Get current width and height
			var intCurrentWidth = $('#lightbox-container-image-box').width();
			var intCurrentHeight = $('#lightbox-container-image-box').height();
			// Get the width and height of the selected image plus the padding
			var intWidth = (intImageWidth + (settings.containerBorderSize * 2)); // Plus the imageīs width and the left and right padding value
			var intHeight = (intImageHeight + (settings.containerBorderSize * 2)); // Plus the imageīs height and the left and right padding value
			// Diferences
			var intDiffW = intCurrentWidth - intWidth;
			var intDiffH = intCurrentHeight - intHeight;
			// Perfomance the effect
			$('#lightbox-container-image-box').animate({ width: intWidth, height: intHeight },settings.containerResizeSpeed,function() { _show_image(); });
			if ( ( intDiffW == 0 ) && ( intDiffH == 0 ) ) {
				if ( $.browser.msie ) {
					___pause(250);
				} else {
					___pause(100);	
				}
			} 
			$('#lightbox-container-image-data-box').css({ width: intImageWidth });
			$('#lightbox-nav-btnPrev,#lightbox-nav-btnNext').css({ height: intImageHeight + (settings.containerBorderSize * 2) });
		};
		/**
		 * Show the prepared image
		 *
		 */
		function _show_image() {
			$('#lightbox-loading').hide();
			$('#lightbox-image').fadeIn(function() {
				_show_image_data();
				_set_navigation();
			});
			_preload_neighbor_images();
		};
		/**
		 * Show the image information
		 *
		 */
		function _show_image_data() {
			$('#lightbox-container-image-data-box').slideDown('fast');
			$('#lightbox-image-details-caption').hide();
			if ( settings.imageArray[settings.activeImage][1] ) {
				$('#lightbox-image-details-caption').html(settings.imageArray[settings.activeImage][1]).show();
			}
			// If we have a image set, display 'Image X of X'
			if ( settings.imageArray.length > 1 ) {
				$('#lightbox-image-details-currentNumber').html(settings.txtImage + ' ' + ( settings.activeImage + 1 ) + ' ' + settings.txtOf + ' ' + settings.imageArray.length).show();
			}		
		}
		/**
		 * Display the button navigations
		 *
		 */
		function _set_navigation() {
			$('#lightbox-nav').show();

			// Instead to define this configuration in CSS file, we define here. And itīs need to IE. Just.
			$('#lightbox-nav-btnPrev,#lightbox-nav-btnNext').css({ 'background' : 'transparent url(' + settings.imageBlank + ') no-repeat' });
			
			// Show the prev button, if not the first image in set
			if ( settings.activeImage != 0 ) {
				if ( settings.fixedNavigation ) {
					$('#lightbox-nav-btnPrev').css({ 'background' : 'url(' + settings.imageBtnPrev + ') left 15% no-repeat' })
						.unbind()
						.bind('click',function() {
							settings.activeImage = settings.activeImage - 1;
							_set_image_to_view();
							return false;
						});
				} else {
					// Show the images button for Next buttons
					$('#lightbox-nav-btnPrev').unbind().hover(function() {
						$(this).css({ 'background' : 'url(' + settings.imageBtnPrev + ') left 15% no-repeat' });
					},function() {
						$(this).css({ 'background' : 'transparent url(' + settings.imageBlank + ') no-repeat' });
					}).show().bind('click',function() {
						settings.activeImage = settings.activeImage - 1;
						_set_image_to_view();
						return false;
					});
				}
			}
			
			// Show the next button, if not the last image in set
			if ( settings.activeImage != ( settings.imageArray.length -1 ) ) {
				if ( settings.fixedNavigation ) {
					$('#lightbox-nav-btnNext').css({ 'background' : 'url(' + settings.imageBtnNext + ') right 15% no-repeat' })
						.unbind()
						.bind('click',function() {
							settings.activeImage = settings.activeImage + 1;
							_set_image_to_view();
							return false;
						});
				} else {
					// Show the images button for Next buttons
					$('#lightbox-nav-btnNext').unbind().hover(function() {
						$(this).css({ 'background' : 'url(' + settings.imageBtnNext + ') right 15% no-repeat' });
					},function() {
						$(this).css({ 'background' : 'transparent url(' + settings.imageBlank + ') no-repeat' });
					}).show().bind('click',function() {
						settings.activeImage = settings.activeImage + 1;
						_set_image_to_view();
						return false;
					});
				}
			}
			// Enable keyboard navigation
			_enable_keyboard_navigation();
		}
		/**
		 * Enable a support to keyboard navigation
		 *
		 */
		function _enable_keyboard_navigation() {
			$(document).keydown(function(objEvent) {
				_keyboard_action(objEvent);
			});
		}
		/**
		 * Disable the support to keyboard navigation
		 *
		 */
		function _disable_keyboard_navigation() {
			$(document).unbind();
		}
		/**
		 * Perform the keyboard actions
		 *
		 */
		function _keyboard_action(objEvent) {
			// To ie
			if ( objEvent == null ) {
				keycode = event.keyCode;
				escapeKey = 27;
			// To Mozilla
			} else {
				keycode = objEvent.keyCode;
				escapeKey = objEvent.DOM_VK_ESCAPE;
			}
			// Get the key in lower case form
			key = String.fromCharCode(keycode).toLowerCase();
			// Verify the keys to close the ligthBox
			if ( ( key == settings.keyToClose ) || ( key == 'x' ) || ( keycode == escapeKey ) ) {
				_finish();
			}
			// Verify the key to show the previous image
			if ( ( key == settings.keyToPrev ) || ( keycode == 37 ) ) {
				// If weīre not showing the first image, call the previous
				if ( settings.activeImage != 0 ) {
					settings.activeImage = settings.activeImage - 1;
					_set_image_to_view();
					_disable_keyboard_navigation();
				}
			}
			// Verify the key to show the next image
			if ( ( key == settings.keyToNext ) || ( keycode == 39 ) ) {
				// If weīre not showing the last image, call the next
				if ( settings.activeImage != ( settings.imageArray.length - 1 ) ) {
					settings.activeImage = settings.activeImage + 1;
					_set_image_to_view();
					_disable_keyboard_navigation();
				}
			}
		}
		/**
		 * Preload prev and next images being showed
		 *
		 */
		function _preload_neighbor_images() {
			if ( (settings.imageArray.length -1) > settings.activeImage ) {
				objNext = new Image();
				objNext.src = settings.imageArray[settings.activeImage + 1][0];
			}
			if ( settings.activeImage > 0 ) {
				objPrev = new Image();
				objPrev.src = settings.imageArray[settings.activeImage -1][0];
			}
		}
		/**
		 * Remove jQuery lightBox plugin HTML markup
		 *
		 */
		function _finish() {
			$('#jquery-lightbox').remove();
			$('#jquery-overlay').fadeOut(function() { $('#jquery-overlay').remove(); });
			// Show some elements to avoid conflict with overlay in IE. These elements appear above the overlay.
			$('embed, object, select').css({ 'visibility' : 'visible' });
		}
		/**
		 / THIRD FUNCTION
		 * getPageSize() by quirksmode.com
		 *
		 * @return Array Return an array with page width, height and window width, height
		 */
		function ___getPageSize() {
			var xScroll, yScroll;
			if (window.innerHeight && window.scrollMaxY) {	
				xScroll = window.innerWidth + window.scrollMaxX;
				yScroll = window.innerHeight + window.scrollMaxY;
			} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
				xScroll = document.body.scrollWidth;
				yScroll = document.body.scrollHeight;
			} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
				xScroll = document.body.offsetWidth;
				yScroll = document.body.offsetHeight;
			}
			var windowWidth, windowHeight;
			if (self.innerHeight) {	// all except Explorer
				if(document.documentElement.clientWidth){
					windowWidth = document.documentElement.clientWidth; 
				} else {
					windowWidth = self.innerWidth;
				}
				windowHeight = self.innerHeight;
			} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
				windowWidth = document.documentElement.clientWidth;
				windowHeight = document.documentElement.clientHeight;
			} else if (document.body) { // other Explorers
				windowWidth = document.body.clientWidth;
				windowHeight = document.body.clientHeight;
			}	
			// for small pages with total height less then height of the viewport
			if(yScroll < windowHeight){
				pageHeight = windowHeight;
			} else { 
				pageHeight = yScroll;
			}
			// for small pages with total width less then width of the viewport
			if(xScroll < windowWidth){	
				pageWidth = xScroll;		
			} else {
				pageWidth = windowWidth;
			}
			arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight);
			return arrayPageSize;
		};
		/**
		 / THIRD FUNCTION
		 * getPageScroll() by quirksmode.com
		 *
		 * @return Array Return an array with x,y page scroll values.
		 */
		function ___getPageScroll() {
			var xScroll, yScroll;
			if (self.pageYOffset) {
				yScroll = self.pageYOffset;
				xScroll = self.pageXOffset;
			} else if (document.documentElement && document.documentElement.scrollTop) {	 // Explorer 6 Strict
				yScroll = document.documentElement.scrollTop;
				xScroll = document.documentElement.scrollLeft;
			} else if (document.body) {// all other Explorers
				yScroll = document.body.scrollTop;
				xScroll = document.body.scrollLeft;	
			}
			arrayPageScroll = new Array(xScroll,yScroll);
			return arrayPageScroll;
		};
		 /**
		  * Stop the code execution from a escified time in milisecond
		  *
		  */
		 function ___pause(ms) {
			var date = new Date(); 
			curDate = null;
			do { var curDate = new Date(); }
			while ( curDate - date < ms);
		 };
		// Return the jQuery object for chaining. The unbind method is used to avoid click conflict when the plugin is called more than once
		return this.unbind('click').click(_initialize);
	};
})(jQuery); // Call and execute the function immediately passing the jQuery object


var gmaps_class;
if(!gmaps_class) gmaps_class = {};

gmaps_class.maps = {};

gmaps_class.maps.set = function(j_element,options)
{
	var map_name = jQuery(j_element).attr("id");
	var this_map = new GMap2(j_element);
	gmaps_class.maps[map_name] = this_map;
	gmaps_class.maps[map_name].options = options;
	return gmaps_class.maps[map_name];
}

gmaps_class.maps.get = function(j_element)
{
	return gmaps_class.maps[jQuery(j_element).attr("id")];
}
gmaps_class.maps.append = function ( j_element, description, appending ) 
{
	var map_name = jQuery(j_element).attr('id');
	gmaps_class.maps[map_name][description] = appending;
};

gmaps_class.get_map_type = function(map_type)
{
	switch(map_type) 
	{
		case 'map':
			map_type = G_NORMAL_MAP;
			break;
		case 'sat':
			map_type = G_SATELLITE_MAP;
			break;
		case 'hybrid':
			map_type = G_HYBRID_MAP;
			break;
	};
	return map_type;
}



gmaps_class.init = function(j_element, options, callback )
{
	
	function defaults()
	{
		return {
			"language" : "en",
			"map_type" : "map",
			"map_center" : [0,0],
			"map_zoom" : 12,
			"map_control" : "large",
			"map_enable_type" : false,
			"map_enable_overview" : false,
			"map_enable_dragging" : true,
			"map_enable_info_windows": true,
			"map_enable_2click_zoom" : true,
			"map_enable_scroll_zoom" : false,
			"map_enable_smooth_zoom" : false,
			"map_enable_scall_control" : false
		};
	};
	
	options = jQuery.extend(defaults(),options);
	
	if (GBrowserIsCompatible()) 
	{
		
		var this_map = gmaps_class.maps.set(j_element,options);
		var map_type = gmaps_class.get_map_type(options.map_type);
		this_map.setCenter(new GLatLng(options.map_center[0], options.map_center[1]), options.map_zoom*1,map_type);
		
		switch (options.map_control) 
		{
			case "small":
				this_map.addControl(new GSmallMapControl());
				break;
			case "large":
				this_map.addControl(new GLargeMapControl());
				break;
		};
		
		if (options.map_enable_type) this_map.addControl(new GMapTypeControl()); // Off by default
		
		if (options.map_enable_overview) this_map.addControl(new GOverviewMapControl());// Off by default
	
		if (!options.map_enable_dragging) this_map.disableDragging();
		if (!options.map_enable_info_windows) this_map.disableInfoWindow();
		if (options.map_enable_2click_zoom) this_map.enableDoubleClickZoom();
		if (options.map_enable_scroll_zoom) this_map.enableScrollWheelZoom();
		if (options.map_enable_smooth_zoom) this_map.enableContinuousZoom();
		if (options.map_enable_scale_control) this_map.addControl(new GScaleControl());
		
		if (typeof callback == 'function') 
			return callback(this_map, j_element, options);
	}
	else
	{
		jQuery(j_element).text('Your browser does not support Google Maps.');
		return false;
	}
	return;
}

gmaps_class.remove_marker = function ( j_element, marker, callback ) 
{
	var this_map = gmaps_class.maps.get(j_element);
	this_map.removeOverlay(marker);
	if (typeof callback === 'function') return callback(marker);
	return;
}
gmaps_class.clear_overlays = function (j_element,callback)
{
	var this_map = gmaps_class.maps.get(j_element);
	this_map.clearOverlays();
	if (typeof callback === 'function') return callback(marker);
	return;
}

gmaps_class.add_marker = function(j_element,options,callback)
{
	function defaults() {
		return {
			'point_lat_lng': undefined,
			'point_html': undefined,
			'point_open_html_event': 'click',
			'point_is_draggable': false,
			'point_is_removable': false,
			'point_remove_event': 'dblclick',
			'point_min_zoom': 4,
			'point_max_zoom': 17,
			'point_icon': undefined,
			'center_map': false,
			'center_move_method':'normal',
			'auto_pan' : false
		};
	};
	var this_map = gmaps_class.maps.get(j_element);
	
	options = jQuery.extend({},defaults(),options);
	
	var marker_options = {};
	
	if (typeof options.point_icon == 'object') 
	{
		jQuery.extend(marker_options, {'icon': options.point_icon});
	}
	
	if (options.point_is_draggable) jQuery.extend(marker_options, {'draggable': options.point_is_draggable});
	if (options.auto_pan) jQuery.extend(marker_options, {'autoPan': options.auto_pan});
			
	if (options.center_map) {
		switch (options.center_move_method) 
		{
			case 'normal':
				this_map.setCenter(new GLatLng(options.point_lat_lng[0],options.point_lat_lng[1]));
				break;
			case 'pan':
				this_map.panTo(new GLatLng(options.point_lat_lng[0],options.point_lat_lng[1]));
				break;
		}
	}
		
	var marker = new GMarker(new GLatLng(options.point_lat_lng[0],options.point_lat_lng[1]), marker_options);
	//gmaps_class.debug(marker);
	if(options.point_html)
	{
		GEvent.addListener(marker, options.point_open_html_event, 
		function()
		{
			marker.openInfoWindowHtml(options.point_html, {maxContent: options.point_max_content, maxTitle: options.point_max_title});
		});
	}
	
	if(options.point_is_removable)
	{
		GEvent.addListener(marker, options.point_remove_event, 
		function()
		{
			this_map.removeOverlay(marker);
		});
	}
	
	this_map.addOverlay(marker);
	if (typeof callback == 'function') return callback(marker, options);
	return;
}

gmaps_class.create_icon = function(options)
{
	function defaults()
	{
		return {
			'icon_img' : undefined,
			'icon_shadow' : undefined,
			'icon_size' : undefined,
			'icon_shadow_size' : undefined,
			'icon_anchor' : undefined,
			'icon_info_window_anchor' : undefined
		};
	}
	options = jQuery.extend(defaults(),options);
	
	var icon = new GIcon(G_DEFAULT_ICON);
	
	if(options.icon_img) icon.image = options.icon_img;
	if(options.icon_shadow) icon.shadow = options.icon_shadow;
	if(options.icon_size) icon.iconSize = options.icon_size;
	if(options.icon_shadow_size) icon.shadowSize = options.icon_shadow_size;
	if(options.icon_anchor) icon.iconAnchor = options.icon_anchor;
	if(options.icon_info_window_anchor) icon.infoWindowAnchor = options.icon_info_window_anchor;
	return icon;
}

gmaps_class.search = function(j_element, options, callback) {
	function defaults() {
		return {
			'query': null,
			'return_type': 'getLatLng',
			'cache' : undefined
		};
	};
	var this_map = gmaps_class.maps.get(j_element);
	options = jQuery.extend(defaults(), options);
	
	if (typeof this_map.Geocoder === 'undefined') 
	{	
		if (typeof options.cache === 'undefined') {
		 	var geoCoder = new GClientGeocoder();
		} 
		else 
		{
			var geoCoder = new GClientGeocoder(cache);
		}
		gmaps_class.maps.append(j_element, 'Geocoder', geoCoder);
		this_map = gmaps_class.maps.get(j_element);
	}
	this_map.Geocoder[options.return_type](options.query, function(result){
		if (typeof callback === 'function') {
			return callback(result, options); 
		}
	});
	return;
};

gmaps_class.search_code = function ( code ) {
	switch (code) {
		case G_GEO_SUCCESS:
			return {'code':G_GEO_SUCCESS,'success':true,'message':'Success'};
		case G_GEO_UNKNOWN_ADDRESS:
			return {'code' : G_GEO_UNKNOWN_ADDRESS, 'success' : false, 'message' : 'No corresponding geographic location could be found for one of the specified addresses. This may be due to the fact that the address is relatively new, or it may be incorrect'};
			break;
		case G_GEO_SERVER_ERROR:
			return {'code' : G_GEO_UNKNOWN_ADDRESS, 'success' : false, 'message' : 'A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.'};
			break;
		case G_GEO_MISSING_QUERY:
			return {'code' : G_GEO_UNKNOWN_ADDRESS, 'success' : false, 'message' : 'The HTTP q parameter was either missing or had no value. For geocoder requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input.'};
			break;
		case G_GEO_BAD_KEY:
			return {'code' : G_GEO_UNKNOWN_ADDRESS, 'success' : false, 'message' : 'The given key is either invalid or does not match the domain for which it was given.'};
			break;
		case G_GEO_BAD_REQUEST:
			return {'code' : G_GEO_UNKNOWN_ADDRESS, 'success' : false, 'message' : 'A directions request could not be successfully parsed.'};
			break;
		default:
			return {
				'code': null,
				'success': false,
				'message': 'An unknown error occurred.'
			};
		break;
	};
}

gmaps_class.move_to = function ( j_element, options, callback ) {
	function defaults() {
		return {
			'center_method': 'normal',
			'map_type': 'map',
			'map_center': [],
			'map_zoom': null
		};
	};
	
	var this_map = gmaps_class.maps.get(j_element);
	options = jQuery.extend(defaults(),options);	
	
	if (options.map_type)
		var map_type = gmaps_class.get_map_type(options.map_type);
	var point = new GLatLng(options.map_center[0], options.map_center[1]);
	switch (options.center_method) {
		case 'normal':
			this_map.setCenter(point, options.map_zoom, map_type);
			break;
		case 'pan':
			this_map.panTo(point);
			break;
	}
	if (typeof callback == 'function') return callback(point, options);
};


gmaps_class.debug = function(object)
{
	var out="";
	if(typeof object == 'object')
	{
		for(i in object) 
		{
			out+="\n"+i;
		}
		document.write(out);
	}
}

var gmaps_class;
if(!gmaps_class) gmaps_class = {};
(function($)
{
	$.fn.vrs4_gmap = function(method, options, callback) {
		
		return this.each(
			function(){
				if (method == 'init' && typeof options == 'undefined') 
				{
					new gmaps_class.init(this, {}, null);
				} 
				else if (method == 'init' && typeof options == 'object') 
				{
					new gmaps_class.init(this, options, callback);
				} 
				else if (method == 'init' && typeof options == 'function') 
				{
					new gmaps_class.init(this, {}, options);
				} 
				else if (typeof method == 'object' || method == null) 
				{
					new gmaps_class.init(this, method, options);
				} 
				else 
				{
					try {
						new gmaps_class[method](this, options, callback);
					} 
					catch(err) 
					{
						//console.log(err);
						throw Error('gmaps function does not exist / method: '+method);
					}
				}
		});
	}
})(jQuery);



function book_date_pickers()
{
	$('#book-arrival-date-pick')
		.datePicker({createButton:false})
		.bind(
			'click',
			function()
			{
				updateSelectsStart($(this).dpGetSelected()[0]);
				$(this).dpDisplay();
				return false;
			}
		)
		.bind(
			'dateSelected',
			function(e, selectedDate, $td, state)
			{
				updateSelectsStart(selectedDate);
			}
		).bind(
			'dpClosed',
			function(e, selected)
			{
				updateSelectsStart(selected[0]);
			}
		);
		
	$('#book-departure-date-pick')
		.datePicker({createButton:false})
		.bind(
			'click',
			function()
			{
				updateSelectsEnd($(this).dpGetSelected()[0]);
				$(this).dpDisplay();
				return false;
			}
		).bind(
			'dateSelected',
			function(e, selectedDate, $td, state)
			{
				updateSelectsEnd(selectedDate);
			}
		).bind(
			'dpClosed',
			function(e, selected)
			{
				updateSelectsEnd(selected[0]);
			}
		);
		
	var updateSelectsStart = function (selectedDate)
	{
		selectedDate = new Date(selectedDate);
		var d = selectedDate.getDate();
		var m = selectedDate.getMonth();
		var y = selectedDate.getFullYear();
		($('#aday')[0]).selectedIndex = d - 1;
		($('#amonth')[0]).selectedIndex = m;
		($('#ayear')[0]).selectedIndex = y - today.getFullYear();
	}
	
	var updateSelectsEnd = function (selectedDate)
	{
		selectedDate = new Date(selectedDate);
		var d = selectedDate.getDate();
		var m = selectedDate.getMonth();
		var y = selectedDate.getFullYear();
		
		($('#dday')[0]).selectedIndex = d - 1;
		($('#dmonth')[0]).selectedIndex = m;
		($('#dyear')[0]).selectedIndex = y - today.getFullYear();
	}
	
	$('#aday, #amonth, #ayear')
		.bind(
			'change',
			function()
			{
				var d = new Date(
							$('#ayear').val(),
							$('#amonth').val()-1,
							$('#aday').val()
						);
				$('#book-arrival-date-pick').dpSetSelected(d.asString());
			}
		);
	
	$('#dday, #dmonth, #dyear')
		.bind(
			'change',
			function()
			{
				var d = new Date(
							$('#dyear').val(),
							$('#dmonth').val()-1,
							$('#dday').val()
						);
				$('#book-departure-date-pick').dpSetSelected(d.asString());
			}
		);
	var today = new Date();
	if($('#aday')[0] && $('#amonth')[0] && $('#ayear')[0] && $('#dday')[0] && $('#dmonth')[0] && $('#dyear')[0])
	{
		if($('#aday').val()!="" && $("#amonth").val()!="" && $("#ayear").val()!="")
		{
			today = new Date(
				$('#ayear').val(),
				$('#amonth').val()-1,
				$('#aday').val()
			);
		}
		
		($('#aday')[0]).selectedIndex = today.getDate() - 1;
		($('#amonth')[0]).selectedIndex = today.getMonth();
		($('#ayear')[0]).selectedIndex = today.getFullYear() - today.getFullYear();
		
		if($('#dday').val()!="" && $("#dmonth").val()!="" && $("#dyear").val()!="")
		{
			today = new Date(
				$('#dyear').val(),
				$('#dmonth').val()-1,
				$('#dday').val()
			);
		}
		
		($('#dday')[0]).selectedIndex = today.getDate() - 1;
		($('#dmonth')[0]).selectedIndex = today.getMonth();
		($('#dyear')[0]).selectedIndex = today.getFullYear() - today.getFullYear();
		
		// and update the datePicker to reflect it...
		$('#aday').trigger('change');
		$('#dday').trigger('change');
	}
}

$(document).ready(
function(){
	$('#details_gallery a').lightBox({fixedNavigation:true});
	$("#details_map").vrs4_gmap('init',
	{
		"map_center":[$("#lat").val(),$("#long").val()],
		"map_zoom":$("#zoom").val()
	}
	);
	/*
	$("#details_map").vrs4_gmap(
		'move_to',
		{
			'map_center':[$("#lat").val(),$("#long").val()],
			'map_zoom' : $("#zoom").val()+0
		}
	);*/
	if(typeof $("#details_map")=="object")
	{
		var ico = new GIcon(G_DEFAULT_ICON);
		ico.image = site_domain+"public/images/gmap_marker.png";
		ico.shadow = site_domain+"public/images/gmap_marker_shadow.png";
		var map = gmaps_class.maps.get($("#details_map"));
		var point = new GLatLng($("#lat").val(),$("#long").val());
		marker = new GMarker(point,{draggable:false, autoPan:false, icon:ico});
		map.addOverlay(marker);
	}
	$(".scrollable").scrollable({});
	$("#print_page").click(
		function(){ window.print();}
	);
	$("#send_to_a_friend").facebox();
	book_date_pickers();
});


/**
 * jquery.scrollable 1.0.1. Put your HTML scroll.
 * 
 * Copyright (c) 2009 Tero Piirainen
 * http://flowplayer.org/tools/scrollable.html
 *
 * Dual licensed under MIT and GPL 2+ licenses
 * http://www.opensource.org/licenses
 *
 * Launch  : March 2008
 * Version : 1.0.1 - Mon Jan 26 2009 12:49:18 GMT-0000 (GMT+00:00)
 */
(function($) {
		
	function fireEvent(opts, name, self, arg) {
		var fn = opts[name];
		
		if ($.isFunction(fn)) { 
			try {  
				return fn.call(self, arg);
				
			} catch (error) {
				if (opts.alert) {
					alert("Error calling scrollable." + name + ": " + error);
				} else {
					throw error;	
				}
				return false;
			} 					
		}
		return true;			
	}
				
	var current = null;	
	
	
	// constructor
	function Scrollable(root, conf) {   
				
		// current instance
		var self = this;  
		if (!current) { current = self; }		
		
		// horizontal flag
		var horizontal = !conf.vertical;		
		
		
		// wrap (root elements for items)
		var wrap = $(conf.items, root);				
		
		// current index
		var index = 0;
		
		
		// get handle to navigational elements
		var navi = root.siblings(conf.navi).eq(0);
		var prev = root.siblings(conf.prev).eq(0);
		var next = root.siblings(conf.next).eq(0);
		var prevPage = root.siblings(conf.prevPage).eq(0);
		var nextPage = root.siblings(conf.nextPage).eq(0);
		
		
		// methods
		$.extend(self, {
				
			getVersion: function() {
				return [1, 0, 1];	
			},
			
			getIndex: function() {
				return index;	
			},
	
			getConf: function() {
				return conf;	
			},
			
			getSize: function() {
				return self.getItems().size();	
			},
	
			getPageAmount: function() {
				return Math.ceil(this.getSize() / conf.size); 	
			},
			
			getPageIndex: function() {
				return Math.ceil(index / conf.size);	
			},

			getRoot: function() {
				return root;	
			},
			
			getItemWrap: function() {
				return wrap;	
			},
			
			getItems: function() {
				return wrap.children();	
			},
			
			/* all seeking functions depend on this */		
			seekTo: function(i, time, fn) {
				
				// default speed
				time = time || conf.speed;
				
				// function given as second argument
				if ($.isFunction(time)) {
					fn = time;
					time = conf.speed;
				}
								
				if (i < 0) { i = 0; }				
				if (i > self.getSize() - conf.size) { return self; } 				

				var item = self.getItems().eq(i);					
				if (!item.length) { return self; }				
				
				// onBeforeSeek
				if (fireEvent(conf, "onBeforeSeek", self, i) === false) {
					return self;	
				}									
				
				if (horizontal) {					
					var left = -(item.outerWidth(true) * i);					
					wrap.animate({left: left}, time, conf.easing, fn ? function() { fn.call(self); } : null);
					
				} else {
					var top = -(item.outerHeight(true) * i); // wrap.offset().top - item.offset().top;					
					wrap.animate({top: top}, time, conf.easing, fn ? function() { fn.call(self); } : null);							
				}
				
				// onSeek
				fireEvent(conf, "onSeek", self, i);		
				
				
				// navi status update
				if (navi.length) {
					var klass = conf.activeClass;
					var page = Math.ceil(i / conf.size);
					page = Math.min(page, navi.children().length - 1);
					navi.children().removeClass(klass).eq(page).addClass(klass);
				} 
				
				// prev buttons disabled flag
				if (i === 0) {
					prev.add(prevPage).addClass(conf.disabledClass);					
				} else {
					prev.add(prevPage).removeClass(conf.disabledClass);
				}
								
				// next buttons disabled flag
				if (i >= self.getSize() - conf.size) {
					next.add(nextPage).addClass(conf.disabledClass);
				} else {
					next.add(nextPage).removeClass(conf.disabledClass);
				}				
				
				current = self;
				index = i;				
				return self;
				
			},			
				
			move: function(offset, time, fn) {
				var to = index + offset;
				if (conf.loop && to > (self.getSize() - conf.size)) {
					to = 0;	
				}
				return this.seekTo(to, time, fn);
			},
			
			next: function(time, fn) {
				return this.move(1, time, fn);	
			},
			
			prev: function(time, fn) {
				return this.move(-1, time, fn);	
			},
			
			movePage: function(offset, time, fn) {
				return this.move(conf.size * offset, time, fn);		
			},
			
			setPage: function(page, time, fn) {
				var size = conf.size;
				var index = size * page;
				var lastPage = index + size >= this.getSize(); 
				if (lastPage) {
					index = this.getSize() - conf.size;
				}
				return this.seekTo(index, time, fn);
			},
			
			prevPage: function(time, fn) {
				return this.setPage(this.getPageIndex() - 1, time, fn);
			},  
	
			nextPage: function(time, fn) {
				return this.setPage(this.getPageIndex() + 1, time, fn);
			}, 
			
			begin: function(time, fn) {
				return this.seekTo(0, time, fn);	
			},
			
			end: function(time, fn) {
				return this.seekTo(this.getSize() - conf.size, time, fn);	
			},
			
			reload: function() {
				return load();	
			},
			
			click: function(index, time, fn) {
				
				var item = self.getItems().eq(index);
				var klass = conf.activeClass;			
				
				if (!item.hasClass(klass) && (index >= 0 || index < this.getSize())) {				
					self.getItems().removeClass(klass);
					item.addClass(klass);
					var delta = Math.floor(conf.size / 2);
					var to = index - delta;

					// next to last item must work
					if (to > self.getSize() - conf.size) { to--;	}
					
					if (to !== index) {
						return this.seekTo(to, time, fn);		
					}				 
				}
				
				return self;
			}			
			
		});
	
		
		// mousewheel
		if ($.isFunction($.fn.mousewheel)) { 
			root.bind("mousewheel.scrollable", function(e, delta)  {
				// opera goes to opposite direction
				var step = $.browser.opera ? 1 : -1;
				
				self.move(delta > 0 ? step : -step, 50);
				return false;
			});
		}  
		
		// prev button		
		prev.addClass(conf.disabledClass).click(function() { 
			self.prev(); 
		});
		

		// next button
		next.click(function() { 
			self.next(); 
		});
		
		// prev page button
		nextPage.click(function() { 
			self.nextPage(); 
		});
		

		// next page button
		prevPage.addClass(conf.disabledClass).click(function() { 
			self.prevPage(); 
		});		

		
		// keyboard
		if (conf.keyboard) {
			
			// unfortunately window.keypress does not work on IE.
			$(window).unbind("keypress.scrollable").bind("keypress.scrollable", function(evt) {
				
				var el = current;	
				if (!el) { return; }
					
				if (horizontal && (evt.keyCode == 37 || evt.keyCode == 39)) {					
					el.move(evt.keyCode == 37 ? -1 : 1);
					return evt.preventDefault();
				}	
				
				if (!horizontal && (evt.keyCode == 38 || evt.keyCode == 40)) {
					el.move(evt.keyCode == 38 ? -1 : 1);
					return evt.preventDefault();
				}
				
				return true;
				
			});	 
		}

		// navi 			
		function load() {			
			
			navi.each(function() {
				
				var nav = $(this);
				
				// generate new entries
				if (nav.is(":empty") || nav.data("me") == self) {
					
					nav.empty();
					nav.data("me", self);
					
					for (var i = 0; i < self.getPageAmount(); i++) {		
						
						var item = $("<" + conf.naviItem + "/>").attr("href", i).click(function(e) {							
							var el = $(this);
							el.parent().children().removeClass(conf.activeClass);
							el.addClass(conf.activeClass);
							self.setPage(el.attr("href"));
							return e.preventDefault();
						});
						
						if (i === 0) { item.addClass(conf.activeClass); }
						nav.append(item);					
					}
					
				// assign onClick events to existing entries
				} else {
					
					// find a entries first -> syntaxically correct
					var els = nav.children(); 
					
					els.each(function(i)  {
						var item = $(this);
						item.attr("href", i);
						if (i === 0) { item.addClass(conf.activeClass); }
						
						item.click(function() {
							nav.find("." + conf.activeClass).removeClass(conf.activeClass);
							item.addClass(conf.activeClass);
							self.setPage(item.attr("href"));
						});
						
					});
				}
				
			});
			
			
			// item.click()
			if (conf.clickable) {
				self.getItems().each(function(index, arg) {
					var el = $(this);
					if (!el.data("set")) {
						el.bind("click.scrollable", function() {
							self.click(index);		
						});
						el.data("set", true);
					}
				});				
			}
			
			
			// hover
			if (conf.hoverClass) {
				self.getItems().hover(function()  {
					$(this).addClass(conf.hoverClass);		
				}, function() {
					$(this).removeClass(conf.hoverClass);	
				});
			}			
			
			return self;
		}
		
		load();
		
		
		// interval stuff
		var timer = null;

		function setTimer() {
			timer = setInterval(function()  {
				self.next();
				
			}, conf.interval);	
		}	
		
		if (conf.interval > 0) {			
			
			root.hover(function() {			
				clearInterval(timer);		
			}, function() {		
				setTimer();	
			});
			
			setTimer();	
		}
		
	} 

		
	// jQuery plugin implementation
	jQuery.prototype.scrollable = function(conf) { 
			
		// already constructed --> return API
		var api = this.eq(typeof conf == 'number' ? conf : 0).data("scrollable");
		if (api) { return api; }		
		
 
		var opts = {
			
			// basics
			size: 5,
			vertical:false,			
			clickable: true,
			loop: false,
			interval: 0,			
			speed: 400,
			keyboard: true,			
			
			// other
			activeClass:'active',
			disabledClass: 'disabled',
			hoverClass: null,			
			easing: 'swing',
			
			// navigational elements
			items: '.items',
			prev: '.prev',
			next: '.next',
			prevPage: '.prevPage',
			nextPage: '.nextPage',			
			navi: '.navi',
			naviItem: 'a',

			
			// callbacks
			onBeforeSeek: null,
			onSeek: null,
			alert: true
		}; 
		
		
		$.extend(opts, conf);		
		
		this.each(function() {			
			var el = new Scrollable($(this), opts);
			$(this).data("scrollable", el);	
		});
		
		return this; 
		
	};
			
	
})(jQuery);


/*
 * Facebox (for jQuery)
 * version: 1.2 (05/05/2008)
 * @requires jQuery v1.2 or later
 *
 * Examples at http://famspam.com/facebox/
 *
 * Licensed under the MIT:
 *   http://www.opensource.org/licenses/mit-license.php
 *
 * Copyright 2007, 2008 Chris Wanstrath [ chris@ozmm.org ]
 *
 * Usage:
 *  
 *  jQuery(document).ready(function() {
 *    jQuery('a[rel*=facebox]').facebox() 
 *  })
 *
 *  <a href="#terms" rel="facebox">Terms</a>
 *    Loads the #terms div in the box
 *
 *  <a href="terms.html" rel="facebox">Terms</a>
 *    Loads the terms.html page in the box
 *
 *  <a href="terms.png" rel="facebox">Terms</a>
 *    Loads the terms.png image in the box
 *
 *
 *  You can also use it programmatically:
 * 
 *    jQuery.facebox('some html')
 *
 *  The above will open a facebox with "some html" as the content.
 *    
 *    jQuery.facebox(function($) { 
 *      $.get('blah.html', function(data) { $.facebox(data) })
 *    })
 *
 *  The above will show a loading screen before the passed function is called,
 *  allowing for a better ajaxy experience.
 *
 *  The facebox function can also display an ajax page or image:
 *  
 *    jQuery.facebox({ ajax: 'remote.html' })
 *    jQuery.facebox({ image: 'dude.jpg' })
 *
 *  Want to close the facebox?  Trigger the 'close.facebox' document event:
 *
 *    jQuery(document).trigger('close.facebox')
 *
 *  Facebox also has a bunch of other hooks:
 *
 *    loading.facebox
 *    beforeReveal.facebox
 *    reveal.facebox (aliased as 'afterReveal.facebox')
 *    init.facebox
 *
 *  Simply bind a function to any of these hooks:
 *
 *   $(document).bind('reveal.facebox', function() { ...stuff to do after the facebox and contents are revealed... })
 *
 */
(function($) {
  $.facebox = function(data, klass) {
    $.facebox.loading()

    if (data.ajax) fillFaceboxFromAjax(data.ajax)
    else if (data.image) fillFaceboxFromImage(data.image)
    else if (data.div) fillFaceboxFromHref(data.div)
    else if ($.isFunction(data)) data.call($)
    else $.facebox.reveal(data, klass)
  }

  /*
   * Public, $.facebox methods
   */

  $.extend($.facebox, {
    settings: {
      opacity      : 0,
      overlay      : true,
      loadingImage : public_domain+'admin/images/facebox/loading.gif',
      closeImage   : public_domain+'admin/images/facebox/closelabel.gif',
      imageTypes   : [ 'png', 'jpg', 'jpeg', 'gif' ],
      faceboxHtml  : '\
    <div id="facebox" style="display:none;"> \
      <div class="popup"> \
        <table> \
          <tbody> \
            <tr> \
              <td class="tl"/><td class="b"/><td class="tr"/> \
            </tr> \
            <tr> \
              <td class="b"/> \
              <td class="body"> \
                <div class="content"> \
                </div> \
                <div class="footer"> \
                  <a href="#" class="close"> \
                    <img src="/facebox/closelabel.gif" title="close" class="close_image" /> \
                  </a> \
                </div> \
              </td> \
              <td class="b"/> \
            </tr> \
            <tr> \
              <td class="bl"/><td class="b"/><td class="br"/> \
            </tr> \
          </tbody> \
        </table> \
      </div> \
    </div>'
    },

    loading: function() {
      init()
      if ($('#facebox .loading').length == 1) return true
      showOverlay()

      $('#facebox .content').empty()
      $('#facebox .body').children().hide().end().
        append('<div class="loading"><img src="'+$.facebox.settings.loadingImage+'"/></div>')

      $('#facebox').css({
        top:	getPageScroll()[1] + (getPageHeight() / 10),
        left:	385.5
      }).show()

      $(document).bind('keydown.facebox', function(e) {
        if (e.keyCode == 27) $.facebox.close()
        return true
      })
      $(document).trigger('loading.facebox')
    },

    reveal: function(data, klass) {
      $(document).trigger('beforeReveal.facebox')
      if (klass) $('#facebox .content').addClass(klass)
      $('#facebox .content').append(data)
      $('#facebox .loading').remove()
      $('#facebox .body').children().fadeIn('normal')
      $('#facebox').css('left', $(window).width() / 2 - ($('#facebox table').width() / 2))
      $(document).trigger('reveal.facebox').trigger('afterReveal.facebox')
    },

    close: function() {
      $(document).trigger('close.facebox')
      return false
    }
  })

  /*
   * Public, $.fn methods
   */

  $.fn.facebox = function(settings) {
    init(settings)

    function clickHandler() {
      $.facebox.loading(true)

      // support for rel="facebox.inline_popup" syntax, to add a class
      // also supports deprecated "facebox[.inline_popup]" syntax
      var klass = this.rel.match(/facebox\[?\.(\w+)\]?/)
      if (klass) klass = klass[1]

      fillFaceboxFromHref(this.href, klass)
      return false
    }

    return this.click(clickHandler)
  }

  /*
   * Private methods
   */

  // called one time to setup facebox on this page
  function init(settings) {
    if ($.facebox.settings.inited) return true
    else $.facebox.settings.inited = true

    $(document).trigger('init.facebox')
    makeCompatible()

    var imageTypes = $.facebox.settings.imageTypes.join('|')
    $.facebox.settings.imageTypesRegexp = new RegExp('\.' + imageTypes + '$', 'i')

    if (settings) $.extend($.facebox.settings, settings)
    $('body').append($.facebox.settings.faceboxHtml)

    var preload = [ new Image(), new Image() ]
    preload[0].src = $.facebox.settings.closeImage
    preload[1].src = $.facebox.settings.loadingImage

    $('#facebox').find('.b:first, .bl, .br, .tl, .tr').each(function() {
      preload.push(new Image())
      preload.slice(-1).src = $(this).css('background-image').replace(/url\((.+)\)/, '$1')
    })

    $('#facebox .close').click($.facebox.close)
    $('#facebox .close_image').attr('src', $.facebox.settings.closeImage)
  }
  
  // getPageScroll() by quirksmode.com
  function getPageScroll() {
    var xScroll, yScroll;
    if (self.pageYOffset) {
      yScroll = self.pageYOffset;
      xScroll = self.pageXOffset;
    } else if (document.documentElement && document.documentElement.scrollTop) {	 // Explorer 6 Strict
      yScroll = document.documentElement.scrollTop;
      xScroll = document.documentElement.scrollLeft;
    } else if (document.body) {// all other Explorers
      yScroll = document.body.scrollTop;
      xScroll = document.body.scrollLeft;	
    }
    return new Array(xScroll,yScroll) 
  }

  // Adapted from getPageSize() by quirksmode.com
  function getPageHeight() {
    var windowHeight
    if (self.innerHeight) {	// all except Explorer
      windowHeight = self.innerHeight;
    } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
      windowHeight = document.documentElement.clientHeight;
    } else if (document.body) { // other Explorers
      windowHeight = document.body.clientHeight;
    }	
    return windowHeight
  }

  // Backwards compatibility
  function makeCompatible() {
    var $s = $.facebox.settings

    $s.loadingImage = $s.loading_image || $s.loadingImage
    $s.closeImage = $s.close_image || $s.closeImage
    $s.imageTypes = $s.image_types || $s.imageTypes
    $s.faceboxHtml = $s.facebox_html || $s.faceboxHtml
  }

  // Figures out what you want to display and displays it
  // formats are:
  //     div: #id
  //   image: blah.extension
  //    ajax: anything else
  function fillFaceboxFromHref(href, klass) {
    // div
    if (href.match(/#/)) {
      var url    = window.location.href.split('#')[0]
      var target = href.replace(url,'')
      $.facebox.reveal($(target).clone().show(), klass)

    // image
    } else if (href.match($.facebox.settings.imageTypesRegexp)) {
      fillFaceboxFromImage(href, klass)
    // ajax
    } else {
      fillFaceboxFromAjax(href, klass)
    }
  }

  function fillFaceboxFromImage(href, klass) {
    var image = new Image()
    image.onload = function() {
      $.facebox.reveal('<div class="image"><img src="' + image.src + '" /></div>', klass)
    }
    image.src = href
  }

  function fillFaceboxFromAjax(href, klass) {
    $.get(href, function(data) { $.facebox.reveal(data, klass) })
  }

  function skipOverlay() {
    return $.facebox.settings.overlay == false || $.facebox.settings.opacity === null 
  }

  function showOverlay() {
    if (skipOverlay()) return

    if ($('facebox_overlay').length == 0) 
      $("body").append('<div id="facebox_overlay" class="facebox_hide"></div>')

    $('#facebox_overlay').hide().addClass("facebox_overlayBG")
      .css('opacity', $.facebox.settings.opacity)
      .click(function() { $(document).trigger('close.facebox') })
      .fadeIn(200)
    return false
  }

  function hideOverlay() {
    if (skipOverlay()) return

    $('#facebox_overlay').fadeOut(200, function(){
      $("#facebox_overlay").removeClass("facebox_overlayBG")
      $("#facebox_overlay").addClass("facebox_hide") 
      $("#facebox_overlay").remove()
    })
    
    return false
  }

  /*
   * Bindings
   */

  $(document).bind('close.facebox', function() {
    $(document).unbind('keydown.facebox')
    $('#facebox').fadeOut(function() {
      $('#facebox .content').removeClass().addClass('content')
      hideOverlay()
      $('#facebox .loading').remove()
    })
  })

})(jQuery);
