(function($){

$.fn.galleria = function(settings) {

    // check for basic CSS support
    if (!hasCSS()) { return false; }
    
    // extend the options
    var settings = $.extend({
	clickNext   : true,
	onImage     : function(image,caption,thumb) {},
	onThumb     : function(thumb) {}
    }, settings);

    // if no insert selector, create a new division and insert it before the ul

    var mainImage = settings.insert ?
	$(settings.insert) :
	$("<div></div>").addClass('galleria_container').insertBefore(this);

    // inject the wrapper in in the insert selector
    mainImage.append($("<div></div>").addClass('galleria_wrapper'))
             .append($("<span></span>").addClass('caption'));

    var current = "";

    // Events for the nav
    $("a.prevLink").click(function() {
	prevImage();
	return false;
    });

    $("a.nextLink").click(function() {
	nextImage();
	return false;
    });

    return this.each(function(){

	// add the Galleria class
	$(this).addClass('galleria');

	// loop through list
	$(this).children('li').each(function() {

	    // bring the scope
	    var item = $(this);

	    // remove the clickNext if image is only child
	    if (item.is(':only-child')) settings.clickNext = false;

	    // try to fetch an anchor
	    var _a = item.find('a').is('a') ? item.find('a') : false;

	    // reference the original image as a variable and hide it
	    var _img = item.find('img').css('display','none');

	    // extract the original source
	    var _src = _a ? _a.attr('href') : _img.attr('src');

	    // find a title
	    var _title = _a ? _a.attr('title') : _img.attr('title');

	    // Handle the description and the involve
	    var _desc = $(this).find('.description').html();
	    var _involve = $(this).find('.involve').html();

	    // create loader image
	    var _loader = new Image();

	    // begin loader
	    $(_loader).load(function () {
		//-----------------------------------------------------------------
		// the image is loaded, let's create the thumbnail

		var _thumb = _a ?
		    _a.find('img').addClass('thumb noscale') :
		    _img.addClass('thumb');

		if (_a) { _a.replaceWith(_thumb); }

		if (!_thumb.hasClass('noscale')) { // scaled tumbnails!
		    var w = Math.ceil( _img.width() / _img.height() * item.height() );
		    var h = Math.ceil( _img.height() / _img.width() * item.width() );
		    if (w < h) {
			_thumb.css({ height: 'auto', width: item.width(), marginTop: -(h-item.height())/2 });
		    } else {
			_thumb.css({ width: 'auto', height: item.height(), marginLeft: -(w-item.width())/2 });
		    }
		} else { // Center thumbnails.
		    // a tiny timer fixed the width/height
		    window.setTimeout(function() {
			_thumb.css({
			    marginLeft: -( _thumb.width() - item.width() )/2,
			    marginTop:  -( _thumb.height() - item.height() )/2
			});
		    }, 1);
		}

		// add the rel attribute
		_thumb.attr('rel',_src);

		// add the title attribute
		_thumb.attr('title',_title);
		_thumb.attr('desc',_desc);
		_thumb.attr('involve',_involve);

		// add the click functionality to the _thumb
		_thumb.click(function() {
		    onPageLoad(_src);
		});

		// hover classes for IE6
		_thumb.hover(
		    function() { $(this).addClass('hover'); },
		    function() { $(this).removeClass('hover'); }
		);
		item.hover(
		    function() { item.addClass('hover'); },
		    function() { item.removeClass('hover'); }
		);

		_thumb.css('display', 'block');

		// call the onThumb function
		settings.onThumb($(_thumb));

		// check active class and activate image if match
		if (item.hasClass('active')) {
		    onPageLoad(_src);
		}


	    }).error(function () {

		// Error handling
		item.html('<span class="error" style="color:red">Error loading image: '+_src+'</span>');

	    }).attr('src', _src);
	});
    });

    function onPageLoad(src) {

	// get the wrapper
	var _wrapper = $('.galleria_wrapper');

	// get the thumb
	var _thumb = $('.galleria img[@rel="' + src + '"]');

	if (src) {

	    // alter the active classes
	    _thumb.parents('li').siblings('.active').removeClass('active');
	    _thumb.parents('li').addClass('active');

	    // define a new image
	    var _img   = $(new Image()).attr('src', src);

	    // empty the wrapper and insert the new image
	    _wrapper.empty().append(_img);

	    // insert the caption
	    _wrapper.siblings('.caption').text(_thumb.attr('title'));

	    $('#infoBox').empty()
	    .append($("<p>" + _thumb.attr('desc') + "</p>"))
	    .append($("<br><p>" + _thumb.attr('involve') + "</p>"));

	    // fire the onImage function to customize the loaded image's features
	    settings.onImage(_img, _wrapper.siblings('.caption'), _thumb);

	    // add clickable image helper
	    if(settings.clickNext) {
		_img.css('cursor','pointer').click(function() { nextImage(); });
	    }

	} else {

	    // clean up the container if none are active
	    _wrapper.siblings().andSelf().empty();

	    // remove active classes
	    $('.galleria li.active').removeClass('active');
	}

	current = src;

    };

    function nextSelector(selector) {
	return $(selector).is(':last-child') ?
	    $(selector).siblings(':first-child') :
    	    $(selector).next();
    };


    function previousSelector(selector) {
	return $(selector).is(':first-child') ?
	    $(selector).siblings(':last-child') :
    	    $(selector).prev();
    };

    // Checks for CSS browser support
    function hasCSS()  {
	$('body').append(
	    $(document.createElement('div'))
	    .attr('id','css_test')
	    .css({ width:'1px', height:'1px', display:'none' })
	);
	var _v = ($('#css_test').width() != 1) ? false : true;
	$('#css_test').remove();
	return _v;
    };

    function nextImage() {
	onPageLoad($(nextSelector($('.galleria img[@rel="' + current + '"]')
				  .parents('li'))).find('img').attr('rel'));
    }

    function prevImage() {
	onPageLoad($(previousSelector($('.galleria img[@rel="' + current + '"]')
				  .parents('li'))).find('img').attr('rel'));
    }


};

})(jQuery);



