var Start = {
  frame_name	: 'gallery_images',
  current_image : 0,
  total_images	: 0,
  move_by		: 0,
  photos		: [],
  moving	   	: false,
  setup			: false,
  
  init: function(args) {
    if (Start.setup) return;
    Start.setup = true;

    Start.box = $(args.first());
	Start.photos = args[1]['pictures'];
	Start.total_images = Start.photos.length;

    Start.next_button = $(args[1]['next']);
    Start.back_button = $(args[1]['previous']);

	Start.next_button.observe('click', Start.showNext);
	Start.back_button.observe('click', Start.showPrevious);
	
	Start.move_by = Start.box.getWidth();
	
	Start.setupBox();
	Start.preload();
  },
  
  showPrevious: function (e) {
	e.stop();
	
	var pixels;
	
	if (Start.moving) return;
	Start.moving = true;
	
	if(Start.current_image == 0) {
		pixels = parseInt(Start.move_by*(Start.total_images-1));
		Start.current_image = Start.photos.length-1;
	} else {
		Start.current_image--;
		pixels = parseInt(Start.move_by*Start.current_image);
	}
	
	new Effect.Morph(Start.frame, {
		style: {
			marginLeft: '-'+ pixels +'px'
		},
		afterFinish: function () {
			Start.moving = false
		},
		duration: 0.3,
		transition: Effect.Transitions.sinoidal
	});	
  },
  
  showNext: function (e) {
	e.stop();
	
	var pixels;
	
	if (Start.moving) return;
	Start.moving = true;
	Start.current_image++;
	
	if(Start.total_images == Start.current_image) {
		pixels = 0;
		Start.current_image = 0;
	} else {
		pixels = parseInt(Start.move_by*Start.current_image);
	}
	
	new Effect.Morph(Start.frame, {
		style: {
			marginLeft: '-'+ pixels +'px'
		},
		afterFinish: function () {
			Start.moving = false
		},
		duration: 0.3,
		transition: Effect.Transitions.sinoidal
	});
  },

  // Setup Box
  setupBox: function () {
	var old_html = Start.box.innerHTML;
	Start.box.setStyle({
		width: Start.box.getWidth()+'px',
		height: Start.box.getHeight()+'px',
		overflow: 'hidden'
	});
	
	Start.box.update('<div id="'+ Start.frame_name +'">'+ old_html +'</div>')
	Start.frame = $(Start.frame_name);
	Start.frame.setStyle({
		width: parseInt(Start.photos.length*Start.box.getWidth())+'px'
	});
	
	Start.frame.update('');
	for(var i = 0; i<Start.photos.length; i++) {
		new Insertion.Bottom(Start.frame, "<img src='"+ Start.photos[i] +"' alt='' />");
	}
  },

  preload: function () {
	var preload_image = new Image();

    for(var i=0; i<Start.photos.length; i++) {
      preload_image.src = Start.photos[i];
	  //console.log('Preloaded: '+ Start.photos[i]);
	}
  }
}
 
var Gallery = Class.create({
  initialize: function() {
    this.options = $A(arguments);
    Start.init(this.options);
  }
});