/*
  Sapo Carousel - A workaround on Bill W. Scott carousel.js script

  Version:	0.3.2
  Author:	David Oliveira - Sapo
 */

/*
 Requires:
	Prototype (externally included) - http://www.prototypejs.org/
	YUI yahoo-dom-event,utilities,dragdrop,container - http://developer.yahoo.com/yui/
	Bill W. Scott Carousel - http://www.billwscott.com/carousel/
*/


// Include some stuff we need

document.write('<script type="text/javascript" src="http://js.sapo.pt/Prototype/1.8/"></script>');
document.write('<script type="text/javascript" src="http://imgs.sapo.pt/js/NOTICIAS2008/yahoo/yahoo-dom-event.js"></script>');
document.write('<script type="text/javascript" src="http://imgs.sapo.pt/js/NOTICIAS2008/yahoo/utilities.js"></<script>');
document.write('<script type="text/javascript" src="http://imgs.sapo.pt/js/NOTICIAS2008/yahoo/dragdrop-min.js"></script>');
document.write('<script type="text/javascript" src="http://imgs.sapo.pt/js/NOTICIAS2008/yahoo/container_core-min.js"></script>');
document.write('<script type="text/javascript" src="http://imgs.sapo.pt/js/NOTICIAS2008/carousel/carousel.js"></script>');


// Global variables

var
	initialized = 0,
	feira = new Array(),
	nextCarrosselId = 0,
	curScrollNav,
	curNavButtons;


// Create new carousel instance

function Carrossel ( size, viewitems ) {

	this.id	= nextCarrosselId;
	this.size = size;
	this.viewItemNr = viewitems;
	this.scrollNav = null;

	this.instance = new YAHOO.extension.Carousel("dhtml-carousel-"+this.id,
		{
			numVisible:			this.viewItemNr,
			scrollInc:			this.viewItemNr,
			size:				this.size,
			animationSpeed:			0.65,
			animationMethod:		YAHOO.util.Easing.easeBothStrong,
			navMargin:			2,
			prevElement:			"prev-"+this.id,
			nextElement:			"next-"+this.id,
			loadInitHandler:		carrosselInit,
			animationCompleteHandler:	updatePageIndicators,
			prevButtonStateHandler:		handlePrevButtonState,
			nextButtonStateHandler:		handleNextButtonState
                }
	);


	// Set id on Carousel instance

	this.instance.cfg.addProperty("id", {
		value: this.id,
		handler: function(type, args, carouselElem) {
		},
		validator: this.instance.cfg.checkNumber
	} );


	feira[nextCarrosselId++] = this;

}


// Initialize carrossel

var carrosselInit = function(type, args, el) {

	createPageIndicators(this,type,args,el);

	// If have more than 1 page, show navigation buttons and scroll nav

	if ( this.getProperty("size") > this.getProperty("scrollInc") ) {
		if ( curNavButtons != null )
			curNavButtons.style.display = 'block';
		if ( curScrollNav != null )
			curScrollNav.style.display = 'block';
	}

};


// Create page indicators on scroll-nav if it exists

var createPageIndicators = function(self, type, args, el) {

	var
		pages, list;


	if ( curScrollNav == null )
		return 0;

	// Calculate page number

	pages = self.getProperty("size") / self.getProperty("scrollInc");
	if ( pages > parseInt(pages) )
		pages = parseInt(pages)+1;

	// Add a list with indicators

	list = document.createElement("UL");
	for ( var x = 1 ; x <= pages ; x++ ) {
		var li = document.createElement("LI");

		li.id = 'pg-'+nextCarrosselId+'-'+x;
		li.innerHTML = "&nbsp;";
		if ( x == 1 )
			li.className = 'active';
		li.onclick = function ( ) {
			var
				idParts = this.id.split('-'),
				carousel = feira[idParts[1]];
			carousel.instance.scrollTo(parseInt(carousel.viewItemNr*(idParts[2]-1))+1);
		};

		list.appendChild(li);
	}
	curScrollNav.appendChild(list);

};


// Update page indicators

var updatePageIndicators = function(type, args) {

	var
		pages,
		id	  = this.getProperty("id"),
		curPage	  = this.getLastVisible() / this.getProperty("scrollInc"),
		scrollNav = feira[id].scrollNav;


	// Calculate page number

	pages = this.getProperty("size") / this.getProperty("scrollInc");
	if ( pages > parseInt(pages) )
		pages = parseInt(pages) + 1;
	if ( curPage > parseInt(curPage) )
		curPage = parseInt(curPage) + 1;

	// Remove actives and just put current page as active

	if ( scrollNav != null ) {
		for ( var x = 1 ; x <= pages ; x++ )
			document.getElementById('pg-'+id+'-'+x).className = '';
		document.getElementById('pg-'+id+'-'+curPage).className = 'active';		
	}

};


// Active/Inactive Prev button

function handlePrevButtonState (type, args) {

        var enabling = args[0];
        var leftImage = args[1];

	if ( leftImage )
		leftImage.className = "prev-"+(enabling ? "active" : "inactive");

}


// Active/Inactive Next button

function handleNextButtonState (type, args) {

        var enabling = args[0];
        var rightImage = args[1];

	if ( rightImage )
		rightImage.className = "next-"+(enabling ? "active" : "inactive");

}


// Detect all the UL's with carousel-list as class name and turn it on a carousel

function initCarrossel() {

	var
		listEls = document.getElementsByTagName("UL"),
		lists = new Array(),
		list, pdiv, cdiv, curCar, args, cNr = 0;


	if ( initialized ) return;


	// Copy list array

	for ( var x = 0 ; x < listEls.length ; x++ )
		lists[lists.length] = listEls[x];

	// For each...

	for ( var x = 0 ; (list = lists[x]) != null ; x++ ) {
		if ( (list.className != "carousel-list") && (list.className.substr(0,14) != "carousel-list ") )
			continue;

		// Get arguments

		args = argsObject(list.className.substr(14,list.className.length-14));

		// Set prev/next button id's

		initCarrosselBotoes(list,nextCarrosselId);

		// Find scrollNav and navButtons

		curScrollNav = ($(list.parentNode.parentNode).select('[class="scroll-nav"]'))[0];
		curNavButtons = ($(list.parentNode.parentNode).select('[class="navButtons"]'))[0];

		// Create the two div elements arround list

		pdiv = document.createElement("DIV");
		pdiv.className = "carousel-component";
		pdiv.id = "dhtml-carousel-"+nextCarrosselId;
		cdiv = document.createElement("DIV");
		cdiv.className = "carousel-clip-region";
		list.parentNode.replaceChild(pdiv,list);
		cdiv.appendChild(list);
		pdiv.appendChild(cdiv);
		list.style.display = 'block';

		// Get items number and group items number

		var
			size = list.getElementsByTagName("LI").length,
			itemsNr = (parseInt(args["items"]) || 3);


		// Create new carousel instance

		curCar = new Carrossel(size,itemsNr);

		curCar.scrollNav = curScrollNav;
		curCar.navButtons = curNavButtons;

		cNr++;
	}

	initialized = cNr;

}


// Search the prev/next buttons and define their id's

function initCarrosselBotoes ( carList, id ) {

	var
		prevs, nexts, node;

	// Go upstairs until find prev element

	node = carList;
	while ( ((node = node.parentNode) != null) && ($(node).select != null) && (prevs = $(node).select('[class="prev"]')) && (prevs.length == 0) ) { }
	node = carList;
	while ( ((node = node.parentNode) != null) && ($(node).select != null) && (nexts = $(node).select('[class="next"]')) && (nexts.length == 0) ) { }

	if ( prevs && prevs.length )
		prevs[0].id = "prev-"+id;

	if ( prevs && nexts.length )
		nexts[0].id = "next-"+id;

}



/*
  Util functions
 */

// Create arguments object based on a string (arg1=val1,arg2=val2)

function argsObject ( str ) {

	var
		sets = str.split(','),
		ret = new Object();

	for ( var x = 0 ; x < sets.length ; x++ ) {
		var nvp = sets[x].split('=');
		ret[nvp[0]] = nvp[1];
	}

	return ret;

}



// Register init event to fire onLoad or 5 seconds after now

if ( document.all )
	attachEvent("onload", initCarrossel);
else
	window.addEventListener("load", initCarrossel, false);

setTimeout(initCarrossel,5000);

