/** Usage

$(document).ready(function(){
	scroller_fade_start("div.scrollimages", "div#fadeimages", '296px');
});

**/

window.ImgScroller = null;
window.ImgLast = 0;
window.ImgTimeout = null;
window.ImgFadeEl = null;
window.ImgScrolEl = null;

function scroller_fade_start(scrollerContainer, innerfadeContainer) {
	window.ImgFadeEl = $(innerfadeContainer);
	window.ImgScrolEl = scrollerContainer;
	$(scrollerContainer).scrollable({hoverClass: 'hover'});
	window.ImgScroller = $(scrollerContainer).scrollable();
	innerfade_start(innerfadeContainer, '296px');
}
 
function innerfade_start(container, height)
{ 
   	var elements = $(container).children(); 
	if (elements.length > 1) 
	{
	    $(container).css('position', 'relative').css('height', height).addClass('innerfade');

	    for (var i = 0; i < elements.length; i++) {
	        $(elements[i]).css('z-index', String(elements.length-i)).css('position', 'absolute').hide();
	 
			$(elements[i]).bind('click', function(){ 
				innerfade_stop();

				innerfade_goto(container, 1);

			});
			
	    };
	 	
		var idx=0;
		$(window.ImgScrolEl + ' img').each(function(i,o) {
			$(o).attr('id', idx).bind('click', function(){ 
				innerfade_stop();
				innerfade_goto(container, this.id);
			});
			idx++;
		});

		window.ImgTimeout = setTimeout(function() {
			innerfade_next(container, 1, 0);
		}, 4000);

		$(elements[0]).show();
		window.ImgScroller.click(0);
	}
}

function innerfade_next(container, current, last) {
	window.ImgLast = current;
	var elements = $(container).children(); 
	$(elements[last]).fadeOut('slow');
    $(elements[current]).fadeIn('slow', function() { 
		if($(this)[0].style.removeAttribute){
			$(this)[0].style.removeAttribute('filter');
		}
	});
	  
	if(window.ImgTimeout) {
		window.ImgScroller.click(current);
 	}
	
    if ((current + 1) < elements.length) {
        current = current + 1;
        last = current - 1;
    } else {
        current = 0;
        last = elements.length - 1;
    }
 
	innerfade_stop(container); 
	window.ImgTimeout = setTimeout((function() {
		innerfade_next(container, current, last);
	}), 4000);
}

function innerfade_goto(container, current) { 
	var last = window.ImgLast; 
	var elements = $(container).children(); 
	$(elements[last]).fadeOut('slow');
    $(elements[current]).fadeIn('slow', function() { 
		try {
			if($(this)[0].style.removeAttribute){
				$(this)[0].style.removeAttribute('filter');
			}
		} catch(e) {}
	});
	window.ImgLast = current;
}

function innerfade_stop(container) {
	clearTimeout(window.ImgTimeout);
}