var positions = new Array();
var galleryEffect = null;

Event.addBehavior({
  "#gallery":function() {
	/* This code is executed after the DOM has been completely loaded */

	var totalWidth = 0;
	
	$$('#slides .slide').each(function(slide, i){

		/* Traverse through all the slides and store their accumulative widths in totWidth */

		positions[i]= totalWidth;
		totalWidth += slide.getWidth();

		/* The positions array contains each slide's commulutative offset from the left part of the container */

		if(!slide.getWidth())
		{
			alert("Please, fill in width & height for all your images!");
			return false;
		}

	});

    $('slides').setStyle({width:totalWidth+"px"});


        /* On page load, mark the first thumbnail as active */

        $('menu').select('li.menuItem').each(function(element, i) {
            if(i==0) {
              element.addClassName('act');
            }
            else {
              element.addClassName('inact');
            }
        })
  },

  "#menu ul li a:click": function(e){
    /* On a thumbnail click */

    var element = e.element();

    $$('#menu li.menuItem').each(function(elem) {
        elem.removeClassName('act')
        elem.addClassName('inact');
    })
    element.up().addClassName('act');

    var pos = element.up('li').previousSiblings().length;

    if(galleryEffect) {
      galleryEffect.cancel();
    }

    var from = parseInt($('slides').getStyle("marginLeft")) || 0;

    galleryEffect = new Effect.Tween($('slides'), 
        from,
        -positions[pos], //to
        {duration:0.45}, //options
        function(p) {
          this.setStyle({marginLeft:p + 'px'});
        });

    /* Start the sliding animation */

    e.preventDefault();
    return false;
    /* Prevent the default action of the link */
  }

});
