/* ------------------------------------------------------------------------
	Class: prettyPhoto
	Use: Lightbox clone for jQuery
	Author: Stephane Caron (http://www.no-margin-for-errors.com)
	Version: 2.1.1
------------------------------------------------------------------------- */

	$(document).ready(function(){
		prettyPhoto.init();
	});

	prettyPhoto = {
		options : {
			'animationSpeed' : 'fast', /* fast/normal/slow */
			'padding' : 40, /* padding for each side of the picture */
			'showTitle' : false
		},
		init : function(){
			// Find all the images to overlay
			prettyPhoto.imagesArray = [];
			$("a[rel^='prettyOverlay'],a[rel^='prettyPhoto']").each(function(){
				prettyPhoto.imagesArray[prettyPhoto.imagesArray.length] = this;
				$(this).bind('click',function(){
					prettyPhoto.open(this); return false;
				});
			});
			
			$(window).scroll(function(){ prettyPhoto.centerPicture(); });
			$(window).resize(function(){ prettyPhoto.centerPicture(); prettyPhoto.resizeOverlay(); })
		},
		open : function(caller) {
			prettyPhoto.caller = caller;
			
			// Find out if the picture is part of a set
			theRel = $(caller).attr('rel');
			galleryRegExp = /\[(?:.*)\]/;
			theGallery = galleryRegExp.exec(theRel);
			
			// Calculate the number of items in the set, and the position of the clicked picture.
			prettyPhoto.setCount = 0; /* Total images in the set */
			prettyPhoto.setPosition = 0; /* Position in the set */
			prettyPhoto.arrayPosition = 0; /* Total position in the array */
			prettyPhoto.isSet = false;
			for (i = 0; i < prettyPhoto.imagesArray.length; i++){
				if($(prettyPhoto.imagesArray[i]).attr('rel').indexOf(theGallery) != -1){
					prettyPhoto.setCount++;
					if(prettyPhoto.setCount > 1) prettyPhoto.isSet = true;

					if($(prettyPhoto.imagesArray[i]).attr('href') == $(caller).attr('href')){
						prettyPhoto.setPosition = prettyPhoto.setCount;
						prettyPhoto.arrayPosition = i;
					};
				};
			};
			
			prettyPhoto.buildOverlay(prettyPhoto.isSet);

			// Display the current position
			$('div.popup span.currentText').html('<span>' + prettyPhoto.setPosition + '</span>' + '/' + prettyPhoto.setCount);

			// Position the picture in the center of the viewing area
			prettyPhoto.centerPicture();
			
			$('div.popup #fullResImageContainer').hide();
			$('.loaderIcon').show();

			// Preload the neighbour images
			prettyPhoto.preload();
		},
		next : function(){
			// Change the current position
			prettyPhoto.arrayPosition++;
			prettyPhoto.setPosition++;

			// Fade out the current picture
			$('div.popup #fullResImageContainer').fadeOut(prettyPhoto.options['animationSpeed'],function(){
				$('.loaderIcon').show();
				
				// Preload the neighbour images
				prettyPhoto.preload();
			});
			
			prettyPhoto.hideTitle();
			$('div.popup .hoverContainer').fadeOut(prettyPhoto.options['animationSpeed']);
			$('div.popup .details').fadeOut(prettyPhoto.options['animationSpeed'],function(){
				prettyPhoto.checkPosition();
			});
		},
		previous: function(){
			// Change the current position
			prettyPhoto.arrayPosition--;
			prettyPhoto.setPosition--;

			// Fade out the current picture
			$('div.popup #fullResImageContainer').fadeOut(prettyPhoto.options['animationSpeed'],function(){
				$('.loaderIcon').show();
				
				// Preload the image
				prettyPhoto.preload();
			});

			prettyPhoto.hideTitle();
			$('div.popup .hoverContainer').fadeOut(prettyPhoto.options['animationSpeed']);
			$('div.popup .details').fadeOut(prettyPhoto.options['animationSpeed'],function(){
				prettyPhoto.checkPosition();
			});
		},
		checkPosition : function(){
			// If at the end, hide the next link
			(prettyPhoto.setPosition == prettyPhoto.setCount) ? $('div.popup a.next').hide() : $('div.popup a.next').show();
			
			// If at the beginning, hide the previous link
			(prettyPhoto.setPosition == 1) ? $('div.popup a.previous').hide() : $('div.popup a.previous').show();
			
			// Change the current picture text
			$('div.popup span.currentText span').text(prettyPhoto.setPosition);
			
			if (prettyPhoto.isSet) {
				if($(prettyPhoto.imagesArray[prettyPhoto.arrayPosition]).attr('title')){
					$('div.popup .description').html(unescape($(prettyPhoto.imagesArray[prettyPhoto.arrayPosition]).attr('title')));
				}else{
					$('div.popup .description').text('');
				};
				
				if($(prettyPhoto.imagesArray[prettyPhoto.arrayPosition]).find('img').attr('alt') && prettyPhoto.options['showTitle']){
					prettyPhoto.hasTitle = true;
					$('div.prettyPhotoTitle .prettyPhotoTitleContent').html(unescape($(prettyPhoto.imagesArray[prettyPhoto.arrayPosition]).find('img').attr('alt')));
				}else{
					prettyPhoto.hasTitle = false;
				};
			}else{
				if($(prettyPhoto.imagesArray[prettyPhoto.arrayPosition]).attr('title')){
					$('div.popup .description').html(unescape($(prettyPhoto.caller).attr('title')));
				}else{
					$('div.popup .description').text('');
				};
				
				if($(prettyPhoto.imagesArray[prettyPhoto.arrayPosition]).find('img').attr('alt') && prettyPhoto.options['showTitle']){
					prettyPhoto.hasTitle = true;
					$('div.prettyPhotoTitle .prettyPhotoTitleContent').html(unescape($(prettyPhoto.caller).find('img').attr('alt')));
				}else{
					prettyPhoto.hasTitle = false;
				};
			};
		},
		centerPicture : function(){
			//Make sure the gallery is open
			if($('div.popup').size() > 0){
				
				var scrollPos = prettyPhoto.getScroll();
				
				$('div.popup').css({
					'top': ($(window).height()/2) + scrollPos['scrollTop'] - ($('div.popup').height()/2),
					'left': ($(window).width()/2) + scrollPos['scrollLeft'] - ($('div.popup').width()/2)
				});
				
				$('div.prettyPhotoTitle').css({
					'top' : $('div.popup').offset().top - 22,
					'left' : $('div.popup').offset().left + (prettyPhoto.options['padding']/2)
				});
			};
		},
		preload : function(){
			// Hide the next/previous links if on first or last images.
			prettyPhoto.checkPosition();
			
			// Set the new image
			imgPreloader = new Image();
			
			// Preload the neighbour images
			nextImage = new Image();
			if(prettyPhoto.isSet) nextImage.src = $(prettyPhoto.imagesArray[prettyPhoto.arrayPosition + 1]).attr('href');
			
			prevImage = new Image();
			if(prettyPhoto.isSet && prettyPhoto.imagesArray[prettyPhoto.arrayPosition - 1]) prevImage.src = $(prettyPhoto.imagesArray[prettyPhoto.arrayPosition - 1]).attr('href');

			$('div.popup .content_foto').css('overflow','hidden');
			
			(prettyPhoto.isSet) ? $('div.popup #fullResImage').attr('src',$(prettyPhoto.imagesArray[prettyPhoto.arrayPosition]).attr('href')) : $('div.popup #fullResImage').attr('src',$(prettyPhoto.caller).attr('href'));

			imgPreloader.onload = function(){
				var correctSizes = prettyPhoto.resize(imgPreloader.width,imgPreloader.height);
				imgPreloader.width = correctSizes['width'];
				imgPreloader.height = correctSizes['height'];
				
				// Need that small delay for the anim to be nice
				setTimeout('prettyPhoto.showimage(imgPreloader.width,imgPreloader.height,'+correctSizes["containerWidth"]+','+correctSizes["containerHeight"]+','+correctSizes["contentWidth"]+')',500);
			};
			
			(prettyPhoto.isSet) ? imgPreloader.src = $(prettyPhoto.imagesArray[prettyPhoto.arrayPosition]).attr('href') : imgPreloader.src = $(prettyPhoto.caller).attr('href');
		},
		showimage : function(width,height,containerWidth,containerHeight,contentWidth){
			$('.loaderIcon').hide();
			
			$('div.popup .content_foto').animate({'height':contentHeight},prettyPhoto.options['animationSpeed']);

			var scrollPos = prettyPhoto.getScroll();

			// Resize the holder
			$('div.popup').animate({
				'top': scrollPos['scrollTop'] + (($(window).height()/2) - (containerHeight/2)),
				'left': (($(window).width()/2) - (containerWidth/2)),
				'width':containerWidth
			},prettyPhoto.options['animationSpeed'],function(){
				$('#fullResImage').attr({
					'width':width,
					'height':height
				});

				// Show the nav elements
				prettyPhoto.shownav();

				$('div.popup .hoverContainer').height(height).width(width);

				// Fade the new image
				$('div.popup #fullResImageContainer').fadeIn(prettyPhoto.options['animationSpeed']);
			});	
		},
		shownav : function(){
			if(prettyPhoto.isSet) $('div.popup .hoverContainer').fadeIn(prettyPhoto.options['animationSpeed']);
			$('div.popup .details').fadeIn(prettyPhoto.options['animationSpeed']);

			prettyPhoto.showTitle();
		},
		showTitle : function(){
			if(prettyPhoto.options['showTitle'] && prettyPhoto.hasTitle){
				$('div.prettyPhotoTitle').css({
					'top' : $('div.popup').offset().top,
					'left' : $('div.popup').offset().left + (prettyPhoto.options['padding']/2),
					'display' : 'block'
				});
				
				$('div.prettyPhotoTitle div.prettyPhotoTitleContent').css('width','auto');
				
				if($('div.prettyPhotoTitle').width() > $('div.popup').width()){
					$('div.prettyPhotoTitle div.prettyPhotoTitleContent').css('width',$('div.popup').width() - (prettyPhoto.options['padding'] * 2));
				}else{
					$('div.prettyPhotoTitle div.prettyPhotoTitleContent').css('width','');
				};
				
				$('div.prettyPhotoTitle').animate({'top':($('div.popup').offset().top - 22)},prettyPhoto.options['animationSpeed']);
			};
		},
		hideTitle : function() {
			$('div.prettyPhotoTitle').animate({'top':($('div.popup').offset().top)},prettyPhoto.options['animationSpeed'],function() { $(this).css('display','none'); });
		},
		buildOverlay : function(){
			
			// Build the background overlay div
			backgroundDiv = "<div class='popupOverlay'></div>";
 			$('body').append(backgroundDiv);
			$('div.popupOverlay').css('height',$(document).height());
			$('.popupOverlay').bind('click',function(){
				prettyPhoto.close();
			});
			
			// Basic HTML for the picture holder
			pictureHolder = '<div class="popup popup_foto"><div class="top"><div class="left"></div><div class="middle"></div><div class="right"></div></div><div class="content_foto"><div class="loaderIcon"></div><div class="hoverContainer"><a class="next" href="#">next</a><a class="previous" href="#">previous</a></div><div id="fullResImageContainer"><img id="fullResImage" src="" /></div><div class="details clearfix"><a class="close" href="#">Close</a><p class="description"></p><p class="currentTextHolder"><span class="currentText"><span>0</span>/<span class="total">0</span></span></p></div></div><div class="bottom"><div class="left"></div><div class="middle"></div><div class="right"></div></div></div>';
			
			// Basic html for the title holder
			titleHolder = '<div class="prettyPhotoTitle"><div class="prettyPhotoTitleLeft"></div><div class="prettyPhotoTitleContent"></div><div class="prettyPhotoTitleRight"></div></div>';

			$('body').append(pictureHolder).append(titleHolder);

			$('.popup,.titleHolder').css({'opacity': 0});
			$('a.close').bind('click',function(){ prettyPhoto.close(); return false; });
			
			$('.popup .previous').bind('click',function(){
				prettyPhoto.previous();
				return false;
			});
			
			$('.popup .next').bind('click',function(){
				prettyPhoto.next();
				return false;
			});

			$('.hoverContainer').css({
				'margin-left':prettyPhoto.options['padding']/2,
				'margin-right':prettyPhoto.options['padding']/2
			});
			
			// If it's not a set, hide the links
			if(!prettyPhoto.isSet) {
				$('.hoverContainer').hide();
				$('.currentTextHolder').hide();
			};

			// Then fade it in
			$('div.popupOverlay').css('opacity',0);
			$('div.popupOverlay').fadeTo(prettyPhoto.options['animationSpeed'],0.35, function(){
				$('div.popup').fadeTo(prettyPhoto.options['animationSpeed'],1,function(){
					// To fix an IE bug
					$('div.popup').attr('style','left:'+$('div.popup').css('left')+';top:'+$('div.popup').css('top')+';');
				});
			});
		},
		resize : function(width,height){
			$('div.popup .details').width(width); /* To have the correct height */
			$('div.popup .details p.description').width(width - parseFloat($('div.popup a.close').css('width'))); /* So it doesn't overlap the button */
			
			// Get the container size, to resize the holder to the right dimensions
			contentHeight = parseFloat($('div.popup .details').height()) + parseFloat($('div.popup .details').css('margin-top')) + parseFloat($('div.popup .details').css('margin-bottom'));
			containerHeight = contentHeight + parseFloat($('div.popup .top').height()) + parseFloat($('div.popup .bottom').height());
			containerWidth = parseFloat($('div.popup .content_foto').css("padding-left")) + parseFloat($('div.popup .content_foto').css("padding-right")) + prettyPhoto.options['padding'];
			
			var newWidth = width;
			var newHeight = height;
			
			// If there's a title, take it into consideration unpon resizing
			if(prettyPhoto.options['showTitle']) containerHeight -= 22;
			
			if((containerWidth + width) > $(window).width() || (containerHeight + height) > $(window).height()) {
				// Get the original geometry and calculate scales
				var xscale=(width+containerWidth + 100)/$(window).width();
				var yscale=(height+containerHeight + 100)/$(window).height();
			
				// Recalculate new size with default ratio
				if (yscale>xscale){
					newWidth = Math.round(width * (1/yscale));
					newHeight = Math.round(height * (1/yscale));
				} else {
					newWidth = Math.round(width * (1/xscale));
					newHeight = Math.round(height * (1/xscale));
				};
			};

			// Get the container size, to resize the holder to the right dimensions
			containerHeight += newHeight;
			contentHeight += newHeight;
			containerWidth += newWidth;
		
			$('div.popup .details').width(newWidth); /* To have the correct height */
			$('div.popup .details p.description').width(newWidth - parseFloat($('div.popup a.close').css('width'))); /* So it doesn't overlap the button */

			return {
				width:newWidth,
				height:newHeight,
				containerHeight:containerHeight,
				containerWidth:containerWidth,
				contentHeight:contentHeight
			};
		},
		resizeOverlay : function() {
			$('div.popupOverlay').css({
				'height':$(document).height(),
				'width':$(window).width()
			});
		},
		getScroll : function(){
			scrollTop = window.pageYOffset || document.documentElement.scrollTop || 0;
			scrollLeft = window.pageXOffset || document.documentElement.scrollLeft || 0;
			return {scrollTop:scrollTop,scrollLeft:scrollLeft};
		},
		close : function(){
			$('div.popup,div.prettyPhotoTitle').fadeTo(prettyPhoto.options['animationSpeed'],0, function(){
				$('div.popupOverlay').fadeTo(prettyPhoto.options['animationSpeed'],0, function(){
					$('div.popupOverlay').remove();
					$('div.popup').remove();
				});
			});
		}
	}

/*
 * Copyright 2007-2008 by Tobia Conforto <tobia.conforto@gmail.com>
 *
 * This program is free software; you can redistribute it and/or modify it under the terms of the GNU General
 * Public License as published by the Free Software Foundation; either version 2 of the License, or (at your
 * option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the
 * implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
 * for more details.
 *
 * You should have received a copy of the GNU General Public License along with this program; if not, write to
 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 *
 * Versions: 0.1    2007-08-19  Initial release
 *                  2008-08-21  Re-released under GPL v2
 *           0.1.1  2008-09-18  Compatibility with prototype.js
 *           0.2    2008-10-15  Linkable images, contributed by Tim Rainey <tim@zmlabs.com>
 *           0.3    2008-10-22  Added option to repeat the animation a number of times, then stop
 */

jQuery.fn.crossSlide = function(opts, plan) {
	var self = this,
			self_width = this.width(),
			self_height = this.height();

	// generic utilities
	function format(str) {
		for (var i = 1; i < arguments.length; i++)
			str = str.replace(new RegExp('\\{' + (i-1) + '}', 'g'), arguments[i]);
		return str;
	}

	function dump_obj(o) {
		var s = '{ ';
		for (var n in o)
			s += n + ': ' + o[n] + ', ';
		return (s == '{ ' ? '{}' : s.slice(0, -2) + ' }');
	}

	// first preload all the images, while getting their actual width and height
	(function(proceed) {

		var n_loaded = 0;
		function loop(i, img) {
			// for (i = 0; i < plan.length; i++) but with independent var i, img (for the closures)
			img.onload = function(e) {
				n_loaded++;
				plan[i].width = img.width;
				plan[i].height = img.height;
				if (n_loaded == plan.length)
					proceed();
			}
			img.src = plan[i].src;
			if (i + 1 < plan.length)
				loop(i + 1, new Image());
		}
		loop(0, new Image());

	})(function() {  // then proceed

		// utility to parse "from" and "to" parameters
		function parse_position_param(param) {
			var zoom = 1;
			var tokens = param.replace(/^\s*|\s*$/g, '').split(/\s+/);
			if (tokens.length > 3) throw new Error();
			if (tokens[0] == 'center')
				if (tokens.length == 1)
					tokens = ['center', 'center'];
				else if (tokens.length == 2 && tokens[1].match(/^[\d.]+x$/i))
					tokens = ['center', 'center', tokens[1]];
			if (tokens.length == 3)
				zoom = parseFloat(tokens[2].match(/^([\d.]+)x$/i)[1]);
			var pos = tokens[0] + ' ' + tokens[1];
			if (pos == 'left top'      || pos == 'top left')      return { xrel:  0, yrel:  0, zoom: zoom };
			if (pos == 'left center'   || pos == 'center left')   return { xrel:  0, yrel: .5, zoom: zoom };
			if (pos == 'left bottom'   || pos == 'bottom left')   return { xrel:  0, yrel:  1, zoom: zoom };
			if (pos == 'center top'    || pos == 'top center')    return { xrel: .5, yrel:  0, zoom: zoom };
			if (pos == 'center center')                           return { xrel: .5, yrel: .5, zoom: zoom };
			if (pos == 'center bottom' || pos == 'bottom center') return { xrel: .5, yrel:  1, zoom: zoom };
			if (pos == 'right top'     || pos == 'top right')     return { xrel:  1, yrel:  0, zoom: zoom };
			if (pos == 'right center'  || pos == 'center right')  return { xrel:  1, yrel: .5, zoom: zoom };
			if (pos == 'right bottom'  || pos == 'bottom right')  return { xrel:  1, yrel:  1, zoom: zoom };
			return {
				xrel: parseInt(tokens[0].match(/^(\d+)%$/)[1]) / 100,
				yrel: parseInt(tokens[1].match(/^(\d+)%$/)[1]) / 100,
				zoom: zoom
			};
		}

		// utility to compute the css for a given phase between p.from and p.to
		// phase = 1: begin fade-in,  2: end fade-in,  3: begin fade-out,  4: end fade-out
		function position_to_css(p, phase) {
			switch (phase) {
				case 1:
					var pos = 0;
					break;
				case 2:
					var pos = fade_ms / (p.time_ms + 2 * fade_ms);
					break;
				case 3:
					var pos = 1 - fade_ms / (p.time_ms + 2 * fade_ms);
					break;
				case 4:
					var pos = 1;
					break;
			}
			return {
				left:   Math.round(p.from.left   + pos * (p.to.left   - p.from.left  )),
				top:    Math.round(p.from.top    + pos * (p.to.top    - p.from.top   )),
				width:  Math.round(p.from.width  + pos * (p.to.width  - p.from.width )),
				height: Math.round(p.from.height + pos * (p.to.height - p.from.height))
			};
		}

		// check global params
		if (! opts.fade)
			throw 'Missing fade parameter.';
		if (opts.speed && opts.sleep)
			throw 'You cannot set both speed and sleep at the same time.';
		// conversion from sec to ms; from px/sec to px/ms
		var fade_ms = Math.round(opts.fade * 1000);
		if (opts.sleep)
			var sleep = Math.round(opts.sleep * 1000);
		if (opts.speed)
			var speed = opts.speed / 1000,
					fade_px = Math.round(fade_ms * speed);

		// a debug: true option may be added to get a dump of the generated JavaScript code
		if (opts.debug)
			var debug = jQuery('<pre><hr/></pre>');

		// set container css
		self.empty().css({
			overflow: 'hidden',
			padding: 0
		});
		if (! self.css('position').match(/absolute|relative|fixed/))
			self.css({ position: 'relative' })

		// prepare each image
		for (var i = 0; i < plan.length; ++i) {

			var p = plan[i];
			if (! p.src)
				throw format('Missing src parameter in picture {0}.', i + 1);

			if (speed) { // speed/dir mode

				// check parameters and translate speed/dir mode into full mode (from/to/time)
				switch (p.dir) {
					case 'up':
						p.from = { xrel: .5, yrel: 0, zoom: 1 };
						p.to   = { xrel: .5, yrel: 1, zoom: 1 };
						var slide_px = p.height - self_height - 2 * fade_px;
						break;
					case 'down':
						p.from = { xrel: .5, yrel: 1, zoom: 1 };
						p.to   = { xrel: .5, yrel: 0, zoom: 1 };
						var slide_px = p.height - self_height - 2 * fade_px;
						break;
					case 'left':
						p.from = { xrel: 0, yrel: .5, zoom: 1 };
						p.to   = { xrel: 1, yrel: .5, zoom: 1 };
						var slide_px = p.width - self_width - 2 * fade_px;
						break;
					case 'right':
						p.from = { xrel: 1, yrel: .5, zoom: 1 };
						p.to   = { xrel: 0, yrel: .5, zoom: 1 };
						var slide_px = p.width - self_width - 2 * fade_px;
						break;
					default:
						throw format('Missing or malformed "dir" parameter in picture {0}.', i + 1);
				}
				if (slide_px <= 0)
					throw format('Picture number {0} is too short for the desired fade duration.', i + 1);
				p.time_ms = Math.round(slide_px / speed);

			} else if (! sleep) { // full mode

				// check and parse parameters
				if (! p.from || ! p.to || ! p.time)
					throw format('Missing either speed/sleep option, or from/to/time params in picture {0}.', i + 1);
				try {
					p.from = parse_position_param(p.from)
				} catch (e) {
					throw format('Malformed "from" parameter in picture {0}.', i + 1);
				}
				try {
					p.to = parse_position_param(p.to)
				} catch (e) {
					throw format('Malformed "to" parameter in picture {0}.', i + 1);
				}
				if (! p.time)
					throw format('Missing "time" parameter in picture {0}.', i + 1);
				p.time_ms = Math.round(p.time * 1000)
			}

			// precalculate left/top/width/height bounding values
			if (p.from)
				jQuery.each([ p.from, p.to ], function(i, from_to) {
					from_to.width  = Math.round(p.width  * from_to.zoom);
					from_to.height = Math.round(p.height * from_to.zoom);
					from_to.left   = Math.round((self_width  - from_to.width)  * from_to.xrel);
					from_to.top    = Math.round((self_height - from_to.height) * from_to.yrel);
				});

			// append the image element to the container
			var html = p.href
					? format('<a href="{0}"><img src="{1}"/></a>', p.href, p.src)
					: format('<img src="{0}"/>', p.src);
			jQuery(html).appendTo(self).css({
				position: 'absolute',
				visibility: 'hidden'
			});
		}
		speed = undefined;  // speed mode has now been translated to full mode

		var imgs = self.children();

		// show first image
		imgs.eq(0).css({ visibility: 'visible' });
		if (! sleep)
			imgs.eq(0).css(position_to_css(plan[0], 2));

		// create animation chain
		var countdown = opts.loop;
		function create_chain(i, chainf) {
			// building the chain backwards, or inside out

			if (i % 2 == 0) {
				if (sleep) {

					// still image sleep

					var i_sleep = i / 2,
							i_hide = (i_sleep - 1 + plan.length) % plan.length,
							img_sleep = imgs.eq(i_sleep),
							img_hide = imgs.eq(i_hide);

					var newf = function() {
						img_hide.css('visibility', 'hidden');
						setTimeout(chainf, sleep);
					};

					if (debug)
						debug.prepend('<hr/>'
							+ format("img[{0}].css(visibility, hidden)\n", i_hide)
							+ format("setTimeout(&#9660;, {0})", sleep));

				} else {

					// single image slide

					var i_slide = i / 2,
							i_hide = (i_slide - 1 + plan.length) % plan.length,
							img_slide = imgs.eq(i_slide),
							img_hide = imgs.eq(i_hide),
							time = plan[i_slide].time_ms,
							slide_anim = position_to_css(plan[i_slide], 3);

					var newf = function() {
						img_hide.css('visibility', 'hidden');
						img_slide.animate(slide_anim, time, 'linear', chainf);
					};

					if (debug)
						debug.prepend('<hr/>'
							+ format("img[{0}].css(visibility, hidden)\n", i_hide)
							+ format("img[{0}].animate({1}, {2}, linear, &#9660;)", i_slide, dump_obj(slide_anim), time));

				}
			} else {
				if (sleep) {

					// still image cross-fade

					var i_from = Math.floor(i / 2),
							i_to = Math.ceil(i / 2) % plan.length,
							img_from = imgs.eq(i_from),
							img_to = imgs.eq(i_to),
							from_anim = {},
							to_init = { visibility: 'visible' },
							to_anim = {};

					if (i_to > i_from) {
						to_init.opacity = 0;
						to_anim.opacity = 1;
					} else {
						from_anim.opacity = 0;
					}

					var newf = function() {
						img_to.css(to_init);
						if (from_anim.opacity != undefined)
							img_from.animate(from_anim, fade_ms, 'linear', chainf);
						else
							img_to.animate(to_anim, fade_ms, 'linear', chainf);
					};

					if (debug)
						debug.prepend('<hr/>'
							+ format("img[{0}].css({1})\n", i_to, dump_obj(to_init))
							+ (from_anim.opacity != undefined
								? format("img[{0}].animate({1}, {2}, linear, &#9660;)", i_from, dump_obj(from_anim), fade_ms)
								: format("img[{0}].animate({1}, {2}, linear, &#9660;)", i_to, dump_obj(to_anim), fade_ms)));

				} else {

					// cross-slide + cross-fade

					var i_from = Math.floor(i / 2),
							i_to = Math.ceil(i / 2) % plan.length,
							img_from = imgs.eq(i_from),
							img_to = imgs.eq(i_to),
							from_anim = position_to_css(plan[i_from], 4),
							to_init = position_to_css(plan[i_to], 1),
							to_anim = position_to_css(plan[i_to], 2);

					if (i_to > i_from) {
						to_init.opacity = 0;
						to_anim.opacity = 1;
					} else {
						from_anim.opacity = 0;
					}
					to_init.visibility = 'visible';

					var newf = function() {
						img_from.animate(from_anim, fade_ms, 'linear');
						img_to.css(to_init);
						img_to.animate(to_anim, fade_ms, 'linear', chainf);
					};

					if (debug)
						debug.prepend('<hr/>'
							+ format("img[{0}].animate({1}, {2}, linear)\n", i_from, dump_obj(from_anim), fade_ms)
							+ format("img[{0}].css({1})\n", i_to, dump_obj(to_init))
							+ format("img[{0}].animate({1}, {2}, linear, &#9660;)", i_to, dump_obj(to_anim), fade_ms));

				}
			}

			// if the loop option was requested, push a countdown check
			if (opts.loop && i == plan.length * 2 - 2) {
				var newf_orig = newf;
				newf = function() {
					if (--countdown) newf_orig();
				}
			}

			if (i > 0)
				return create_chain(i - 1, newf);
			else
				return newf;
		}
		var animation = create_chain(plan.length * 2 - 1, function() { return animation(); });

		// show debug window, if enabled
		if (debug)
			jQuery(window.open('', 'debug', 'width=600,height=500,menubar=no,toolbar=no,directories=no,'
					+ 'location=no,status=no,scrollbars=yes,resizable=yes').document.body)
				.empty()
				.append(debug);

		// start animation
		animation();

	});

	return self;
};



/*
	jQuery Coda-Slider v1.1 - http://www.ndoherty.com/coda-slider
	
	Copyright (c) 2007 Niall Doherty
	
	Inspired by the clever folks at http://www.panic.com/coda
	Many thanks to Gian Carlo Mingati. Coda-Slider is a heavily modified version of his slideViewer, which can be found at  http://www.gcmingati.net/wordpress/wp-content/lab/jquery/imagestrip/imageslide-plugin.html
	
	Requirements:
	-  jQuery 1.2 ... available via  http://www.jquery.com
	-  jQuery easing plugin (1.2) ... available via  http://gsgd.co.uk/sandbox/jquery/easing/
	- jQuery easing compatability plugin ... available via  http://gsgd.co.uk/sandbox/jquery/easing/
	- CSS included in index.html
*/

var j = 0;
jQuery.fn.codaSlider = function(settings) {
	 settings = jQuery.extend({
     easeFunc: "expoinout",
     easeTime: 750,
     toolTip: false
  }, settings);
	return this.each(function(){
		var container = jQuery(this);
		// Get the width of a panel, set from CSS...
		var panelWidth = container.find("div.panel").width();
		// panelCount gives us a count of the panels in the container...
		var panelCount = container.find("div.panel").size();
		// Calculate the width of all the panels when lined up end-to-end...
		var stripViewerWidth = panelWidth*panelCount;
		// Use the above width to specify the CSS width for the panelContainer element...
		container.find("div.panelContainer").css("width" , stripViewerWidth);
		// Set the navWidth as a multiple of panelCount to account for margin-right on each li
		var navWidth = panelCount*2;
		
		// Specify the current panel.
		// If the loaded URL has a hash (cross-linking), we're going to use that hash to give the slider a specific starting position...
		if (location.hash && parseInt(location.hash.slice(1)) <= panelCount) {
			var cPanel = parseInt(location.hash.slice(1));
			var cnt = - (panelWidth*(cPanel - 1));
			jQuery(this).find("div.panelContainer").css({ left: cnt });
		// Otherwise, we'll just set the current panel to 1...
		} else { 
			var cPanel = 1;
		};
		
		// Create appropriate nav
		container.each(function(i) {
			// Create the Tabs
			jQuery(this).before("<div class='stripNav' id='stripNav" + j + "'><ul><\/ul><\/div>");
			jQuery(this).find("div.panel").each(function(n) {
				if( cPanel - 1 == n )
					jQuery("div#stripNav" + j + " ul").append("<li class='menu" + (n+1) + " actiu'><a href='la-carta#" + (n+1) + "'><\/a><\/li>");
				else
					jQuery("div#stripNav" + j + " ul").append("<li class='menu" + (n+1) + "'><a href='la-carta#" + (n+1) + "'><\/a><\/li>");
			});
			
			// Tab nav
			jQuery("div#stripNav" + j + " a").each(function(z) {
				// Figure out the navWidth by adding up the width of each li
				navWidth += jQuery(this).parent().width();
				// What happens when a nav link is clicked
				jQuery(this).bind("click", function() {
					jQuery(this).parent().addClass('actiu').parent().parent().find("li").not(jQuery(this)).removeClass('actiu'); // wow!
					jQuery(this).parent().addClass('actiu');
					var cnt = - (panelWidth*z);
					cPanel = z + 1;
					jQuery(this).parent().parent().parent().next().find("div.panelContainer").animate({ left: cnt}, settings.easeTime, settings.easeFunc);
				});
			});
		});
		
		j++;
  });
};



previsualitzar = {
	init : function( id_article, lloc ){
		previsualitzar.buildOverlay( id_article, lloc );

		// Display the current position
		$('div.popup span.currentText').html('<span>' + previsualitzar.setPosition + '</span>' + '/' + previsualitzar.setCount);

		previsualitzar.center();

		$('div.popup #fullResContainer').hide();
		$('.loaderIcon').show();
		
		// Need that small delay for the anim to be nice
		setTimeout('previsualitzar.show()',500);
		
		
		$('div.popupOverlay').css({
			'height':$(document).height(),
			'width':$(window).width()
		});
		
		$(window).scroll(function(){ previsualitzar.center(); });
		$(window).resize(function(){ previsualitzar.center(); })
	},
	center : function(){
		//Make sure the gallery is open
		if($('div.popup').size() > 0){
			
			scrollTop = window.pageYOffset || document.documentElement.scrollTop || 0;
			scrollLeft = window.pageXOffset || document.documentElement.scrollLeft || 0;
			
			$('div.popup').css({
				'top': ($(window).height()/2) + scrollTop - ($('div.popup').height()/2),
				'left': ($(window).width()/2) + scrollLeft - ($('div.popup').width()/2)
			});
		};
	},
	show : function(){
		$('.loaderIcon').hide();
		$('div.popup #fullResContainer').fadeIn('fast');
	},
	buildOverlay : function( id_article, lloc ){
		// Build the background overlay div
		backgroundDiv = "<div class='popupOverlay'></div>";
		$('body').append(backgroundDiv);
		$('div.popupOverlay').css('height',$(document).height());
		$('.popupOverlay').bind('click',function(){
			previsualitzar.close();
		});
		
		var nom = $("#nom").val();
		var comentari = $("#comentari").val();
		
		// Basic HTML
		html = '<div class="popup popup_previsualitzar"><div class="top"><div class="left"></div><div class="middle"></div><div class="right"></div></div><div class="content_previsualitzar"><div class="loaderIcon"></div><div id="fullResContainer">';
		html += '		<h4 class="vermell">Previsualització</h4>\n';
		
		if( comentari )
		{
			html += '		<strong class="vermell">Nom:</strong> '+ nom +'<br /><br />\n';
			html += '		<strong class="vermell">Comentari:</strong><br />'+ comentari +'<br /><br />\n';
		}
		else
		{
			html += '		<br />No hi ha cap comentari per previsualitzar<br /><br /><br />\n';
		}
		
		html += '<div style="float: right; padding-top: 5px"><a onclick="previsualitzar.close()"><img src="/img/icones/btnClose.gif" alt="tancar" /></a></div><br class="p" /></div></div><div class="bottom"><div class="left"></div><div class="middle"></div><div class="right"></div></div></div>';
		$('body').append(html);
		
		

		// Then fade it in
		$('div.popupOverlay').css('opacity',0);
		$('div.popupOverlay').fadeTo('fast',0.35, function(){
			$('div.popup').fadeTo('fast',1,function(){
				// To fix an IE bug
				$('div.popup').attr('style','left:'+$('div.popup').css('left')+';top:'+$('div.popup').css('top')+';');
			});
		});
	},
	resize : function(width,height){
		// Get the container size, to resize the holder to the right dimensions
		containerHeight = contentHeight + parseFloat($('div.popup .top').height()) + parseFloat($('div.popup .bottom').height());
		containerWidth = parseFloat($('div.popup .content_previsualitzar').css("padding-left")) + parseFloat($('div.popup .content_previsualitzar').css("padding-right"));
		
		var newWidth = width;
		var newHeight = height;
		
		if((containerWidth + width) > $(window).width() || (containerHeight + height) > $(window).height()) {
			// Get the original geometry and calculate scales
			var xscale=(width+containerWidth + 100)/$(window).width();
			var yscale=(height+containerHeight + 100)/$(window).height();
		
			// Recalculate new size with default ratio
			if (yscale>xscale){
				newWidth = Math.round(width * (1/yscale));
				newHeight = Math.round(height * (1/yscale));
			} else {
				newWidth = Math.round(width * (1/xscale));
				newHeight = Math.round(height * (1/xscale));
			};
		};

		// Get the container size, to resize the holder to the right dimensions
		containerHeight += newHeight;
		contentHeight += newHeight;
		containerWidth += newWidth;
	
		return {
			width:newWidth,
			height:newHeight
		};
	},
	close : function(){
		$('div.popup').fadeTo('fast',0, function(){
			$('div.popupOverlay').fadeTo('fast',0, function(){
				$('div.popupOverlay').remove();
				$('div.popup').remove();
				$('.publicitat').css({ display: "block" });
			});
		});
	}
}


enviarEmail = {
	init : function( id_article, lloc ){
		$('.publicitat').css({ display: "none" });
		
		enviarEmail.buildOverlay( id_article, lloc );

		// Display the current position
		$('div.popup span.currentText').html('<span>' + enviarEmail.setPosition + '</span>' + '/' + enviarEmail.setCount);

		enviarEmail.center();

		$('div.popup #fullResContainer').hide();
		$('.loaderIcon').show();
		
		// Need that small delay for the anim to be nice
		setTimeout('enviarEmail.show()',500);
		
		
		$('div.popupOverlay').css({
			'height':$(document).height(),
			'width':$(window).width()
		});
		
		$(window).scroll(function(){ enviarEmail.center(); });
		$(window).resize(function(){ enviarEmail.center(); })
	},
	center : function(){
		//Make sure the gallery is open
		if($('div.popup').size() > 0){
			
			scrollTop = window.pageYOffset || document.documentElement.scrollTop || 0;
			scrollLeft = window.pageXOffset || document.documentElement.scrollLeft || 0;
			
			$('div.popup').css({
				'top': ($(window).height()/2) + scrollTop - ($('div.popup').height()/2),
				'left': ($(window).width()/2) + scrollLeft - ($('div.popup').width()/2)
			});
		};
	},
	show : function(){
		$('.loaderIcon').hide();
		$('div.popup #fullResContainer').fadeIn('fast');
	},
	buildOverlay : function( id_article, lloc ){
		// Build the background overlay div
		backgroundDiv = "<div class='popupOverlay'></div>";
		$('body').append(backgroundDiv);
		$('div.popupOverlay').css('height',$(document).height());
		$('.popupOverlay').bind('click',function(){
			enviarEmail.close();
		});
		
		// Basic HTML
		html = '<div class="popup popup_email"><div class="top"><div class="left"></div><div class="middle"></div><div class="right"></div></div><div class="content_email"><div class="loaderIcon"></div><div id="fullResContainer">';
		
		html += '		<h4 class="vermell">Enviar article</h4>\n';
		html += '		<input type="hidden" id="id_article" value="'+ id_article +'" />\n';
		html += '		<label for="nom_e">Nom del destinatari</label>\n';
		html += '		<input id="nom_e" type="text" value="" name="nom" />\n';
		html += '		<br class="p" />\n';
		html += '		<label for="email_e">Correu electrònic del destinatari</label>\n';
		html += '		<input id="email_e" type="text" value="" name="email" />\n';
		html += '		<br class="p" />\n';
		html += '		<label for="r_nom">El teu nom</label>\n';
		html += '		<input id="r_nom" type="text" value="" name="r_nom" />\n';
		html += '		<br class="p" />\n';
		html += '		<label for="r_email">El teu correu</label>\n';
		html += '		<input id="r_email" type="text" value="" name="r_email" />\n';
		html += '		<br class="p" />\n';
		html += '		<label for="comentari">Comentari</label>\n';
		html += '		<textarea id="comentari" name="comentari"></textarea><br /><br />\n';
		html += '		<input type="hidden" id="url_enviar" value="'+ lloc  +'" />\n';
		html += '		<div style="float: left;"><input type="button" onclick="enviarEmail.enviar()" value="ENVIAR" class="enviar" /></div>\n';
		html += '<div style="float: right; padding-top: 5px"><a onclick="enviarEmail.close()"><img src="/img/icones/btnClose.gif" alt="tancar" /></a></div><br class="p" /></div></div><div class="bottom"><div class="left"></div><div class="middle"></div><div class="right"></div></div></div>';
		
		$('body').append(html);

		// Then fade it in
		$('div.popupOverlay').css('opacity',0);
		$('div.popupOverlay').fadeTo('fast',0.35, function(){
			$('div.popup').fadeTo('fast',1,function(){
				// To fix an IE bug
				$('div.popup').attr('style','left:'+$('div.popup').css('left')+';top:'+$('div.popup').css('top')+';');
			});
		});
	},
	resize : function(width,height){
		// Get the container size, to resize the holder to the right dimensions
		containerHeight = contentHeight + parseFloat($('div.popup .top').height()) + parseFloat($('div.popup .bottom').height());
		containerWidth = parseFloat($('div.popup .content_email').css("padding-left")) + parseFloat($('div.popup .content_email').css("padding-right"));
		
		var newWidth = width;
		var newHeight = height;
		
		if((containerWidth + width) > $(window).width() || (containerHeight + height) > $(window).height()) {
			// Get the original geometry and calculate scales
			var xscale=(width+containerWidth + 100)/$(window).width();
			var yscale=(height+containerHeight + 100)/$(window).height();
		
			// Recalculate new size with default ratio
			if (yscale>xscale){
				newWidth = Math.round(width * (1/yscale));
				newHeight = Math.round(height * (1/yscale));
			} else {
				newWidth = Math.round(width * (1/xscale));
				newHeight = Math.round(height * (1/xscale));
			};
		};

		// Get the container size, to resize the holder to the right dimensions
		containerHeight += newHeight;
		contentHeight += newHeight;
		containerWidth += newWidth;
	
		return {
			width:newWidth,
			height:newHeight
		};
	},
	close : function(){
		$('div.popup').fadeTo('fast',0, function(){
			$('div.popupOverlay').fadeTo('fast',0, function(){
				$('div.popupOverlay').remove();
				$('div.popup').remove();
			});
		});
	},
	enviar : function(){
		var email = $("#email_e").val();
		var nom = $("#nom_e").val();
		var r_email = $("#r_email").val();
		var r_nom = $("#r_nom").val();
		var comentari = $("#comentari").val();
		var id_article = $("#id_article").val();
		var url_enviar = $("#url_enviar").val();
		
		
		if( email != '' )
		{
			html = '<div class="enviarAmic"><div class="top"><div class="left"></div><div class="middle"></div><div class="right"></div></div><div class="content_email"><div class="loaderIcon"></div><div id="fullResContainer">';
			html += '<img src="/img/icones/loader.gif" alt="loader" style="margin: 150px 0px 100px 125px" />';
			html += '<br class="p" /></div></div><div class="bottom"><div class="left"></div><div class="middle"></div><div class="right"></div></div></div>';
			$(".popup").html( html );
			
			$.post( AJAX, { email: email, nom: nom, r_email: r_email, r_nom: r_nom, id_article: id_article, url_enviar: url_enviar, comentari: comentari, accio: 'enviar_art' },
			function( resposta )
			{
				// Basic HTML
				html = '<div class="enviarAmic"><div class="top"><div class="left"></div><div class="middle"></div><div class="right"></div></div><div class="content_email"><div class="loaderIcon"></div><div id="fullResContainer">';
				html += '<h4 class="vermell">S\'ha enviat correctament el missatge</h4>\n';
				html += '<br class="p" /></div></div><div class="bottom"><div class="left"></div><div class="middle"></div><div class="right"></div></div></div>';
				
				$('.popup').html(html);
				$('.popup .content_email').css({height: "25px"})
				
				setTimeout('enviarEmail.close()',3000)
			});
		}
		else
		{
			alert("Has de posar un correu de destí com a mínim");
		}
	}
}

