jQuery(document).ready(function($) { 
	// Bail if no images, not a slideshow, IE6 
	if(typeof portfolialSlideshowImages === 'undefined') {return;}
	if(!$('.gallery').hasClass('gallery-slideshow')) {return;}
	if($('body').hasClass('ie6')) {$('body').removeClass('js'); return;}
	
	var debug = false;
	
	function log(c){
		if(debug === true & 'undefinded' !== typeof console){
			console.log(c);
		}
	}	

	function mkA(i,c,t){
		return $('<a />',{'href':'#','id':i,'class':c,text:t});
	}
	
	function mkDIV(i,c,t){
		return $('<div />',{'id':i,'class':c});
	}
	
	function bool(a){
		return 'true' === a;
	}
	
	var transitions = {
		'cross_fade': 'fade',
		'slide_left': 'scrollHorzCustom',
		'slide_vert': 'scrollVert'
	};
	
	var slideshowID = 1,
		slideshow = mkDIV('slideshow').appendTo('body').css('visibility','hidden'),
		gallery = $('.gallery').eq(0).hide(),
		sWidth = $(slideshow[0]).width(),
		sHeight = $(slideshow[0]).height(),
		caption = mkDIV('slideshow-caption'),
		controls = mkDIV(null,'slideshow-controls'),
		pager = mkDIV(null,'slideshow-pager'),
		controlNext = mkA('slideshow-controls-next-'+slideshowID,'slideshow-controls-next','>').attr('title','next image').prependTo(controls),
		controlPause = mkA('slideshow-controls-pause-'+slideshowID,'slideshow-controls-pause','||').attr('title','pause or resume slideshow'),
		controlPrev = mkA('slideshow-controls-prev-'+slideshowID,'slideshow-controls-prev','<').attr('title','previous image').prependTo(controls),
		l = portfolialSlideshowImages.length,
		loading = $('<div id="slideshow-loading"><img class="loader" src="'+portfolialSlideshowOptions.loaderImage+'" /></div>').insertBefore(gallery),
		imageElements = [],
		opt = {};
	
	opt.transition = transitions[portfolialSlideshowOptions.transition].length>0? transitions[portfolialSlideshowOptions.transition] : portfolialSlideshowOptions.transition;
	opt.holdTime = portfolialSlideshowOptions.holdTime || 3000;
	opt.fadeTime =  +portfolialSlideshowOptions.fadeTime || 3000;
	opt.navigation = portfolialSlideshowOptions.navigation || null;
	opt.prevNext = bool(portfolialSlideshowOptions.showPrevNext);
	opt.automatic =  bool(portfolialSlideshowOptions.automatic);
	opt.centreImages = bool(portfolialSlideshowOptions.centreImages);
	opt.layout = portfolialSlideshowOptions.layout;
	
	log(opt);
	
	
	$.fn.cycle.transitions.scrollHorzCustom = function($cont, $slides, opts) {
		$cont.css('overflow','hidden').width();
	
		opts.before.push(function(curr, next, opts, fwd) {
			$.fn.cycle.commonReset(curr,next,opts);	
			opts.cssBefore.left = fwd ? (sWidth-1) : (1-sWidth);
			opts.animOut.left = fwd ? -sWidth : sWidth;
	
		});
	
		opts.cssFirst = { left: 0 };
		opts.cssBefore= { top: 0 };
		opts.animIn   = { left: 0 };
		opts.animOut  = { top: 0 };
	};
    
	(function addImage(i){
		var src = portfolialSlideshowImages[i];
		imageElements[i] = new Image();
		
		
		//Resize each image to fit calling the next image once done
		imageElements[i].onload = function(){
			var image = resizeToFit.call(this,sWidth,sHeight,opt.centreImages);
			//Add image to slideshow
			slideshow.append($(image));
			if(i<(l-1)) {
				addImage(++i);
			} else {
				loadSlideshow();
			}
		}
		
		log('Add image '+i+' '+src);
		
		//Trigger the onload
		imageElements[i].src = src;
	})(0);
	
	
	//Set-up the slideshow
	function loadSlideshow(){
		var pagerItemClass, pagerItem;
		log('initialize slideshow');	
		
		loading.remove();
		
		slideshow.hide().css('visibility','visible').fadeIn('slow').wrap('<div id="slideshow-wrapper" style="position:relative">');
		$('#slideshow-wrapper').insertBefore(gallery).addClass(['slideshow-'+opt.layout,'slideshow-'+opt.navigation].join(' '));
		
		addControls();
		
		slideshow.cycle({
			fx: opt.transition, 
			timeout: opt.holdTime,
			speed: opt.fadeTime,
			fastOnEvent: 500,
			next: '#slideshow-controls-next-'+slideshowID,
			prev: '#slideshow-controls-prev-'+slideshowID,
			pager: '.slideshow-pager',
			pagerAnchorBuilder: buildPager
		});
		
		if(!opt.automatic) {slideshow.cycle('pause');}
	}
	
	function buildPager(i,el){
		var pagerItemClass = '',
			pagerItem = '';
			
		switch (opt.navigation){
			case "navigation_thumbnails_small":
			case "navigation_thumbnails_large":
				pagerItemClass = 'thumbnail';
				pagerItem = gallery.find('a').eq(i).html();
				break;
			case "navigation_numbers":
				pagerItem = i+1;
				pagerItemClass = 'number';
				break;
			case "navigation_dots":	
				pagerItemClass = 'dot';
				pagerItem ='<span>&#8226;<span>';
				break;
		}
		
		return mkA(null,pagerItemClass).html(pagerItem).get();	
	}
 	
	function addControls(){
		var wrapper = $('#slideshow-wrapper');
		
		switch (opt.navigation){
			case "navigation_thumbnails_small":
				gallery.find('img').width('40px');
				break;
			case "navigation_thumbnails_large":
				gallery.find('img').width('100px');
				break;	
		}
		
		wrapper.append(caption).append(pager);
		
		if(opt.prevNext) { 
			if(opt.automatic) {controlPrev.after(controlPause);}
			wrapper.append(controls);
		}
		
		controlPause.click(togglePause);
		slideshow.click(togglePause);
	}
	
	function togglePause(){
		var text = controlPause.text();
		switch(text){
			case '||':
				controls.addClass('slideshow-paused');
				slideshow.cycle('pause');
				controlPause.text('>');
				break;
			case '>':
				controls.removeClass('slideshow-paused');
				slideshow.cycle('resume').cycle('next');
				controlPause.text('||');
				break;
		}
		
		return false;
	}

	function resizeToFit(maxWidth,maxHeight,centre){
		var image = $(this),
			imageWidth = this.width,
			imageHeight = this.height,
			wScale = maxWidth / imageWidth,
			hScale = maxHeight / imageHeight,
			ratio = imageWidth / imageHeight,
			newTop = 0,
			paddingString = '', topMargin, html, hPadding = 0, vPadding = 0,
			newWidth,  newHeight;

		if(typeof centre === 'undefined') {centre = true;}
		
		newWidth = imageWidth;
		newHeight = imageHeight;
		
		//reset the image size to automatic
		image.width('auto').height('auto').css({width:'auto',height:'auto',padding:'0'});
	
		if(imageWidth>maxWidth){
			//downscale width;
			newWidth = maxWidth;
			newHeight = maxWidth/ratio;
			//newTop = (sHeight-newHeight)/3;
		}
		
		if(imageHeight>maxHeight) {
			//downscale  height
			newHeight = maxHeight;
			newWidth = maxHeight*ratio;
		}

		image.height(newHeight);
		image.width(newWidth);
		if(centre){
			//Padding to centre the image
			hPadding = Math.max(0,(maxWidth-newWidth)/2) + 'px';
			vPadding = Math.max(0,(maxHeight-newHeight)/2) + 'px';
			paddingString = vPadding+' '+hPadding;
			log(paddingString);
			image.css('padding',paddingString);
		}
		
		log('Resized image ' +this.src);	
		return image;

	}
});
