// Declare the loading functions 
var loading = {
	start: function () {
		// Show loading div
		$('#loading').show();
		// Start the animation
		loadingAnimation('loading');
	},
	end: function () {
		// Hide div
		$('#loading').hide();
		// Destroy contents of the  div
		$('#loader').html('');
	}
};

// Variable to indicate if we have to shift the left
var doLeftShift = false;

$(document).ready(function() {

	// Decide if the carousel should wrap or not
	var wrap = null;
	// Enable wrap if there is more then 6
	if ($('#featuredListingFrontend #navigation > li').size() > 6) {
		wrap = 'circular';
		
	}

	
    // https://github.com/jsor/jcarousel/issues/issue/7
    // ça corrige le problème de dimension sous IE7 - Ray
	if($.browser.msie && jQuery.browser.version == '7.0'){
		$('#featuredListingFrontend #navigation').jcarousel({itemFallbackDimension: 81});
	}    
	var nbThumb = $("img.srcTmp").length ;
	
	var start = (nbThumb < 7 ) ? 1 : 2;
	
	if(start == 1)
		wrap = 'both';

	$('#featuredListingFrontend #navigation').jcarousel({                
		wrap: wrap,
		start: start,
		scroll: 1,
		itemFirstOutCallback: function(carousel, item, idx, state) {
			// refill images src in case empty
			$(".srcTmp").each(function(){
				if($(this).attr("src") == "" && $(this).attr("alt") !=""){
					$(this).attr("src",$(this).attr("alt"));
				}
		    });
		
			// Only care about next scrolls and if the item has the selected class
//			if (state == 'next' && $(item).hasClass('selected')) {
//				doLeftShift = true;
//			}
			
			if(state == 'prev'){
				$('li.selected').removeClass('selected');
				if(start == 1)
				{	
					//block carousel on left side
					var index = $('li.jcarousel-item').index($('li.selected')) ;
					if(index > 0)
					{
						$(item).addClass('selected') ;
						updatePropertyDetails($('li.selected img'));
					}
				}
				else{
					$(item).prev().addClass('selected') ;
					updatePropertyDetails($('li.selected img'));
				}
			}
			
			if(state == 'next'){
				$('li.selected').removeClass('selected');
				if(start == 1)
				{
					//block carousel on right side
					var index = $('li.jcarousel-item').index($('li.selected')) ;
					if(index < nbThumb - 1)
					{	
						$(item).addClass('selected') ;
						updatePropertyDetails($('li.selected img'));
					}
				}
				else{
					$(item).next().addClass('selected') ;
					updatePropertyDetails($('li.selected img'));
				}
			}
		}
	
	});
	
	// Up the width to compensate for the increased size of the selected one
	$('#navigation').width($('#navigation').width() + 18);

	$('#featuredListingFrontend .jcarousel-item img').click(function(){
		updatePropertyDetails($(this));
	});

	//select the first or the second thumbnail according the count of photo
	//There is a lag of one picture because the loading is asynchronous
	if( start == 1){
            $('#featuredListingFrontend .jcarousel-item img').eq(0).click(); // Click only the first one
            $('.jcarousel-prev').css("display", "none");
            $('.jcarousel-next').css("display", "none");
        } else {
            $('#featuredListingFrontend .jcarousel-item img').eq(1).click(); // Click only the second one
        }
	
	$('.jcarousel-next-horizontal').addClass('rightArrow');
	$('.jcarousel-prev-horizontal').addClass('leftArrow');
	
});

function updatePropertyDetails($o)
{
	// Shift the left of the navigation container if needed
//	if (doLeftShift) {
//	
//		// Get the left of the navigation
//		var position = $('#navigation').position();
//		var left = position.left;
//		// Add 18 to the left and set
//		$('#navigation').css('left', parseInt(left) + 18);
//		doLeftShift = false;
//		
//	}
	
	// Start loading animation
	loading.start();

	$('#featuredListingFrontend .jcarousel-item.selected').removeClass('selected');
	var source = $o.attr('photo');
	$o.parent().addClass('selected');

	// Get the house information
	redoPropertyInfo($o.attr('propertyID'));
	$('#featuredListingFrontend #body #photo #propertyImage').attr('src', source );
}

function loadingAnimation(__elemID)	{
	// Credit goes to the Raphael team for this demo code
	var sectorsCount = 12 || 12,
	color = "#FFF" || "#fff",
	width = 15 || 15,
	r1 = Math.min(40, 80) || 35,
	r2 = Math.max(40, 80) || 60,
	cx = r2 + width,
	cy = r2 + width,
	tDim = r2 * 2 + width * 2,

	sectors = [],
	opacity = [],
	beta = 2 * Math.PI / sectorsCount,

	pathParams = {stroke: color, "stroke-width": width, "stroke-linecap": "round"};
	var gR = Raphael('loader', tDim, tDim);
	Raphael.getColor.reset();

	// Center the loading vector
	$('#loader').css({ 'left': ( ($('#'+__elemID).width()/2)-(tDim/2) )+'px', 'top': ( ($('#'+__elemID).height()/2)-(tDim/2) )+'px' });

	for (var i = 0; i < sectorsCount; i++)
	{
		var alpha = beta * i - Math.PI / 2,
		cos = Math.cos(alpha),
		sin = Math.sin(alpha);
		opacity[i] = 1 / sectorsCount * i;
		sectors[i] = gR.path([["M", cx + r1 * cos, cy + r1 * sin], ["L", cx + r2 * cos, cy + r2 * sin]]).attr(pathParams);
		if (color == "rainbow") {
			sectors[i].attr("stroke", Raphael.getColor());
		}
	}
	var tick;
	(function ticker()
	{
		opacity.unshift(opacity.pop());
		for (var i = 0; i < sectorsCount; i++)
		{
			sectors[i].attr("opacity", opacity[i]);
		}
		gR.safari();
		tick = setTimeout(ticker, 1000 / sectorsCount);

		return function()
		{
			clearTimeout(tick);
			gR.remove();
		};
	})();
	// End loader
}



