/**
 * @author Viames Marino
 */

// Cicle's speed in ms
var cicle_speed = 5000;

var totalDivs = 0;

var pagers = '';

var ctime;

var active_image = '/corporate/system/modules/com.lavazza.corporate/resources/images/slideshow-active.gif';

var passive_image = '/corporate/system/modules/com.lavazza.corporate/resources/images/slideshow-passive.gif';

var $j = jQuery.noConflict();

/**
 * Navigate the slideshow in both left or right direction, according to parameter.
 * @param direction string 'left' or 'right'
 * @return void;
 */
function navigate(direction) {
	
	var curr = $j('.dropcontent:visible');
	var next;
	
	if (direction == 'left') {
		if ($j('.dropcontent').index(curr) == 0) {
			next = $j('.dropcontent:last');
		} else {
			next = curr.prev();
		}
	} else {
		if ($j('.dropcontent').index(curr) == totalDivs - 1) {
			next = $j('.dropcontent:first');
		} else {
			next = curr.next();
		}
	}
	
	var curr_idx = $j('.dropcontent').index(curr);
	var next_idx = $j('.dropcontent').index(next);
	
	$j('#page-' + curr_idx).attr('src', passive_image);
	$j('#page-' + next_idx).attr('src', active_image);

	$j('#droptrigger-' + curr_idx).hide();
	$j('#droptrigger-' + next_idx).show();
	
	curr.hide();
	next.show();
}

function cicle() {
	navigate('right');
	ctime = setTimeout('cicle()', cicle_speed);
}

$j(document).ready(

		function() {

			totalDivs = $j('.dropcontent').size();
			
			$j('#droptrigger-0').show();
			$j('.dropcontent:first').show();
			
			// in case of 1 div only, will hide the bottom navbar
			if (1==totalDivs) {
				
				$j('#dropnav').hide();
				$j('#dropnavsingle').show()
			
			} else {
				$j('#dropnavsingle').hide()
				for ( var i = 0; i < totalDivs; i++) {
					pagers += '<img alt="page" class="droppages" id="page-' + i
							+ '" src="' + passive_image + '" />'
				}
	
				$j('#droppages').html(pagers);
				$j('#page-0').attr('src', active_image);
				
				setTimeout('cicle()', cicle_speed);

			}

			$j('#pager-prev').click( function() {
				clearTimeout(ctime);
				navigate('left');
			});

			$j('#pager-next').click( function() {
				clearTimeout(ctime);
				navigate('right');
			});

		}

);