(function($) {


$.fn.alh_slider = function(options) {

	var settings = {
		width: this.find("img").attr('width'),
		height: this.find("img").attr('height'),
		rotateSpeed: '4000',
		animationSpeed: '1200',
		id: '99'
	};


	if (options) {
		$.extend(settings, options);
	}

	var	current,
		last,
		timer = '',
		$self = this,
		slides,
		next;

	var change = function () {

		next = (current == (slides.length - 1)) ? 0 : current + 1;
		//console.debug(settings.id +' Changing.  next:' + next + ', current:' + current + ', last:' + last + ', length:' + slides.length);
		$(slides[last]).css('z-index', 0);
		$(slides[next]).hide().css('z-index', 2);
		$(slides[current]).css('z-index', 1);
		last = current;

		//console.debug(settings.id +' fadein starting.  next:' + next + ', current:' + current + ', last:' + last + ', length:' + slides.length);
		$(slides[next]).fadeIn(settings.animationSpeed, function(){

			current = next;
			//console.debug(settings.id +' fadein completed. , current:' + current + ', last:' + last + ', length:' + slides.length);
			});

		timer = setTimeout(change, settings.rotateSpeed);
	};

	var standard_alt_text = this.children("img").attr("alt");
	var loaded_count = this.find("img").length;
	var total_count = this.find("li").length + loaded_count;

	//console.debug('creating. loaded count:'+loaded_count +' , total count:'+total_count);

	if((loaded_count == total_count)&&(total_count>1)){

		slides = this.find('img').get();
		current = slides.length -1;
		last = slides.length -2;
		timer = setTimeout(change, settings.rotateSpeed);
		return this;

	}else{

		//get all images from the unordered list and load lazyload into html
		this.find("li").children("a").each(function(){

			src = $(this).attr("href");

			if($(this).attr("title")){
				alt = $(this).attr("title");
			}else{
				alt = standard_alt_text;
			}//end if else

			img = new Image();
			$(img).attr('alt', alt);
			$(img).attr('width', settings.width);
			$(img).attr('height', settings.height);
			var imagelink = $(this).attr('rel');

			$(img).load(function () {
				//image has loaded event fired

				// then insert our image into the #slide-show div
				$self.prepend(this);

				if(typeof imagelink !== 'undefined' && imagelink !== false){
					$(this).wrap("<a href="+imagelink+"></a>");
				}

				loaded_count++;

				//console.debug('image loaded. loaded count:'+loaded_count +' , total count:'+total_count);

				if((loaded_count == total_count)&&(total_count>1)){

					$self.children('ul').remove();


					slides = $self.find('img').get();
					current = slides.length -1;
					last = slides.length -2;

					timer = setTimeout(change, settings.rotateSpeed);

					return $self;

				}//emd of

			}).error(function() {

				self.total_count = self.total_count - 1;

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

		});

	}//end if else


};

})(jQuery)
