/**
 * ImageSlider
 * a widget for jQuery to slide images
 */

(function() {

  function extend(destination, source) {
    for (var property in source)
      destination[property] = source[property];
    return destination;
  }
  
  function isUndefined(object) {
	    return typeof object === "undefined";
  }
  
  extend(Object, {
    extend:        extend,
    isUndefined:	isUndefined
  });
})();


Object.extend(Function.prototype, (function() {
  var slice = Array.prototype.slice;
  
  function update(array, args) {
	    var arrayLength = array.length, length = args.length;
	    while (length--) array[arrayLength + length] = args[length];
	    return array;
	  }

  function bind(context) {
	    if (arguments.length < 2 && Object.isUndefined(arguments[0])) return this;
	    var __method = this, args = slice.call(arguments, 1);
	    return function() {
	      var a = merge(args, arguments);
	      return __method.apply(context, a);
	    }
	  }
  
  function merge(array, args) {
	    array = slice.call(array, 0);
	    return update(array, args);
	  }

  return {
    bind:                bind,
    merge:	merge,
    update: update
  }
})());

  
  

var ImageSlider = {
	options: {
		speed : .15
	},
	
	_init : function () {
		this.element.removeClass ("imageslider_noscript");
		this.element.addClass ( "imageslider_script" );
		
		this.element.mouseenter ( this.stop.bind(this));
		this.element.mouseleave ( this.start.bind(this));
		
		var inner = this.element.children ( ".imageslider_inner");

		this.options.originalWidth = inner.width(); 
			
		var width = this.element.width();
		var images_width = 0;
		var image = 0;
		var images = inner.children (".imageslider_image");
		
		while ( images_width < width && image < images.length ) {
			images_width += $(images[image]).width();
			$(images[image]).clone().appendTo ( inner );
			
			image ++;
		}
		
		this.start();
	},
	
	start : function () {
		var inner = this.element.children ( ".imageslider_inner" );
		var position = inner.position().left;
		var outerwidth = this.element.width();
		var target = this.options.originalWidth;
		
		var duration = (target + position) / this.options.speed;
				
		inner.animate (
			{
				left: "-" + target + "px"
			},
			duration,
			"linear",
			this.restart.bind ( this )
		);
	},
	
	stop: function () {
		//alert ( "hallo" );
		var inner = this.element.children ( ".imageslider_inner");
		inner.stop();
		inner.clearQueue();
	},
	
	reset: function () {
		var inner = this.element.children ( ".imageslider_inner");
		inner.stop();
		inner.clearQueue();
		inner.css ( "left", 0 );
	},
	
	restart: function ( ) {
		var inner = this.element.children ( ".imageslider_inner");
		//inner.stop();
		inner.clearQueue();
		inner.css ( "left", 0 );
		
		this.start();
	}
	
};

$.widget("ui.imageslider", ImageSlider); 
