﻿

(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.6, // (integer) Opacity value to overlay; inform: 0.X. Where X are number from 0 to 9
			// Configuration related to navigation
			imageLoading: 'media/img/lightbox/lightbox-ico-loading.gif', // (string) Path and the name of the loading icon
			imageBtnClose: 'media/img/lightbox/boton_cerrar.png', // (string) Path and the name of the close btn
			imageBtnPrev:			'media/img/lightbox/boton_anterior.png',			// (string) Path and the name of the prev button image
			imageBtnPrevOff:			'media/img/lightbox/boton_anterior.png',			// (string) Path and the name of the prev button image
			imageBtnNext:			'media/img/lightbox/boton_proxima.png',			// (string) Path and the name of the next button image
			imageBtnNextOff:			'media/img/lightbox/boton_proxima.png',			// (string) Path and the name of the next button image
			imageBlank: 'media/img/lightbox/lightbox-blank.gif', // (string) Path and the name of a blank image (one pixel)
			// Configuration related to container image box
			containerBorderSize: 4, // (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.
			intMapWidth : 690,
			intMapHeight : 422,
			minImgHeight : 600, 
			// Donï¿½t alter these variables in any way
			iconoMapa:'media/img/gmaps.icon.png',
			raiz:'/website2009/',
			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
		}
		
		function showPanorama(){
			var povObj = {
				pitch:-0.42,
				yaw:137.79,
				zoom:0
			};
			var p = new GLatLng(41.400791,2.176892);
			panoramaOptions = { latlng:p, pov:povObj };
			var node = $('#lightbox-container-image').append('<div id="panorama" />')
			.find('#panorama').css({
				position:"absolute",
				width:"100%",
				height:"100%",
				top:"0px",
				left:"0px",
				zIndex:'995'
			})[0];
			
			$.panorama = new GStreetviewPanorama(node, panoramaOptions);
			
     		GEvent.addListener($.panorama, "error", handleNoFlash);
			GEvent.addListener($.panorama, "initialized", onPanoramaInit);
			
			GEvent.addListener($.panorama, "yawchanged", sendToFirebug );
			GEvent.addListener($.panorama, "pithcchanged", sendToFirebug );
			GEvent.addListener($.panorama, "zoomchanged", sendToFirebug );
		}
		
		function sendToFirebug(event){
			console.dir($.panorama.getPOV());
			console.dir($.panorama);
		}
		
		function onPanoramaInit(event){
			//console.log(event);
		}
		
	    function handleNoFlash(errorCode) {
	      if (errorCode == FLASH_UNAVAILABLE) {
	        alert("Error: Flash doesn't appear to be supported by your browser");
	        return;
	      }
	    }  

		/**
		 * 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) {
			url = objClicked.getAttribute('href');
			// 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();
			/**
			 * Markcial says : Ahora vienen mis modificaciones :D 
			 */
			if($(window).height()<settings.minImgHeight) return;
			// 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
			if(!objClicked.getAttribute('href').match(/http:\/\/maps.google.es/)) {
				_set_image_to_view();
			}else{
				var params = {};
				var pr = objClicked.getAttribute('href').split('?')[1];
				var pairs = "";
				pr.split('&').length>0 ?
					 pairs = pr.split('&') : 
					 pairs = pr;
				$(pairs).each(function(){
					var pieces = this.split('=');
					params[pieces[0]] = pieces[1];
				}) 
				
				
				if( params["q"] ){
					address = params["q"];
				}
				
				if( params["ll"] ){
					latlng = params["ll"].split(',');
				}
				
				//info = $(objClicked).find('img').attr('title') + '<br /><a href="'+url+'" target="_blank">Ver en Google Maps</a>'
				// hay que maquetar la info en un html externo TODO
				info = '<h3>Xtranet</h3><div style="text-align:left;font-size:12px;">Calle Sardenya 229 2ª planta<br />08013 Barcelona<br />t +34 93 450 25 33<br />f +34 93 511 63 98<br />SPAIN<br /><a href="javascript:;" class="panorama">Ver en Street View</a></div>'
				$('#lightbox-image').remove();
				_resize_container_image_box(settings.intMapWidth,settings.intMapHeight,true);
				
			}
		}
		/**
		 * 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">
					<a href="#" class="lightbox-close"></a>
					<div id="lightbox-container-image">
						<img src="../fotos/XX.jpg" id="lightbox-image">
						<div id="lightbox-loading">
							<a href="#" id="lightbox-loading-link">
								<img src="../media/img/lightbox/lightbox-ico-loading.gif">
							</a>
						</div>
					</div>
				</div>
			</div>
		 *
		 */
		function _set_interface() {
			if($(window).height()<settings.minImgHeight){
				var img = new Image();
				img.onload = function(){
					var popup = window.open(url, "Imagen", "resizable=no,toolbar=no,location=no,scrollbars=no,menubar=no,width="+img.width+",height="+img.height+",top="+ ( screen.height - img.height ) / 2 +",left="+ ( screen.width - img.width ) / 2);
					popup.focus();
				}
				if(url.match(/http:\/\/maps.google.es/)){
					var popup = window.open(url, "Imagen", "resizable=no,toolbar=no,location=no,scrollbars=no,menubar=no,width="+settings.intMapWidth+",height="+settings.intMapHeight+",top="+ ( screen.height - settings.intMapHeight ) / 2 +",left="+ ( screen.width - settings.intMapWidth ) / 2);
				}else{
					img.src = url;
				}
				return;
			}
			//$('body,html').css({overflowY:'hidden'});
			// Apply the HTML markup into body tag
			if (!url.match(/http:\/\/maps.google.es/)) {
				// si hay paginacion
				$('body').append('<div id="jquery-overlay"></div><div id="jquery-lightbox"><div id="lightbox-container-image-box"><a href="#" id="lightbox-close"><img src="' + settings.raiz + settings.imageBtnClose + '" /></a><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.raiz + settings.imageLoading + '"></a></div></div></div></div>');
			}
			else {
				// si no hay paginacion
				$('body').append('<div id="jquery-overlay"></div><div id="jquery-lightbox"><div id="lightbox-container-image-box"><a href="#" id="lightbox-close"><img src="' + settings.raiz + settings.imageBtnClose + '" /></a><div id="lightbox-container-image"><img id="lightbox-image"><div id="lightbox-loading"><a href="#" id="lightbox-loading-link"><img src="' + settings.raiz + settings.imageLoading + '"></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] / 4),
				left:	arrPageScroll[0] 
			}).show();
			// Assigning click events in elements to close overlay
			$('#jquery-overlay').click(function() {
				_finish();				
			});
			/*$('#lightbox-container-image-box').click(function(e){
				e.stopPropagation();
				return false;
			})*/
			$('#lightbox-close').hide();
			// Assign the _finish function to lightbox-loading-link and lightbox-secNav-btnClose objects
			$('#lightbox-loading-link,#lightbox-close').click(function() {
				_finish();
				return false;
			});
			$('#lightbox-image').css({cursor:'pointer'}).bind('click',function(){
				_set_image_to_view();
				return false;
			})
			// If window was resized, calculate the new overlay dimensions
			$(window).bind('resize',resize).bind('scroll',resize)
			
		}
		
		function resize(){
			// 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
			var centerTop = arrPageScroll[1]+( arrPageSizes[3]- $('#lightbox-container-image').height())/2;
			var centerLeft = ( arrPageSizes[2] - $('#lightbox-container-image').width() ) /2;
			$('#jquery-lightbox').css({
				top:	centerTop,
				left:	centerLeft
			});
		}
		/**
		 * geolocalizacion
		 */
		function _show_address(){
			if (geocoder) {
				geocoder.getLatLng(
				  address,
				  function(point) {
				    if (!point) {
					  address = address.split(' ')
					  address.shift();
					  address = address.join(" ");
					  showAddress(address);
				    } else {
				      map.setCenter(point, 16);
				      var marker = new GMarker(point);
					  marker.info = info;
				      GEvent.addListener(marker, "click", function() {
				  		marker.openInfoWindowHtml(marker.info);
						  });
					  map.addOverlay(marker);
					  marker.openInfoWindowHtml(marker.info);
				    }
				  }
				);
			}
		}
		/**
		 * renderiza el mapa
		 */
		function _render_map(){
			$('#lightbox-container-image-box').stop().css({
				border:settings.containerBorderSize+"px solid black"
			});
			
			$('#lightbox-close').show();
			$('#lightbox-container-image').css({
				width:settings.intMapWidth+(settings.containerBorderSize*2),
				height:settings.intMapHeight+(settings.containerBorderSize*2),
				padding:"0px",
				border:"0px solid black"
			});
			$.mapa = new GMap($('#lightbox-container-image')[0]);
	        $.mapa.addControl(new GSmallMapControl());
	        $.mapa.addControl(new GMapTypeControl());
			$.mapa.enableScrollWheelZoom();
			
			var xtraIco = new GIcon(G_DEFAULT_ICON);
        	xtraIco.image = settings.raiz+settings.iconoMapa;
			xtraIco.iconSize = new GSize(15,14);
			xtraIco.shadowSize = new GSize(30,14);
			xtraIco.iconAnchor = new GPoint(7,0);
			// Set up our GMarkerOptions object
			markerOptions = { icon:xtraIco };

			$.marker = new GMarker(new GLatLng(latlng[0],latlng[1]),markerOptions);
			$.marker.info = info;
			$.mapa.setCenter($.marker.getPoint(),16);
			GEvent.addListener($.marker, "click", function() {
          		$.marker.openInfoWindowHtml($.marker.info);
				//showPanorama();
   		    });
			GEvent.addListener($.mapa, "infowindowopen", function() {
				$('#lightbox-container-image a.panorama').click(function(){
					showPanorama();
				}); 
			});
			
			$.mapa.addOverlay($.marker);
		    $.marker.openInfoWindowHtml($.marker.info);
			
			return false;
		}
		/**
		 * Prepares image exibition; doing a imageï¿½s preloader to calculate itï¿½s size
		 *
		 */
		function _set_image_to_view() {
			$('#lightbox-nav,#lightbox-close').hide();
			// Show the loading
			$('#lightbox-loading').show();
			// Hide some elements
			$('#lightbox-image,#lightbox-container-image-data-box').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,isMap) {
			// 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
			//var centerTop = (___getPageSize()[3]-intHeight)/2;
			var arrPageScroll = ___getPageScroll();
			var arrPageSizes = ___getPageSize();
			var centerTop = arrPageScroll[1] + ( arrPageSizes[3]-intHeight ) / 2;
			var centerLeft = ( arrPageSizes[2]-intWidth ) /2;
			$('#jquery-lightbox').animate({
				top:centerTop,
				left : centerLeft,
				width: intWidth
			})
			$('#lightbox-container-image-box').animate({ width: intWidth, height: intHeight },settings.containerResizeSpeed,function() { 
				isMap?_render_map():_show_image(); 
			});
			if ( ( intDiffW == 0 ) && ( intDiffH == 0 ) ) {
				if ( $.browser.msie ) {
					___pause(250);
				} else {
					___pause(100);	
				}
			} 
		};
		/**
		 * Show the prepared image
		 *
		 */
		function _show_image() {
			$('#lightbox-loading').hide();
			$('#lightbox-image').fadeIn(function() {
				$('#lightbox-close').show();
				_set_navigation();
			});
			_preload_neighbor_images();
		};
		/**
		 * 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' : 'none' }).hide();
			
			
			// Show the prev button, if not the first image in set
			if (settings.activeImage != 0) {
				
				$('#lightbox-nav-btnPrev').css({ 'background' : 'url(' + settings.raiz + settings.imageBtnPrevOff + ') left 50% no-repeat' }).show();
				
				if ( settings.fixedNavigation ) {
					$('#lightbox-nav-btnPrev').css({ 'background' : 'url(' + settings.raiz + settings.imageBtnPrev + ') left 50% no-repeat' })
						.unbind()
						.bind('click',function() {
							settings.activeImage = settings.activeImage - 1;
							_set_image_to_view();
							return false;
						}).show();
				} else {
					// Show the images button for Next buttons
					$('#lightbox-nav-btnPrev').unbind().hover(function() {
						if (settings.activeImage != 0) {
							$(this).css({
								'background': 'url(' + settings.raiz + settings.imageBtnPrev + ') left 50% no-repeat'
							}).show();
						}else{
							$(this).css({
								'background': 'none'
							}).hide();
						}
					},function() {
						if (settings.activeImage != 0) {
							$(this).css({ 'background' : 'url(' + settings.raiz + settings.imageBtnPrevOff + ') left 50% no-repeat' }).show();
						}else{
							$(this).css({
								'background': 'none'
							}).hide();
						}
						
					}).show().bind('click',function() {
						//$(this).css({ 'background' : 'url(' + settings.raiz + settings.imageBtnPrevOff + ') left 50% no-repeat' });
						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 ) ) {
				
				$('#lightbox-nav-btnNext').css({ 'background' : 'url(' + settings.raiz + settings.imageBtnNextOff + ') right 50% no-repeat' }).show();
			
				if ( settings.fixedNavigation ) {
					$('#lightbox-nav-btnNext').css({ 'background' : 'url(' + settings.raiz + settings.imageBtnNext + ') right 50% no-repeat' })
						.unbind()
						.bind('click',function() {
							settings.activeImage = settings.activeImage + 1;
							_set_image_to_view();
							return false;
						}).show();
				} else {
					// Show the images button for Next buttons
					$('#lightbox-nav-btnNext').unbind().hover(function() {
						if (settings.activeImage != (settings.imageArray.length - 1)) {
							$(this).css({
								'background': 'url(' + settings.raiz + settings.imageBtnNext + ') right 50% no-repeat'
							}).show();
						}else{
							$(this).css({
								'background': 'none'
							}).hide();
						}
					},function() {
						if (settings.activeImage != (settings.imageArray.length - 1)) {
							$(this).css({ 'background' : 'url(' + settings.raiz + settings.imageBtnNextOff + ') right 50% no-repeat' }).show();
						}else{
							$(this).css({
								'background': 'none'
							}).hide();
						}
					}).show().bind('click',function() {
						settings.activeImage = settings.activeImage + 1;
						_set_image_to_view();
						return false;
					});
				}
			}
		}
		/**
		 * 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();
			//$('body,html').css({overflowY:'auto'});
			$('#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
