/*
 object oriented gallery 
*/
options = {
	container: '#img_container', //image container
	arrow: '#arrow', // arrow container
	navigator: '#navigator',//navigator container
	autoPlay: true, //autoplay
	autoPlayDuration: 10000 // if autoplay is activate
};

var gallery = function(options){
	var options = options;
	var container = $(options.container);
	var images = container.children();
	var current = 0;
	var autoplayTimer;
	var navigatorItem = new Array();
	/*
	* Construct image navigator and the others
	*/
	this.construct = function(){
		images.hide();
		var navigator = document.getElementById(options.navigator.replace(/\#/gi,""));
		var me = this;
		for(i=0;i<images.length;i++){
			//create Element
			new_span = document.createElement('span');
			navigatorItem.push(new_span); //add to navigators item
			if(i==0){
				new_span.className = 'dot_active';//set active if first item
			}else{
				new_span.className = 'dot_disable';
			}
			$(images[i]).hide();
			$(new_span).bind('click',i,function(event){
				c = event.data;
				navigate_id(c);	
				$('.dot_active').attr('class','dot_disable');	
				$(this).attr('class','dot_active');						
				clearInterval(autoplayTimer);//reset gallery timer
				me.autoplay(); //start again the timer
			});
			navigator.appendChild(new_span);
		}
		$(images[0]).fadeIn();
	}
	/*
	* Auto play every options.autoPlayDuration
	*/
	this.autoplay = function(){
		if(options.autoPlay){
			autoplayTimer = setInterval(this.next_item,options.autoPlayDuration);
		}
	}
	this.next_item = function(){
		if(current == (images.length-1)){
			this.navigate_id(0);
		}else{
			this.navigate_id(current+1);
		}
	}
	/*
	* Animate item by id using this function
	*/
	this.navigate_id = function(id){
		target = images[id];
		for(i=0;i<images.length;i++){
			if(images[i] != target){
				$(navigatorItem).attr('class','dot_disable');
				$(navigatorItem[id]).attr('class','dot_active');
				$(images[i]).fadeOut(2000);
			}else{
				$(target).fadeIn(500);
			}
		}
		current = id; //set navigated item to active
	}
	this.construct();
	this.autoplay();
}

$(document).ready(function(){
	gallery(options);
});
