/*
 * Copyright (c) 2010 Bjorn Boonen
	Permission is hereby granted, free of charge, to any person obtaining a copy
	of this software and associated documentation files (the "Software"), to deal
	in the Software without restriction, including without limitation the rights
	to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
	copies of the Software, and to permit persons to whom the Software is
	furnished to do so, subject to the following conditions:

	The above copyright notice and this permission notice shall be included in
	all copies or substantial portions of the Software.

	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
	IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
	FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
	AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
	LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
	OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
	THE SOFTWARE.
 * Basic jquery plugin to add a small gallery.
 * Version
 *
 * expected
 * - interval (how many ms to check the width of the ul again?
 * - the following html-code: <div class="list xg-list"><ul></ul></div>
 */
;
(function($){
	$.xfinxGallery = function( obj, options ){
		// To avoid scope issues, use 'self' instead of 'this'
		// to reference this class from internal events and functions.
		var self = this;

		// Access to jQuery and DOM versions of element
		self.$obj = $( obj );
		self.obj = obj;

		self.defaultOptions = {
			recalculate				: false,
			activeControls			: false,
			innerBox				: 'xg-inner',
			innerElement			: 'xg-inner-element',
			animationSpeed			: 300,
			animationType			: 'swing',
			autoAnimate				: true,
			autoAnimateRestartTime	: 10000,
			autoAnimateInterval		: 1000
		};

		self.options = $.extend( {}, self.defaultOptions, options );
		self.$innerBox = self.$obj.find( '.' + self.options.innerBox );

		// Add a reverse reference to the DOM object
		self.$obj.data( "xfinxGallery", self );
		self.animating = false;

		self.init = function(){
			// add the class xg-wrap fir styling purposees
			self.$obj.addClass( 'xg-wrap' );
			// if no xg-list is defined, create our own.
			if (self.$obj.find( '.' + self.options.innerBox ).length === 0) {
				self.$obj.append( '<ul class="'+self.options.innerBox+'"></ul>' );
			}

			// some basic initialisations
			self.innerWidth		= 0;
			self.itemWidth		= 0;
			self.ul				= {
				$obj				: self.$innerBox,
				'location'			: 0
			};

			// First calculate the width of the ul/xg-inner
			if ( self.options.recalculate ) {
				setInterval( function() {
					self.setInnerWidth();
				}, self.options.recalculate );
			} else {
				self.setInnerWidth();
			}
			self.listener();
			if ( self.options.autoAnimate ) {
				self.autoAnimation();
			}
		};


		self.setInnerWidth = function() {
			self.innerWidth = 0;
			var contentObj = self.$innerBox.find('.'+self.options.innerElement);
			self.innerWidth += contentObj.outerWidth(true); // true gives margin and border also
			self.itemWidth = self.innerWidth;
			// now multiply the width per item by the number of items
			self.innerWidth *= contentObj.length;

			// The ul can have padding also, as in the (current) normal boxmodal
			// padding extends the width, so there is no trouble there yet. Might
			// be interesting later though ;-)
			self.ul.$obj.width( self.innerWidth );
			if (!self.activeControls) {
				if ( self.innerWidth > self.$obj.outerWidth(true) ) {
					self.addControls();
				}
			} else {
				if ( self.innerWidth < self.$obj.outerWidth(true) ) {
					self.removeControls();
				}
			}
		};

		self.addControls = function() {
			self.activeControls = true;
			var html = '';
			html = '<a class="xg-navigate xg-navigate-left disabled"></a><a class="xg-navigate xg-navigate-right"></a>';
			self.$obj.append( html );
		};
		
		self.removeControls = function() {
			self.activeControls = false;
			self.$obj.find('.xg-navigate').remove();
		};


		self.listener = function() {
			self.$obj.delegate( '.xg-navigate-left', 'click', function() {
				if ( !self.animating ) {
					self.killAutoAnimation();
					self.moveItems({
						'direction':'left'
					});
				}
			});
			self.$obj.delegate( '.xg-navigate-right', 'click', function() {
				if ( !self.animating ) {
					self.killAutoAnimation();
					self.moveItems({
						'direction':'right'
					});
				}
			});
		};

		self.moveItems = function( options ) {
			// we might want to continue automating.
			if ( !options.autoAnimation && self.options.autoAnimate === true && self.options.autoAnimateRestartTime > 0 ) {
				clearTimeout( self.restartAutoAnimation );
				self.restartAutoAnimation = setTimeout( function() {
					self.autoAnimateDirection = options.direction;
					self.autoAnimation();
				}, self.options.autoAnimateRestartTime );
			}

			// this sets animating to true, so clicking twice will result in only 1 action
			self.animating = true;
			var location = Number( self.ul.$obj.css( 'left' ).replace( /-?(\d+)px/g,'$1' ) );
			if ( options.direction === 'left' && -location < 0 ) {
				self.ul.location = ( -location + self.itemWidth );
			} else if ( options.direction === 'right' && ( location < ( self.innerWidth - self.$obj.width() ) ) ) {
				self.ul.location = ( -location - self.itemWidth );
			}

			// We want to trigger if a button is disabled or not.
			if ( self.ul.location < 0 ) { // is positioned to the left
				self.$obj.find( '.xg-navigate-left' ).removeClass( 'disabled' ); // if the beginning is not reached
			} else {
				self.$obj.find( '.xg-navigate-left' ).addClass( 'disabled' );
				self.ul.location = 0;
			}
			if ( -self.ul.location < ( self.innerWidth - self.$obj.width() ) ) { // if the end is not reached
				self.$obj.find( '.xg-navigate-right' ).removeClass( 'disabled' );
			} else {
				self.$obj.find( '.xg-navigate-right' ).addClass( 'disabled' );
				self.ul.location = self.$obj.width() - self.innerWidth;
			}

			// do animate!
			self.ul.$obj.animate({
				left : self.ul.location+'px'
			},self.options.animationSpeed, self.options.animationType, function() {
				self.animating = false;
			});
		};

		// this method starts the autoanimation.
		self.autoAnimation = function() {
			self.autoAnimateDirection = 'right';
			self.autoAnimateIntervalId = setInterval( function() {
				if ( -self.ul.location >= ( self.innerWidth - self.$obj.width() ) ) { // it reached the end, not go left
					self.autoAnimateDirection = 'left';
				} else if ( self.ul.location >= 0 ) { // it reached the beginning, now go right
					self.autoAnimateDirection = 'right';
				}
				self.moveItems({'direction' : self.autoAnimateDirection, 'autoAnimation' : true});
			}, self.options.autoAnimateInterval);

		};

		//this method can kill the autoanimation
		self.killAutoAnimation = function() {
			clearInterval( self.autoAnimateIntervalId );
		};

		// Run initializer
		self.init();
	};


	$.fn.xfinxGallery = function(options){
		if (!options) {
			var options = [];
		}
		return this.each(function(){
			(new $.xfinxGallery(this, options));
		});

	
	};

})(jQuery);

