var slideshow;

jQuery.fn.imageGallery = function(contentPane, displayFirst) {
	

	return this.each(function() {
		
		// We may need to set the content pane to use the first entry by default.
		var first;
		if (displayFirst == undefined) {
			first = true;
		} else {
			first = displayFirst;
		}
		
		var topElement = this;
		
		// For each entry in the list.
		jQuery(this).children().each(function() {
			
			
			// We remove the main_content element and add it to contentPane when we are clicked. 
			var contentElement = jQuery(this).children(".main_content");
			
			var content = contentElement.contents();
			jQuery(this).click(function() {
				if (!jQuery(this).hasClass('selected')) {
					contentPane.empty().append(content.parent().html());

					jQuery(topElement).find('.selected').removeClass('selected');
					jQuery(this).addClass('selected');

					if (contentElement.hasClass('content_slideshow')) {
						contentPane.createSlideshow();
					}
				}
			});
				
			if (first) {
				first = false;			

				jQuery(this).click();
			}
		});
	});
};

jQuery.fn.createSlideshow = function() {
	return this.each(function() {
		
		jQuery(this).children('ul').attr('id', 'slideshow').children('li').each(function() {
            var img = jQuery(this).children("img");
            if (img.length > 0) {
                var tn = img.attr('src');
                var mainURL = tn.replace("_tn", "");

                var mainSpan = document.createElement('span');
                jQuery(mainSpan).text(mainURL);

                jQuery(this).children().first().after(mainSpan);
                
                // We need to insert an h3 and p for the name and description respectively if none is there.
                if (jQuery(this).find('h3').length == 0) {
                	jQuery(this).append('<h3></h3>');
                }
                
                if (jQuery(this).find('p').length == 0) {
                	jQuery(this).append('<p></p>');
                }         
            }
        });
		
		
		jQuery(this).append('<div id="wrapper">' +
        '<div id="fullsize">' +
        '  <div id="cnr"></div>' +
        '    <div id="image"></div></div></div><a id="imgprev">Previous</a><a id="imgnext">Next</a><div id="imglink" />');
		
	
		jQuery("#slideshow").hide();
        jQuery("#wrapper").show();
            
		slideshow = new TINY.slideshow("slideshow");
		slideshow.auto=true;
        slideshow.speed=5;
        slideshow.link=false;
        slideshow.info=false;
        slideshow.thumbs=false;
        slideshow.left=false;
        slideshow.right=false;
        slideshow.scrollSpeed=4;
        slideshow.spacing=5;
        slideshow.active="#fff";
        slideshow.init("slideshow","image", "imgprev", "imgnext", "imglink");
       
	});
};
