/* ------------------------------------------------------------------------
	Class: prettyPhoto
	Use: Lightbox clone for jQuery
	Author: Stephane Caron (http://www.no-margin-for-errors.com)
	Version: 2.5.6
------------------------------------------------------------------------- */

(function($) {
	$.prettyPhoto = {version: '2.5.6'};
	
	$.fn.prettyPhoto = function(settings) {
		settings = jQuery.extend({
			animationSpeed: 'normal', /* fast/slow/normal */
			opacity: 0.80, /* Value between 0 and 1 */
			showTitle: true, /* true/false */
			showAuthor: true, /* true/false */
			showDescriptionIfEqual: false, /* true/false */
			allowresize: true, /* true/false */
			default_width: 500,
			default_height: 344,
			min_width: 180,
			flowplayerSettings: '',
			authorString: PrettyPhoto.TT['AUTHOR'],
			zoomString: PrettyPhoto.TT['ZOOM'],
			prevString: PrettyPhoto.TT['PREVIOUS'],
			nextString: PrettyPhoto.TT['NEXT'],
			closeString: PrettyPhoto.TT['CLOSE'],
			counter_separator_label: ' / ', /* The separator for the gallery counter 1 "of" 2 */
			theme: 'proxia', /* The prettyPhoto theme */
			hideflash: true, /* Hides all the flash object on a page, set to TRUE if flash appears over prettyPhoto */
			wmode: 'transparent', /* Set the flash wmode attribute */
			autoplay: true, /* Automatically start videos: True/False */
			modal: false, /* If set to true, only the close button will close the window */
			changepicturecallback: function(){}, /* Called everytime an item is shown/changed */
			callback: function(){}, /* Called when prettyPhoto is closed */
			markup: '<div class="pp_pic_holder"> \
						<div class="pp_top"> \
							<div class="pp_left"></div> \
							<div class="pp_middle"></div> \
							<div class="pp_right"></div> \
							<a class="pp_close" href="#">{closeString}</a> \
						</div> \
						<div class="pp_content_container"> \
							<div class="pp_left"></div> \
							<div class="pp_content"> \
								<div class="pp_loaderIcon"></div> \
								<div class="pp_fade"> \
									<div id="pp_full_res_container"> \
										<div id="pp_full_res"></div> \
										<div class="pp_author_container"><div class="pp_author_bg"></div><div class="pp_author"><span class="pp_author_title"></span><span class="pp_author_data"></span></div></div> \
										<a href="#" class="pp_expand" title="{zoomString}">{zoomString}</a> \
									</div> \
									<div class="pp_details clearfix"> \
										<div class="ppt"></div> \
										<div class="pp_description"></div> \
									</div> \
								</div> \
								<div class="pp_nav"> \
									<div class="pp_nav_prev"><a href="#" class="pp_arrow_previous">{prevString}</a></div> \
									<span class="currentTextHolder">0/0</span> \
									<div class="pp_nav_next"><a href="#" class="pp_arrow_next">{nextString}</a></div> \
								</div> \
							</div> \
							<div class="pp_bgnav_container"> \
								<div class="pp_bgnav"></div> \
							</div> \
							<div class="pp_right"></div> \
						</div> \
						<div class="pp_bottom"> \
							<div class="pp_left"></div> \
							<div class="pp_middle"></div> \
							<div class="pp_right"></div> \
						</div> \
					</div> \
					<div class="pp_overlay"></div>',
			image_markup: '<img id="fullResImage" src="" />',
			flash_markup: '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="{width}" height="{height}"><param name="wmode" value="{wmode}" /><param name="allowfullscreen" value="true" /><param name="allowscriptaccess" value="always" /><param name="movie" value="{path}" /><embed src="{path}" type="application/x-shockwave-flash" allowfullscreen="true" allowscriptaccess="always" width="{width}" height="{height}" wmode="{wmode}"></embed></object>',
			flowplayer_markup: '<object id="fp_pphoto" width="{width}" height="{height}" type="application/x-shockwave-flash" data="'+_rootWeb+'/javaScript/flowplayer/flowplayer.unlimited-3.1.5.swf"><param name="movie" value="'+_rootWeb+'/javaScript/flowplayer/flowplayer.unlimited-3.1.5.swf"/><param name="wmode" value="{wmode}" /><param name="allowfullscreen" value="true"/><param name="flashvars" value=\'config={{flpconfig}}\'/></object>',
			ebook_markup: '<object id="ebook" width="{width}" height="{height}" type="application/x-shockwave-flash" data="'+_rootWeb+'/javaScript/pageflip/pageflip_loader.swf"><param name="movie" value="'+_rootWeb+'/javaScript/pageflip/pageflip_loader.swf"/><param name="wmode" value="{wmode}" /><param name="allowfullscreen" value="true"/><param name="allowscriptaccess" value="samedomain"/><param name="menu" value="true"/><param name="bgcolor" value="#000000"/><param name="flashvars" value="XMLfn={path}"/><param name="base" value="'+_rootWeb+'/javaScript/pageflip/"/></object>',
			iframe_markup: '<iframe src ="{path}" width="{width}" height="{height}" frameborder="no"></iframe>',
			inline_markup: '<div class="pp_inline clearfix">{content}</div>'
		}, settings);
		
		// We replace the markup taking into an account the localized information
		settings.markup = settings.markup.replace(/{zoomString}/g,settings.zoomString).replace(/{prevString}/g,settings.prevString).replace(/{nextString}/g,settings.nextString).replace(/{closeString}/g,settings.closeString);
		settings.flowplayer_markup = settings.flowplayer_markup.replace(/{flpconfig}/g,settings.flowplayerSettings);

		if($('.pp_overlay').size()==0) _buildOverlay(); // If the overlay is not there, inject it!
		
		// Author opacity background changed with jquery to avoid accesibility issues
		if($('.pp_author_bg').size()>0)
			if($.browser.msie)
				$('.pp_author_bg').css('filter','alpha(opacity=50)');
			else
				$('.pp_author_bg').fadeTo(0, 0.5);

		// hasLayout activation in IE6+
		if($('#pp_full_res_container').size()>0 && $.browser.msie)
			$('#pp_full_res_container').css({'zoom': 1});

		// Global variables accessible only by prettyPhoto
		var doresize = true, percentBased = false, correctSizes,
		
		// Cached selectors
		$pp_pic_holder, $ppt, $pp_overlay,
		
		// prettyPhoto container specific
		pp_contentHeight, pp_contentWidth, pp_containerHeight, pp_containerWidth,
		
		// Window size
		windowHeight = $(window).height(), windowWidth = $(window).width(),
	
		// Gallery specific
		setPosition = 0,
		
		// Gallery Map
		galleryMap = new Array(),

		// Global elements
		scrollPos = _getScroll();
	
		// Window/Keyboard events
		$(window).scroll(function(){ scrollPos = _getScroll(); _centerOverlay(); _resizeOverlay(); });
		$(window).resize(function(){ _centerOverlay(); _resizeOverlay(); });
		$(document).keydown(function(e){
			if($pp_pic_holder.is(':visible'))
			switch(e.keyCode){
				case 37:
					$.prettyPhoto.changePage('previous');
					break;
				case 39:
					$.prettyPhoto.changePage('next');
					break;
				case 27:
					if(!settings.modal)
					$.prettyPhoto.close();
					break;
			};
	    });
		
		// We have to eval if there is an active gallery, so we have
		// to load it via AJAX
		$(this).each(function(i) {
			theRel = $(this).attr('rel');
			var hrefPath = _rootWeb+'/cm/';
			if(theRel.indexOf('[gallery="true"]')!=-1) {
				// We have decoded all info-photo
				var infoPhoto = decodeMap(theRel.substring(11));
				
				// Extract all parameters needed for AJAX load.
				var _idContent   = infoPhoto['idContent'];
				var _alias       = infoPhoto['alias'];
				var _galleryMode = infoPhoto['type'];
				
				// We have to query galleryMap in order to know if
				// this gallery has been preloaded or we have to load
				// it for the first time.
				if(!galleryMap[_idContent+'@'+_alias+'@'+_galleryMode]) {
					// We fill the map with a empty array, just to avoid repetitive
					// calls for the same content - since AJAX call is asynchronous -
					galleryMap[_idContent+'@'+_alias+'@'+_galleryMode]= new Array();
					var currentGallery = galleryMap[_idContent+'@'+_alias+'@'+_galleryMode];
					
					// We have to make AJAX call and load all data in order to
					// analyze it.
					$.ajax({
						type: "POST",
						url: hrefPath+"contents/galleryResources",
						data: "idContent="+_idContent+"&alias="+_alias+"&galleryMode="+_galleryMode,
						dataType: "xml",
						success: function(resourceList) {
							// We have the XML message and we have to process it.
							var resources = resourceList.getElementsByTagName('resource');
							for(t =0;t<resources.length;t++) {
								var currentResource = new Array();
								var currentMmedia = false;
								// We prepare the array in order to fill it.
								currentResource['title'] = new Array();
								currentResource['description'] = new Array();
								currentResource['width'] = new Array();
								currentResource['height'] = new Array();
								currentResource['type'] = new Array();
								currentResource['author'] = new Array();
								
								
								// We fill the title from the resource
								currentResource['title'][0] = resources[t].getAttribute('name');
								
								// We have to read the nodes in order to retrieve authors and file information
								for(j=0;j<resources[t].childNodes.length;j++) {
									// Authors information
									if(resources[t].childNodes[j].nodeName == 'authors') {
										var currentNode = resources[t].childNodes[j];
										for(n=0;n<currentNode.childNodes.length;n++) {
											if(currentNode.childNodes[n].nodeName=='author') {
												currentResource['author'][currentResource['author'].length] = currentNode.childNodes[n].getAttribute('name');
											}
										}
									}
									// File information.
									if(resources[t].childNodes[j].nodeName == 'files') {
										// candidateFileNode stores the "zoomed image" view of the current node.
										var candidateFileNode = false;
										var currentNode = resources[t].childNodes[j];
										
										// We go through array in order to find the zoomed image or the default
										// image.
										for(n=0;n<currentNode.childNodes.length;n++) {
											if(currentNode.childNodes[n].nodeName == 'file') {
												if(!candidateFileNode) candidateFileNode = currentNode.childNodes[n];
												else {
													if(currentNode.childNodes[n].getAttribute('place')=='1') {
														candidateFileNode = currentNode.childNodes[n];
													}
												}
											}
										}
										
										// Fill array data
										currentMmedia=hrefPath+'images?idMmedia='+candidateFileNode.getAttribute('id');
										currentResource['description'][0]=candidateFileNode.getAttribute('description');
										currentResource['width'][0]=candidateFileNode.getAttribute('width');
										currentResource['height'][0]=candidateFileNode.getAttribute('height');
										currentResource['type'][0]='image';
									
									}

								}
								// We have to fill the map in order to be usable.
								if(!currentGallery['images']) {
									currentGallery['images'] = new Array();
								}
								if(!currentGallery['imageData']) {
									currentGallery['imageData'] = new Array();
								}
							
								currentGallery['images'][currentGallery['images'].length] = currentMmedia;
								currentGallery['imageData'][currentGallery['imageData'].length] = currentResource;
							}
							
						}
					});
				}
				
			}
		});
		
		
		// Bind the code to each links
		$(this).each(function(){
			$(this).bind('click',function(){
				_self = this; // Fix scoping
				
				// Find out if the picture is part of a set
				theRel = $(this).attr('rel');
				var infoPhoto = decodeMap(theRel.substring(11));
				
				var theGallery = (infoPhoto['gallery'] != undefined);
				var currentGallery = false;
				if(theGallery) {
					currentGallery = galleryMap[infoPhoto['idContent']+'@'+infoPhoto['alias']+'@'+infoPhoto['type']];
				}
				
				// Build the gallery array, we have to store images and data for each image.
				var images = new Array();
				var imagesData = new Array();
				if(theGallery && currentGallery){
					// We have to get the position in the set.
					images = currentGallery['images'];
					imagesData = currentGallery['imageData'];
					var idmmedia = grab_param('idMmedia',$(this).attr('href'));
					if(!idmmedia) {
						idmmedia = getMmediaFromPathInfo($(this).attr('href'));
					}
					for(var n=0;n<images.length;n++) {
						if(grab_param('idMmedia',images[n])==idmmedia) {
							setPosition = n;
						}
					}
				} else {
                                        var idmmedia = grab_param('idMmedia',$(this).attr('href'));
                                        if(idmmedia) {
                                        	var tmpImage = $(this).attr('href');
                                        	images = $(this).attr('href').substring(0,tmpImage.lastIndexOf('/')+1)+'images?idMmedia='+idmmedia;
                                        } else {
                                        	var tmpImage = $(this).attr('href');
                                        	var baseImage = '';
                                        	if(tmpImage.indexOf('/')!=-1) {
                                        		baseImage = tmpImage.substring(0,tmpImage.lastIndexOf('/')+1);
                                        		tmpImage = tmpImage.substring(tmpImage.lastIndexOf('/')+1);
                                        	}
                                        
                                        	if(tmpImage.indexOf('g,') == 0 || tmpImage.indexOf('s,') == 0 ||
                                        		tmpImage.indexOf('f,') == 0) {
                                        		tmpImage = tmpImage.substring(2);
                                        	}
                                        
                                        	images = baseImage+tmpImage;
                                        }

					// Now we have to generate a decodedMap based upon this data in order
					// to use internally in the code
					imagesData.push(infoPhoto);
				}
				$.prettyPhoto.open(images,imagesData);
				return false;
			});
		});
	
		
		/**
		* Opens the prettyPhoto modal box.
		* @param gallery_images {String,Array} Full path to the image to be open, can also be an array containing full images paths.
		* @param gallery_imageData {Array} Data associated to the curren image to be opened, it will be an array of arrays.
		*/
		$.prettyPhoto.open = function(gallery_images,gallery_imageData) {

			// To fix the bug with IE select boxes
			if($.browser.msie && $.browser.version == 6){
				$('select').css('visibility','hidden');
			};
			
			// Author opacity background changed with jquery to avoid accesibility issues
			if($('.pp_author_bg').size()>0) $('.pp_author_bg').fadeTo(0, 0.5);
			
			// Add hasOverlay if IE
			if($.browser.msie && $('#pp_full_res_container').size()>0) $('#pp_full_res_container').css({'zoom': 1});

			$('.pp_nav').hide(); // Hide the navigation links

			if(settings.hideflash) $('object,embed').css('visibility','hidden'); // Hide the flash
			
			// Convert everything to an array in the case it's a single item
			images = $.makeArray(gallery_images);
			imagesData = $.makeArray(gallery_imageData);
			image_set = ($(images).size() > 0) ?  true : false; // Find out if it's a set

			$('.pp_loaderIcon').show(); // Do I need to explain?
		
			// Fade the content in
			$pp_overlay.show().fadeTo(settings.animationSpeed,settings.opacity);

			// Display the current position
			$pp_pic_holder.find('.currentTextHolder').text((setPosition+1) + settings.counter_separator_label + $(images).size());

			// Si es un ebook no mostramos los detalles del recurso
			(imagesData[setPosition]['type'] != 'EBook') ? $('.pp_details').show() : $('.pp_details').hide();

			// We extract all needed information about the image we are going to load...
			var imgTitle, imgDescription, imgAuthor, movie_width, movie_height,imgType;
			if(gallery_imageData[setPosition]) {
				imgTitle = decodeURIComponent(imagesData[setPosition]['title'][0]);
				if(imagesData[setPosition]['description']) {
					imgDescription = decodeURIComponent(imagesData[setPosition]['description'][0]);
				}
				imgAuthorArray = imagesData[setPosition]['author'];
				if(imgAuthorArray) {
					for(i=0;i<imgAuthorArray.length;i++) {
						if(i==0) imgAuthor = '';
						if(i!=0) imgAuthor+=', ';
						imgAuthor+=decodeURIComponent(imgAuthorArray[i]);
					}
				}
				if(imagesData[setPosition]['width']) {
					imgWidth = decodeURIComponent(imagesData[setPosition]['width'][0]);
				} else {
					imgWidth = settings.default_width.toString();
				}
				if(imagesData[setPosition]['height']) {
					imgHeight = decodeURIComponent(imagesData[setPosition]['height'][0]);
				} else {
					imgHeight = settings.default_height.toString();
				}
				imgType = decodeURIComponent(imagesData[setPosition]['type']);
			}

			// Set the description
			if(imgDescription && imgDescription != '""' && (imgDescription != imgTitle || settings.showDescriptionIfEqual) ){
				$pp_pic_holder.find('.pp_description').show().html(imgDescription);
			}else{
				$pp_pic_holder.find('.pp_description').hide().text('');
			};

			// Set the title
			if(imgTitle && imgTitle != '""' && settings.showTitle){
				$ppt.html(imgTitle);
			}else{
				$ppt.hide().text('');
			};
			
			// Set the author
			if(imgAuthor && settings.showAuthor) {
				$pp_pic_holder.find('.pp_author_title').html(settings.authorString);
				$pp_pic_holder.find('.pp_author_data').html(imgAuthor);
				$pp_pic_holder.find('.pp_author').show();
			} else {
				$pp_pic_holder.find('.pp_author').hide();
			}
			
			// Get the dimensions
			movie_width = ( parseFloat(imgWidth) ) ? imgWidth : settings.default_width.toString();
			movie_height = ( parseFloat(imgHeight) ) ? imgHeight : settings.default_height.toString();
			
			// If the size is % based, calculate according to window dimensions
			if(movie_width.indexOf('%') != -1 || movie_height.indexOf('%') != -1){
				movie_height = parseFloat(($(window).height() * parseFloat(movie_height) / 100) - 100);
				movie_width = parseFloat(($(window).width() * parseFloat(movie_width) / 100) - 100);
				percentBased = true;
			}
			
			// Fade the holder
			$pp_pic_holder.fadeIn(function(){
				imgPreloader = "";
				// Inject the proper content
				switch(imgType){
					case 'image':
						// Set the new image
						imgPreloader = new Image();

						// Preload the neighbour images
						nextImage = new Image();
						if(image_set && setPosition > $(images).size()) nextImage.src = images[setPosition + 1];
						prevImage = new Image();
						if(image_set && images[setPosition - 1]) prevImage.src = images[setPosition - 1];

						$pp_pic_holder.find('#pp_full_res')[0].innerHTML = settings.image_markup;
						$pp_pic_holder.find('#fullResImage').attr('src',images[setPosition]);

						imgPreloader.onload = function(){
							// Fit item to viewport
							correctSizes = _fitToViewport(imgPreloader.width,imgPreloader.height);

							_showContent();
						};

						imgPreloader.onerror = function(){
							alert('Image cannot be loaded. Make sure the path is correct and image exist.');
							$.prettyPhoto.close();
						};
					
						imgPreloader.src = images[setPosition];
					break;
				
					case 'audiovideo':
					case 'flv':
						correctSizes = _fitToViewport(movie_width,movie_height); // Fit item to viewport
						toInject = settings.flowplayer_markup.replace(/{width}/g,correctSizes['width']).replace(/{height}/g,correctSizes['height']).replace(/{wmode}/g,settings.wmode).replace(/{path}/g,images[setPosition]);
					break;
					case 'mp3':
						correctSizes = _fitToViewport(300,30); // Fit item to viewport
					        toInject = settings.flowplayer_markup.replace(/{width}/g,correctSizes['width']).replace(/{height}/g,correctSizes['height']).replace(/{wmode}/g,settings.wmode).replace(/{path}/g,imagesData[setPosition]['path'][0].replace(/\'/g, ''));
                                        break;
					case 'EBook':
						correctSizes = _fitToViewport(720,560); // Fit item to viewport
					        toInject = settings.ebook_markup.replace(/{width}/g,correctSizes['width']).replace(/{height}/g,correctSizes['height']).replace(/{wmode}/g,settings.wmode).replace(/{path}/g,escape(imagesData[setPosition]['path'][0].replace(/\'/g, '')));
                                        break;
					case 'flash':
						correctSizes = _fitToViewport(movie_width,movie_height); // Fit item to viewport
					
						flash_vars = images[setPosition];
						flash_vars = flash_vars.substring(images[setPosition].indexOf('flashvars') + 10,images[setPosition].length);

						filename = images[setPosition];
						filename = filename.substring(0,filename.indexOf('?'));
					
						toInject =  settings.flash_markup.replace(/{width}/g,correctSizes['width']).replace(/{height}/g,correctSizes['height']).replace(/{wmode}/g,settings.wmode).replace(/{path}/g,filename+'?'+flash_vars);
					break;
				
					case 'iframe':
						correctSizes = _fitToViewport(movie_width,movie_height); // Fit item to viewport
				
						frame_url = images[setPosition];
						frame_url = frame_url.substr(0,frame_url.indexOf('iframe')-1);
				
						toInject = settings.iframe_markup.replace(/{width}/g,correctSizes['width']).replace(/{height}/g,correctSizes['height']).replace(/{path}/g,frame_url);
					break;
				
					case 'inline':
						// to get the item height clone it, apply default width, wrap it in the prettyPhoto containers , then delete
						myClone = $(images[setPosition]).clone().css({'width':settings.default_width}).wrapInner('<div id="pp_full_res"><div class="pp_inline clearfix"></div></div>').appendTo($('body'));
						correctSizes = _fitToViewport($(myClone).width(),$(myClone).height());
						$(myClone).remove();
						toInject = settings.inline_markup.replace(/{content}/g,$(images[setPosition]).html());
					break;
					default:
						// Is a not controlled type, we have to return.
						$.prettyPhoto.close();
						return false;
				};

				if(!imgPreloader){
					$pp_pic_holder.find('#pp_full_res')[0].innerHTML = toInject;
				
					// Show content
					_showContent();
				};
			});

		};
		
		/**
		* Change page in the prettyPhoto modal box
		* @param direction {String} Direction of the paging, previous or next.
		*/
		$.prettyPhoto.changePage = function(direction){
			if(direction == 'previous') {
				setPosition--;
				if (setPosition < 0){
					setPosition = 0;
					return;
				};
			}else{
				if($('.pp_arrow_next').is('.disabled')) return;
				setPosition++;
			};

			// Allow the resizing of the images
			if(!doresize) doresize = true;
			_hideContent(function(){$.prettyPhoto.open(images,imagesData)});
			if($.browser.msie)
				$('a.pp_expand,a.pp_contract').hide();
			else
				$('a.pp_expand,a.pp_contract').fadeOut(settings.animationSpeed);
		};
		
		/**
		* Closes the prettyPhoto modal box.
		*/
		$.prettyPhoto.close = function(){
			$pp_pic_holder.find('object,embed').css('visibility','hidden');
			
			$('div.pp_pic_holder,.pp_fade').fadeOut(settings.animationSpeed);
			
			$pp_overlay.fadeOut(settings.animationSpeed, function(){
				$('#pp_full_res').html(''); // Kill the opened content
				
				$pp_pic_holder.attr('style','').find('div:not(.pp_hoverContainer)').attr('style',''); // Reset the width and everything that has been set.
				_centerOverlay(); // Center it
			
				// To fix the bug with IE select boxes
				if($.browser.msie && $.browser.version == 6){
					$('select').css('visibility','visible');
				};
				
				// Show the flash
				if(settings.hideflash) $('object,embed').css('visibility','visible');
				
				setPosition = 0;
				settings.callback();
			});
			doresize = true;
		};
	
		/**
		* Set the proper sizes on the containers and animate the content in.
		*/
		_showContent = function(){
			$('.pp_loaderIcon').hide();

			// Calculate the opened top position of the pic holder
			projectedTop = scrollPos['scrollTop'] + ((windowHeight/2) - (correctSizes['containerHeight']/2));
			if(projectedTop < 0) projectedTop = 0;

			// Resize the content holder
			$pp_pic_holder.find('.pp_content').animate({'height':correctSizes['contentHeight']},settings.animationSpeed);
			
			// Resize picture the holder
			$pp_pic_holder.animate({
				'top': projectedTop,
				'left': (windowWidth/2) - (correctSizes['containerWidth']/2),
				'width': (correctSizes['containerWidth']+((imagesData[setPosition]['type'] == 'mp3')?34:0))
			},settings.animationSpeed,function(){
				$pp_pic_holder.find('.pp_hoverContainer,#fullResImage').height(correctSizes['height']).width(correctSizes['width']);

				// IE6 Hack: lateral borders should be equal to the content
				if($.browser.msie && parseInt($.browser.version) == 6){
					$('.pp_content_container .pp_left').height($('.pp_fade').height());
					$('.pp_content_container .pp_right').height($('.pp_fade').height());
					/* Required for jquery 1.4.3 */
					$('.pp_content').css({'overflow':'visible'});
				}
                                if($.browser.msie){

                                 $('.pp_content').css({'overflow':'visible'});

                                }

				// Fade the new image
				$pp_pic_holder.find('.pp_fade').fadeIn(settings.animationSpeed);

				// Show navigation links
				if($(images).size() > 1) _checkPosition($(images).size());

				// Show the nav
				if(image_set && _getFileType(images[setPosition])=="image") { $pp_pic_holder.find('.pp_hoverContainer').show(); }else{ $pp_pic_holder.find('.pp_hoverContainer').hide(); }

				// Content alignment to left when playing mp3
				$pp_pic_holder.find('#pp_full_res').css('textAlign',(imagesData[setPosition]['type'] == 'mp3')?'left':'center');

				// Fade the resizing link if the image is resized, and is not an audio or video
				if(correctSizes['resized'])
					if(imagesData[setPosition]['type'] != 'audiovideo' && imagesData[setPosition]['type'] != 'flv' && imagesData[setPosition]['type'] != 'mp3')
						$('a.pp_expand,a.pp_contract').fadeIn(settings.animationSpeed);
				
				// Callback!
				settings.changepicturecallback();
			});
		};
		
		/**
		* Hide the content...DUH!
		*/
		function _hideContent(callback){
			// Fade out the current picture
			$pp_pic_holder.find('#pp_full_res object,#pp_full_res embed').css('visibility','hidden');
			$pp_pic_holder.find('.pp_fade').fadeOut(settings.animationSpeed,function(){
				$('.pp_loaderIcon').show();
				
				if(callback) callback();
			});
			
		}
	
		/**
		* Check the item position in the gallery array, hide or show the navigation links
		* @param setCount {integer} The total number of items in the set
		*/
		function _checkPosition(setCount){
			// If at the end, hide the next link
			if(setPosition == setCount-1) {
				$pp_pic_holder.find('a.pp_next').css('visibility','hidden');
				$pp_pic_holder.find('a.pp_arrow_next').addClass('disabled').unbind('click');
			}else{ 
				$pp_pic_holder.find('a.pp_next').css('visibility','visible');
				$pp_pic_holder.find('a.pp_arrow_next.disabled').removeClass('disabled').bind('click',function(){
					$.prettyPhoto.changePage('next');
					return false;
				});
			};
		
			// If at the beginning, hide the previous link
			if(setPosition == 0) {
				$pp_pic_holder.find('a.pp_previous').css('visibility','hidden');
				$pp_pic_holder.find('a.pp_arrow_previous').addClass('disabled').unbind('click');
			}else{
				$pp_pic_holder.find('a.pp_previous').css('visibility','visible');
				$pp_pic_holder.find('a.pp_arrow_previous.disabled').removeClass('disabled').bind('click',function(){
					$.prettyPhoto.changePage('previous');
					return false;
				});
			};
			
			// Hide the bottom nav if it's not a set.
			if(setCount > 1) {
				$('.pp_nav').fadeIn();
			}else{
				$('.pp_nav').hide();
			}
		};
	
		/**
		* Resize the item dimensions if it's bigger than the viewport
		* @param width {integer} Width of the item to be opened
		* @param height {integer} Height of the item to be opened
		* @return An array containin the "fitted" dimensions
		*/
		function _fitToViewport(width,height){
			hasBeenResized = false;

			_getDimensions(width,height);
			
			// Define them in case there's no resize needed
			imageWidth = width;
			imageHeight = height;

			if(imagesData[setPosition]['type'] != 'EBook') { // El tipo EBook no se debe ajustar a la ventana del navegador
				$pp_pic_holder.find('.pp_bottom').css('z-index','5');
			        if( ((pp_containerWidth > windowWidth) || (pp_containerHeight > windowHeight)) && doresize && settings.allowresize && !percentBased) {
				        hasBeenResized = true;
				        notFitting = true;

				        while (notFitting){
					        if((pp_containerWidth > windowWidth)){
						        imageWidth = (windowWidth - 200);
						        imageHeight = (height/width) * imageWidth;
					        }else if((pp_containerHeight > windowHeight)){
						        imageHeight = (windowHeight - 200);
						        imageWidth = (width/height) * imageHeight;
					        }else{
						        notFitting = false;
					        };

					        pp_containerHeight = imageHeight;
					        pp_containerWidth = imageWidth;
				        };

				        _getDimensions(imageWidth,imageHeight);
			        };
			}else{
				imageHeight += 20;
				$pp_pic_holder.find('.pp_bottom').css('z-index','10');
			};

			return {
				width:Math.floor(imageWidth),
				height:Math.floor(imageHeight),
				containerHeight:Math.floor(pp_containerHeight),
				containerWidth:Math.floor(pp_containerWidth) + 40,
				contentHeight:Math.floor(pp_contentHeight),
				contentWidth:Math.floor(pp_contentWidth),
				resized:hasBeenResized
			};
		};
		
		/**
		* Get the containers dimensions according to the item size
		* @param width {integer} Width of the item to be opened
		* @param height {integer} Height of the item to be opened
		*/
		function _getDimensions(width,height){

			width = (width>settings.min_width)?width:settings.min_width;

			width = parseFloat(width);
			height = parseFloat(height);
			
			// Get the details height, to do so, I need to clone it since it's invisible
			$pp_details = $pp_pic_holder.find('.pp_details');
			$pp_details.width(width);
			detailsHeight = parseFloat($pp_details.css('marginTop')) + parseFloat($pp_details.css('marginBottom'));
			$pp_details_clone = $pp_details.clone();
			$pp_details = $('<div class="'+settings.theme+'" />');
			$pp_details.append($pp_details_clone);
			$pp_details.appendTo($('body')).css({
				'position':'absolute',
				'top':-10000
			});
			detailsHeight += $pp_details.eq(0).height();
			//detailsHeight = (detailsHeight <= 34) ? 36 : detailsHeight; // Min-height for the details
			//if($.browser.msie && $.browser.version==7) detailsHeight+=8;
			$pp_details.remove();

			// Get the container size, to resize the holder to the right dimensions
			pp_contentHeight = height + detailsHeight;
			if($(images).size() == 1) pp_contentHeight -= $pp_pic_holder.find('.pp_nav').height(); // Remove navigation height if only one image
			pp_contentWidth = width;
			pp_containerHeight = pp_contentHeight +  $pp_pic_holder.find('.pp_top').height() + $pp_pic_holder.find('.pp_bottom').height();
			pp_containerHeight -= 20; // Remove 10px from .pp_top (bottom: -10px) and 10px from .pp_bottom (top: -10px)
			pp_containerWidth = width;
		}
	
		function _getFileType(itemSrc){
			if (itemSrc.match(/youtube\.com\/watch/i)) {
				return 'youtube';
			}else if (itemSrc.match(/vimeo\.com/i)) {
				return 'vimeo';
			}else if(itemSrc.indexOf('.mov') != -1){ 
				return 'quicktime';
			}else if(itemSrc.indexOf('.wmv') != -1){ 
				return 'wmedia';
			}else if(itemSrc.indexOf('.swf') != -1){
				return 'flash';
			}else if(itemSrc.indexOf('iframe') != -1){
				return 'iframe'
			}else if(itemSrc.substr(0,1) == '#'){
				return 'inline';
			}else{
				return 'image';
			};
		};
	
		function _centerOverlay(){
			if(doresize) {
				contentHeight = $pp_pic_holder.height();
				contentwidth = $pp_pic_holder.width();
				
				projectedTop = (windowHeight/2) + scrollPos['scrollTop'] - ((contentHeight)/2);
				
				$pp_pic_holder.css({
					'top': projectedTop,
					'left': (windowWidth/2) + scrollPos['scrollLeft'] - (contentwidth/2)
				});
			};
		};
	
		function _getScroll(){
			if (self.pageYOffset) {
				return {scrollTop:self.pageYOffset,scrollLeft:self.pageXOffset};
			} else if (document.documentElement && document.documentElement.scrollTop) { // Explorer 6 Strict
				return {scrollTop:document.documentElement.scrollTop,scrollLeft:document.documentElement.scrollLeft};
			} else if (document.body) {// all other Explorers
				return {scrollTop:document.body.scrollTop,scrollLeft:document.body.scrollLeft};
			};
		};
	
		function _resizeOverlay() {
			windowHeight = $(window).height();
			windowWidth = $(window).width();
			
			$pp_overlay.css({
				'height':$(document).height()
			});
		};
	
		function _buildOverlay(){
			// Inject the markup
			$('body').append(settings.markup);
			
			// Set my global selectors
			$pp_pic_holder = $('.pp_pic_holder');
			$ppt = $('.ppt');
			$pp_overlay = $('div.pp_overlay');
			
			$pp_pic_holder.attr('class','pp_pic_holder ' + settings.theme); // Set the proper theme

			// To fix the bug with IE6 and PNG images
			if($.browser.msie && $.browser.version == 6) {
				$pp_pic_holder.addClass('pp_ie6');
			}
			
			/*if($.browser.msie && $.browser.version >= 6) {
				$pp_pic_holder.addClass('pp_ie');
			}*/
			
			$pp_overlay
				.css({
					'opacity':0,
					'height':$(document).height()
					})
				.bind('click',function(){
					if(!settings.modal)
					$.prettyPhoto.close();
				});

			$('a.pp_close').bind('click',function(){ $.prettyPhoto.close(); return false; });

			$('a.pp_expand').bind('click',function(){
				$this = $(this); // Fix scoping
				
				// Expand the image
				if($this.hasClass('pp_expand')){
					$this.removeClass('pp_expand').addClass('pp_contract');
					doresize = false;
				}else{
					$this.removeClass('pp_contract').addClass('pp_expand');
					doresize = true;
				};
			
				_hideContent(function(){ $.prettyPhoto.open(images,imagesData) });
				
				$pp_pic_holder.find('.pp_fade').fadeOut(settings.animationSpeed);
		
				return false;
			});
		
			$pp_pic_holder.find('.pp_previous, .pp_arrow_previous').bind('click',function(){
				$.prettyPhoto.changePage('previous');
				return false;
			});
		
			$pp_pic_holder.find('.pp_next, .pp_arrow_next').bind('click',function(){
				$.prettyPhoto.changePage('next');
				return false;
			});
		};
		
		_centerOverlay(); // Center it
	};
	
	function grab_param(name,url){
	  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
	  var regexS = "[\\?&]"+name+"=([^&#]*)";
	  var regex = new RegExp( regexS );
	  var results = regex.exec( url );
	  if( results == null )
	    return "";
	  else
	    return results[1];
	}
	
	// This function allows reading the mmedia parameter from request uri, rather than
	// queryString.
	function getMmediaFromPathInfo(url) {
	  url = url.substring(url.lastIndexOf('/')+1);
	  var regexS = "([\\d]+)-.+$";
	  var regex = new RegExp( regexS );
	  var results = regex.exec( url );
	  if( results == null )
	    return "";
	  else
	    return results[1];
	}
	
	// This function decodes the data stored in data in the 
	// way ([key="value"])+, it converts this information
	// to an array indexed by key
	function decodeMap(data) {
		// The regular expresion we are going to eval
		var regexExpr = /\[([^=]+)=\"([^\"]+)\"\]/g;
		var results = regexExpr.exec(data);
		// The array - in which we are going to store data (indexed as a map of arrays)
		var resultsArray = new Array();
		while(results!=null) {
			// If the key exists in the map we add a new entry to it.
			if(resultsArray[results[1]]) {
				resultsArray[results[1]][resultsArray[results[1]].length] = results[2];
			} else {
				resultsArray[results[1]] = new Array();
				resultsArray[results[1]][0] = results[2];
			}
			// We check for new data...
			results = regexExpr.exec(data);
		}
		// Finally, we have eval the array, so we can return it.
		return resultsArray;
	}
})(jQuery);

