// JavaScript Document

function image_slideshow_inc( file, obj_name, fn, timeout ){
	eval( 'var testObj = (typeof '+obj_name+'==\'undefined\');' );
	if ( testObj ){
		var e = document.createElement( 'script' );
		e.type = 'text/javascript'; e.src = file;
		document.getElementsByTagName('head')[0].appendChild(e);
		var tout = setTimeout(function(){
			// Timeout for 5 seconds, display error when script is not loaded
			clearTimeout(t);
			if ( timeout ) timeout();
		}, 20000); // ten seconds timeout
		var t = setInterval( function(){
			eval( 'var testObj = (typeof '+obj_name+'!=\'undefined\');' );
			if ( testObj ){
				clearTimeout( t );
				clearTimeout( tout );
				if ( fn ){ fn(); }
			} }, 100 );
	} else { if ( fn ) fn(); }
}

function image_slideshow_start_slideshow(){
	$('.cms-image-slideshow-cycle').each(function(i){
		if ( $(this).hasClass('no-cycle') ) return;
		eval('var opts = '+$(this).attr('options')+';');
		if ( !opts ) opts = null;
		$(this).cycle(opts);
	});
}
function image_slideshow_start_lightbox(){
	var fn_start = function(){
		$('a[rel^="prettyPhoto"]').prettyPhoto();
	};
	var is_c = $('.cms-image-slideshow-cycle').length;
	$('.cms-image-slideshow-cycle').each(function(i){
		if ( !$(this).hasClass('no-cycle') ) return;
		
		var im_c = $(this).find( 'img' ).length;
		/*$(this).find( 'img' ).load( function(){
			im_c--;
			if ( im_c==0 ){
				is_c--;
				alert( 'we' );
				if ( is_c==0 ){
					fn_start();
					alert( 'aw' );
				}
			}
		});*/
		$(this).find( 'img' ).each(function(){
		
			/*$(this).load( function(){

			});*/
			
			var src = $(this).attr('src');
			var title = $(this).attr('title');
			$(this).attr('alt', title);
			var src_split = src.split('_'); var ls = src_split.length;
			var li = src_split[ls-1].split('.');
			// Check if img is a resized image
			if ( li[0].substring(0,1)=='(' && li[0].substring( li[0].length-1 )==')' ){
				src_split[ls-2] = src_split[ls-2]+'.'+li[1];
				src_split.splice( ls-1, 1 );
				src = src_split.join('_');
			}
			//alert( '<a href="'+src+'" rel="prettyPhoto['+i.toString()+']">' );
			$(this).wrap('<a href="'+src+'" rel="prettyPhoto['+i.toString()+']">');
			$(this).parent().attr('title', title);
			
		});
	});
	setTimeout( function(){
		fn_start();
	}, 1000 );
}

// Dynamically load jQuery
setTimeout( function(){
	image_slideshow_inc( _image_slideshow_core[0], 'jQuery', function(){
		image_slideshow_inc( _image_slideshow_core[1], 'jQuery().cycle', function(){
			// Start slideshow
			image_slideshow_start_slideshow();
		});
		image_slideshow_inc( _image_slideshow_core[2], 'jQuery().prettyPhoto', function(){
			// Start slideshow
			image_slideshow_start_lightbox();
		});
	});
}, 10 );
