// Scrolling Panels
// By Filmobile
//
function Panels ( container, timings ) {
	// create the variables
	this.swapSpeed = typeof timings.swapSpeed == 'undefined' ? 1 : timings.swapSpeed;
	this.returnSpeed = typeof timings.returnSpeed == 'undefined' ? 2 : timings.returnSpeed;
	this.duration = typeof timings.duration == 'undefined' ? 10000 : timings.duration*1000;
	this.currentPanel = 1;
	this.element = $(container);
	// move to the next panel every 5 seconds
	this.pe = setInterval ( this.move.bind ( this ), this.duration );
	// build the menu
	this.createMenu();
	// place the panels next to each other
	for (i=0; i<=this.element.childElements().length-1; i++) {	
		this.element.childElements()[i].setStyle({ left:this.element.getWidth()*i+'px',display:'block' });
	}
}

Panels.prototype.move = function () {
    if (this.currentPanel == this.element.childElements().length) {
        new Effect.Move ( this.element, { "x": 0, "y": 0, "mode": 'absolute', "duration": this.returnSpeed, "transition": Effect.Transitions.sinoidal } );
        this.currentPanel = 1;
    } else {
        var x = this.element.positionedOffset () [ 0 ] - this.element.up ( 0 ).getWidth ();
        new Effect.Move ( this.element, { "x": x, "y": 0, "mode": "absolute", "duration": this.swapSpeed } );
        this.currentPanel++;
    }
    this.highlight(this.currentPanel);
};

Panels.prototype.createMenu = function () {
    // create the menu's markup
    var html = '<div class="controls clearfix" id="'+this.element.id+'_control">';
    var links = '';
    // get how many panels there are
    var l = this.element.childElements().length;
    var controlIDs = new Array ();
    // make the buttons
    for(i=1;i<=l;i++) {
        var currentID = this.element.id+'_control_'+(i);
        controlIDs.push(currentID);
		if (i == 1) { var a = " active"; } else { var a = ""; }
        links+= '<span class="control'+a+'" id="' + currentID + '"><strong></strong></span>';
    }
    // finish the markup
    html += links+"</div>";
    // add the menu to the page
    Insertion.After(this.element, html);
    controlIDs.each (function(currentID,index) {
		$( currentID ).observe("click", function(event) {             	
			clearInterval ( this.pe );
			var target = Event.element ( event );
			var x = -( this.element.up ( 0 ).getWidth () * index );
			new Effect.Move ( this.element, { "x": x, "y": 0, "mode": "absolute", "duration": this.swapSpeed } );
			this.currentPanel = index + 1;
			this.highlight(this.currentPanel);
			this.pe = setInterval ( this.move.bind ( this ), this.duration );
		}.bind(this));
	}.bind(this));
    return;
};

Panels.prototype.highlight = function (x) {
	$(this.element).next().childElements().each(function(e) {
		var i = parseInt(e.id.substr(e.id.lastIndexOf("_")+1));
		if (i == x) {
			e.addClassName("active");
		} else {
			e.removeClassName("active");
		}
	});
};