$(window).load(function() {
	initFarandolesWithRetry(0);
});

/**
 * Retry mechanism for IE firing "ready" event with DOM not completely loaded
 */
function initFarandolesWithRetry(nbTry) {
	var nbElems = $('.farandole').length;
	if ((nbTry == null || nbTry < 15) && nbElems == 0) {
		window.setTimeout(function() {
			initFarandolesWithRetry(nbTry + 1);
			return false;
		}, 1000);
		return;
	}
	initFarandoles();
}

/**
 * Inits farandoles
 * @return
 */
function initFarandoles() {
	// Add and adjust scroller size
	$('.farandole .farandoleBody').each(function() {
		var farandoleBody = $(this);
		//Calculate total width of farandole elements
		var elementWidth = $(farandoleBody).find('.farandoleElement')[0].offsetWidth;
		var elementCount = $(farandoleBody).find('.farandoleElement').length;
		var scrollerWidth = elementCount * elementWidth;
		//Add scroller wrapper
		if ($(farandoleBody).find('.farandoleBodyScroller').length == 0) {
			//$(farandoleBody).html('<div class="farandoleBodyScroller">' + $(this).html() + '</div>'); PB IE
			var content = '<div class="farandoleBodyScroller">';
			var data= $(this).html();
			content += data;
			content += "</div>";
			$(farandoleBody).html(content);
			//Set scroller width
			$(farandoleBody).find('.farandoleBodyScroller').css('width', scrollerWidth + 'px');
		}
	});
	
	// Add Pagers
	$('.farandole').each(function() {
		var farandoleDiv = $(this);

		//Calculate page count
		var farandoleWidth = $(this).find('.farandoleBody').width();
		var scrollerWidth = $(this).find('.farandoleBody .farandoleBodyScroller').width();
		var pageCount = Math.ceil(scrollerWidth / farandoleWidth);

		//Append pager inner HTML
		
		// DEBUT MANTIS 24290: CR08 NewHomePage: Les visuels des produits ne s'affichent pas dans les farandoles si =<5 produits qui doivent s'afficher.
		// Si la farandole comporte 5 produits ou moins (soit une seule page/onglet à afficher )
		// on n'affichera pas la liste qui numérote les pages et permet de passer de l'une à l'autre
		// grâce au "display:none;" de la variable pagerStyle 
		
		var pagerStyle = '';
		if (pageCount <= 1) {
		pagerStyle = 'display: none;';
		}
		
		var pagerInnerHTML = '';
		// On retrouve nore variable pagerStyle: Soit elle est à "display:none" (1 seule page donc pas d'affichage de la liste <ul>)
		// Soit c'est une string vide ('')donc on affiche notre liste <ul>
		pagerInnerHTML += '<ul style="' + pagerStyle + '">';
		// FIN MANTIS 24290
		
		pagerInnerHTML += '<li class="farandolePagePrev"><a href="#"><span>Prev</span></a></li>';
		for (var i = 1; i <= pageCount; i++) {
			pagerInnerHTML += '<li class="farandolePageNumber">'
			pagerInnerHTML += '<a href="#"><span>' + i + '</span></a>'
			pagerInnerHTML += '</li>';
		}
		pagerInnerHTML += '<li class="farandolePageNext"><a href="#"><span>Next</span></a></li>';
		pagerInnerHTML += '</ul>';

		$(this).find('.farandolePager').html(pagerInnerHTML);

		//Goto page 1
		farandoleGotoPage(farandoleDiv, $(this).find('.farandolePager .farandolePageNumber')[0]);	
		
		//Bind pager events
		$(this).find('.farandolePager .farandolePageNumber a').click(function() {
			var pageNumber = $(this).parent();
			$(farandoleDiv).removeClass('autoscroll');
			farandoleGotoPage(farandoleDiv, pageNumber);
			return false;
		});
		$(this).find('.farandolePager .farandolePagePrev a').click(function() {
			var pageNumber = $(this).parent();
			$(farandoleDiv).removeClass('autoscroll');
			farandolePagePrev(farandoleDiv);
			return false;
		});
		$(this).find('.farandolePager .farandolePageNext a').click(function() {
			var pageNumber = $(this).parent();
			$(farandoleDiv).removeClass('autoscroll');
			farandolePageNext(farandoleDiv);
			return false;
		});
	});
	
	// Autoscroll Init
		$('.farandole.autoscroll').each(function() {
			// Autoscroll the ones that have 'autoscroll' class
			var farandoleAutoscrollDelay = 2500; // Delay between page switch
			
			var farandoleDiv = $(this)[0];
			// Calculate number of pages
			var pageCount = $(farandoleDiv).find('.farandolePager .farandolePageNumber').length;
			var i = 1;
			// Each 'farandoleAutoscrollDelay' scroll to next page
			var interval = setInterval(function() {
				// Abort if class 'autoscroll' is missing
				if (!$(farandoleDiv).is('.autoscroll')) {
					clearInterval(interval);
					return;
				}
				// At last page, return to first page
				if (i++ >= pageCount) {
					i = 1; // reinit counter
					farandoleGotoPage(farandoleDiv, $(farandoleDiv).find('.farandolePager .farandolePageNumber')[0]); // Goto first page
					// If class 'once' is found, force to stop autoscroll after first cycle
					if ($(farandoleDiv).is('.once')) {
						$(farandoleDiv).removeClass('autoscroll');
					}
				} else {
					farandolePageNext(farandoleDiv); // Goto next page
				}
			}, farandoleAutoscrollDelay);
		});
}

function farandolePageNext(farandoleDiv) {
	farandoleGotoPage(farandoleDiv, farandoleGetPrevOrNextPageLi(farandoleDiv, true));
}

function farandolePagePrev(farandoleDiv) {
	farandoleGotoPage(farandoleDiv, farandoleGetPrevOrNextPageLi(farandoleDiv, false));
}

/**
 * Finds next/previous page based on the pagenumber that has the 'actif' class
 * @param farandoleDiv
 * @param isNext
 * @return
 */
function farandoleGetPrevOrNextPageLi(farandoleDiv, isNext) {
	var currentPageLi = $(farandoleDiv).find('.farandolePager .farandolePageNumber.actif');
	if (currentPageLi == null || currentPageLi.length == 0) {
		return $(farandoleDiv).find('.farandolePager .farandolePageNumber')[0];
	}
	var newPageLi = isNext ? $(currentPageLi).next('.farandolePageNumber') : $(currentPageLi).prev('.farandolePageNumber');
	if (newPageLi == null || newPageLi.length == 0) {
		return currentPageLi;
	}
	return newPageLi;
}

/**
 * - Calculates position of the scroller for a given page
 * - Sets 'actif' class on the new active page
 * - Scrolls to the active page
 * @param farandoleDiv
 * @param newPageLi
 * @return
 */
function farandoleGotoPage(farandoleDiv, newPageLi) {
	// TODO: Page number is deducted from the html content of the div element,
	// this could be deducted from the position of the element within its siblings
	var pageNumber = $(newPageLi).text(); 
	var farandoleWidth = $(farandoleDiv).find('.farandoleBody').width();
	var newPositionLeft = -1 * (pageNumber - 1) * farandoleWidth;
	
	$(farandoleDiv).find('.farandolePager .farandolePageNumber').removeClass('actif');
	$(newPageLi).addClass('actif');
	
	// Check for async loaded images
	$(farandoleDiv).find('.farandoleElement').each(function() {
		if (isElementVisible(this, newPositionLeft, farandoleWidth)) {
			$(this).find('img.with-async-load').each(function() {
				$(this).removeClass('with-async-load');
				$(this).attr('src', $(this).attr('src-async'));
				$(this).removeAttr('src-async');
			});
		}
	});
	
	farandoleGotoPosition(farandoleDiv, newPositionLeft);
}

/**
 * Animates the farandole scroller
 * @param farandoleDiv
 * @param positionLeft
 * @return
 */
function farandoleGotoPosition(farandoleDiv, positionLeft) {
	$(farandoleDiv).find('.farandoleBody .farandoleBodyScroller').animate({left: positionLeft }, 500, function() {
		$(this).css('left', positionLeft + 'px');
	}); 
}
function isElementVisible(farandoleElementDiv, newPositionLeft, farandoleWidth) {
	var newElementOffsetLeft = farandoleElementDiv.offsetLeft + newPositionLeft
	var isVisible = newElementOffsetLeft >= 0 && newElementOffsetLeft < farandoleWidth;
	return isVisible;
}
