(function($) {

	if(!$.maria) $.maria = {};

	/**
	* @param elem jQuery-Object (Wrapped DiashowController)
	* @param index Number Target-Index  
	*/
	function changeSlideTo (elem, index) {
		var data;
	
		data = elem[0].options;
		var oldIndex = elem[0].index;
		
		if(oldIndex === index) {
			return index;
		}
	
		elem.trigger("beforeChange." + (data.eventNamespace), [oldIndex, index]);
	
		elem.trigger("Change." + (data.eventNamespace), [oldIndex, index]);
        
        elem[0].index = index;
	
		elem.trigger("afterChange." + (data.eventNamespace), [oldIndex, index]);
		
		return index;

	}
	
  	/**
	* @param elem jQuery-Object (Wrapped DiashowController)
	* @param index Number value by which the actual Index is changed
	*/
	function changeSlideBy (elem, indexChange) {
		var data, maxIndex, targetIndex;
	
		data = elem[0].options;
		targetIndex = elem[0].index + indexChange;
		maxIndex = data.maxIndex;
	
		if (targetIndex > maxIndex) {
			targetIndex = -1 + -(maxIndex - targetIndex);
		} else if (targetIndex < 0) {
			targetIndex = (1 + maxIndex) + targetIndex;
		}
	
		return changeSlideTo(elem, targetIndex);

	}

	var intervalObject;

	/**
	* @param options Object Descripes the Controller -> required Keys: maxIndex (descripes the count of "slides")
	*/
	$.maria.DiashowController = function(options) {
		
		this.options = $.extend(true, {}, $.maria.DiashowController.prototype.defaults, options);
		this.index = this.options.startIndex;
		
		if (this.options.automaticLoop === true) {
			this.startTimer();
		}
		
	};
	
	$.maria.DiashowController.prototype = {
		
		defaults: {
			startIndex: 0,
			interval: 300,
			automaticLoop: false,
			eventNamespace: "slider"
		},
		
		index: null,
		
		/**
		* @param index Number -> Target-Index
		*/
		changeTo: function(index) {
			return changeSlideTo($(this), index);
		},
		
		/**
		* @param index Number -> Changes the actual Index by this value
		*/
		changeBy: function(indexChange) {
			return changeSlideBy($(this), indexChange);
		},
		
		/**
		* @description Start the automatic timer
		*/
		startTimer: function() {
				
			var self = this;
				
			this.stopTimer();
			this._intervalObject = setInterval(function(){
					
				self.changeBy(1);
					
			}, this.options.interval);
			
			this.timerIsRunning = true;
				
		},
		
		/**
		* @description Stop the automatic timer
		*/
		stopTimer: function() {
			
			this._intervalObject && clearInterval(this._intervalObject);
			this.timerIsRunning = false;
			
		},
		
		/**
		* @description Reset the automatic timer
		*/
		resetTimer: function() {
			
			this.stopTimer();
			this.startTimer();
			
		}
		
	};
  
})(jQuery);

