/**
 * jQuery gmapBox 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 gmap-gmap-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.gmlightBox = function(settings) {
		// Settings to configure the jQuery lightBox plugin how you like
		settings = jQuery.extend({
			marker:			null,
			// 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 images
			imageBtnClose:		'images/gmap-btn-close.gif',		// (string) Path and the name of the close btn
			// Configuration related to container image box
			containerWidth:		640,
			containerHeight:		480,
			containerBorderSize:	10,			// (integer) If you adjust the padding in the CSS for the container, #gmap-container-map-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 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.
		},settings);
		// Caching the jQuery object with all elements matched
		var jQueryMatchedObj = this; // This, in this context, refer to jQuery object
		var gmMapObject = null;
		var gm_zoom;
		var gm_mapType;
		/**
		 * 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();
			// Call the function that prepares map exibition
			_set_map_to_view(jQueryMatchedObj[0]);
		}
		/**
		 * Create the jQuery lightBox plugin interface
		 *
		 * The HTML markup will be like that:
			<div id="gmap-overlay"></div>
			<div id="gmap-lightbox">
				<div id="gmap-container-map-box">
					<div id="gmap-container-map"></div>
				</div>
				<div id="gmap-container-map-data-box">
					<div id="gmap-container-map-data">
						<div id="gmap-image-details">
							<span id="gmap-image-details-caption"></span>
						</div>
						<div id="gmap-secNav">
							<a href="#" id="gmap-secNav-btnClose">
								<img src="../images/gmap-btn-close.gif">
							</a>
						</div>
					</div>
				</div>
			</div>
		 *
		 */
		function _set_interface() {
			// Apply the HTML markup into body tag
			if (! document.getElementById('gmap-container-map-box')) {
				$('body').append('<div id="gmap-overlay"></div><div id="gmap-lightbox"><div id="gmap-container-map-box"><div id="gmap-container-map"></div></div><div id="gmap-container-map-data-box"><div id="gmap-container-map-data"><div id="gmap-image-details"><span id="gmap-image-details-caption"></span></div><div id="gmap-secNav"><a href="#" id="gmap-secNav-btnClose"><img src="' + settings.imageBtnClose + '"></a></div></div></div></div>');	
			}
			// Get page sizes
			var arrPageSizes = ___getPageSize();
			// Style overlay and show it
			$('#gmap-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 gmap-lightbox div object and show it
			$('#gmap-lightbox').css({
				top:	arrPageScroll[1] + (arrPageSizes[3] / 10),
				left:	arrPageScroll[0]
			}).show();
			// Assigning click events in elements to close overlay
			$('#gmap-overlay,#gmap-lightbox').click(function() {
				_finish();
			});
			$('#gmap-container-map').click(function() {
				return false;
			});
			// Assign the _finish function to gmap-secNav-btnClose object
			$('#gmapbox-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
				$('#gmap-overlay').css({
					width:		arrPageSizes[0],
					height:		arrPageSizes[1]
				});
				// Get page scroll
				var arrPageScroll = ___getPageScroll();
				// Calculate top and left offset for the gmap-lightbox div object and show it
				$('#gmap-lightbox').css({
					top:	arrPageScroll[1] + (arrPageSizes[3] / 10),
					left:	arrPageScroll[0]
				});
			});
		}
		/**
		 * Prepares map exibition
		 *
		 */
		function _set_map_to_view(obj) {
			$('#gmap-container-map-data-box').hide();
			// Map process
			$('#gmap-container-map-box').css({
				width:		settings.containerWidth,
				height:		settings.containerHeight,
				padding:		settings.containerBorderSize
			});
			$('#gmap-container-map').css({
				width:		settings.containerWidth,
				height:		settings.containerHeight
			});
			$('#gmap-container-map-data-box').css({ width: settings.containerWidth });

			if (! $('#gmap-container-map div').length) {
				var params = parseGmapLink(obj.href);
				gm_setMap(params);
			}

			/*$('#gmapbox-image-details-caption').hide();
			if ( settings.imageArray[settings.activeImage][1] ) {
				$('#gmapbox-image-details-caption').html(settings.imageArray[settings.activeImage][1]).show();
			}*/
			$('#gmap-container-map-data-box').slideDown('fast');
			// 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();
			}
		}
		/**
		 * Remove jQuery lightBox plugin HTML markup
		 *
		 */
		function _finish() {
			$('#gmap-lightbox').hide(); //remove();
			$('#gmap-overlay').fadeOut(function() { $('#gmap-overlay').hide(); }); //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);
		};

		function gm_setMap(params) {
			if (GBrowserIsCompatible()) {
				if(!gmMapObject){
					gmMapObject = new GMap2(document.getElementById('gmap-container-map'));
					gmMapObject.addControl(new GLargeMapControl());
					gmMapObject.addControl(new GMapTypeControl());
				}
				gm_mapType=G_NORMAL_MAP;
				gm_zoom=10;
				if(params["t"]=="k"){gm_mapType=G_SATELLITE_MAP;gm_zoom=parseInt(params["z"]);}
				else if(params["t"]=="" || params["t"]==null){gm_mapType=G_NORMAL_MAP;gm_zoom=parseInt(params["z"]);}
				else if(params["t"]=="h"){gm_mapType=G_HYBRID_MAP;gm_zoom=parseInt(params["z"]);}

				if(params["lat"]==null && params["long"]==null && params["q"]!=null && params["q"].indexOf("http://")==-1){
					var geocoder = new GClientGeocoder();
					geocoder.getLatLng(
						unescape(params["q"].replace(/\+/g,  " ")),
						function(point){
							gmMapObject.setCenter(point, gm_zoom,gm_mapType);
							gm_addMarker(point);
						}
					);

				}
				else if(params["q"]!=null && params["q"].indexOf('http://')!=-1){
					//alert(params["q"]);
					//var geoxml = new GGeoXml(params["q"]);
					//var geoxml = new GGeoXml("http://www.emich.be/fr/kml");
					//gm_addXMLMarker(geoxml);
				}
				else{
					var point = new GLatLng(params["lat"],params["long"]);
					gmMapObject.setCenter(point, gm_zoom,gm_mapType);
					gm_addMarker(point);
				}
			}
		}
		function gm_addMarker(point){
			if(settings.marker!=null){
				var marqueur = new GMarker(point, {draggable: false});
				GEvent.addListener(marqueur, 'click', function(){
					marqueur.openInfoWindowHtml('<div style="font-family:Verdana;font-size:10px; color:#000; line-height:1.3em;"><img style="float:left; margin-right:10px;" src="IMG/jpg/esprit-public_googlemap.jpg">'+ settings.marker +'<div style="clear:both;"></div></div>');
				});
				// Ajoutons le marqueur à la carte.
				gmMapObject.addOverlay(marqueur);
			}
		}
		/*function gm_addXMLMarker(geoxml){
			if(settings.marker!=null){gmMapObject.removeOverlay(settings.marker);}
			settings.marker = geoxml;
			gmMapObject.addOverlay(settings.marker);
		}*/
		function parseGmapLink(url){
			var parts = url.split("?");
			if(parts.length<2)return new Array();
			var params = parts[1].split("&");
			var gMapParams={};
			for(i = 0 ; i < params.length ; i++){
				keyValue=params[i].split("=");
				if(keyValue[0]!="ll"){
					gMapParams[keyValue[0]]=keyValue[1];
				}
				else{
					var latlong=keyValue[1].split(",");
					gMapParams["lat"]=latlong[0];
					gMapParams["long"]=latlong[1];
				}
			}
			return gMapParams;
		}

		// 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

