/**
 *   sliderHome v1.0.5
 *
 *   A jQuery plugin based on Marcofolio's article "Advanced Query background image slideshow"
 *   (http://www.marcofolio.net/webdesign/advanced_jquery_background_image_slideshow.html)
 *
 *   @param options (Array) An array containing the settings to override the defaults one
 *
**/

(function($) {
	var defaults = {
			divContainer: "#sliderHomeContainer",
			slideshowSpeed: 6000,
			language: 'es',
			photos: []
		},
		currentImg = 0,
		animating  = false,
		imagesArray = [],
		imagesLoaded = 0,
		options,
		interval,
		fb_share_txt,
		photos_length;

	$.fn.sliderHome = function (options) {
		return this.each(function () {
			// Extends the defaults options
			if (options) {
				$.extend(defaults, options);
			}

			// Set the share button text
			if (defaults.language === 'pt') {
				fb_share_txt = 'Compartilhar';
			} else if (defaults.language === 'es') {
				fb_share_txt = 'Compartir en Facebook';
			} else {
				fb_share_txt = 'Share';
			}

			// Create the structure
			$(defaults.divContainer).append(
				'<div id="headerimgs">\
					<a href="#" class="slider-link">\
						<div id="headerimg1" class="headerimg"></div>\
						<div id="headerimg2" class="headerimg"></div>\
					</a>\
				</div>\
				<div id="slider-wrapper">\
					<div id="headercontainer">\
							<div id="headertxt" class="tcm-rotation">\
									<h5 id="firstline" class="tcm-title2"></h5>\
									<h1 id="secondline" class="tcm-title"></h1>\
									<p id="slider-text"></p>\
									<a href="#" id="slider-button"></a>\
									<a id="slider-fb-button" target="_blank">' + fb_share_txt + '</a>\
							</div>\
							<ul id="slider-selector"></ul>\
					</div>\
							<div id="back" class="btn"></div>\
							<div id="next" class="btn"></div>\
				</div>'
			);

			// For better performance
			photos_length = defaults.photos.length;

			// Backwards navigation
			$("#back").click(function(e) {
				e.stopPropagation();
				stopAnimation();
				navigate("back");
			});

			// Forward navigation
			$("#next").click(function(e) {
				e.stopPropagation();
				stopAnimation();
				navigate("next");
			});

			navigateButtons();

			// Preload content
			for (var i = 0; i < photos_length; i += 1) {
				imagesArray[i] = new Image();
				imagesArray[i].src = defaults.photos[i].image;
				imagesArray[i].onload = function () {
			        imagesLoaded += 1;
			        if (imagesLoaded === photos_length) {
			        	// Start animating the slide
						navigate("next");

						// Create a new timer to slide the pics automatically
						interval = setInterval(function() {
							navigate("next");
						}, defaults.slideshowSpeed);
			        }
				}
			}

		});
	};

	function navigateButtons() {
		var li_controls = '';

		// Create the nav
		for (var i = 1; i <= photos_length; i++) {
			li_controls += '<li id="slider-item-' + i + '" class="slider-selector-item"></li>';
		}
		// Append the nav
		$('#slider-selector').append(li_controls);
		// Assign a click event to each item
		$('.slider-selector-item').each(function (index) {
			$(this).click(function (e) {
				e.stopPropagation();
				if ($(this).hasClass('slider-item-active')) {
					return;
				}
				stopAnimation();
				navigate(index + 1);
			});
		});
		// Apply a hover effect to the navigation
		$(defaults.divContainer).hover(
			function() {
				$(".btn").fadeIn("fast");
			},
			function() {
				$(".btn").fadeOut("fast");
			}
		);
	}

	function navigate(direction) {
		// Check if no animation is running. If it is, prevent the action
		if(animating) {
			return;
		}

		// Check which current image we need to show
		if(direction === "next") {
			currentImg++;
			if(currentImg == photos_length + 1) {
				currentImg = 1;
			}
		} else if (direction === "back") {
			currentImg--;
			if(currentImg == 0) {
				currentImg = photos_length;
			}
		} else {
			currentImg = direction;
		}

		showImage(defaults.photos[currentImg - 1]);
	}

	function stopAnimation() {
		// Clear the interval
		clearInterval(interval);
	}

	function showImage(photoObject) {
		animating = true;

		// Set the new nav item active
		$('.slider-item-active').removeClass('slider-item-active');
		$('#slider-item-' + currentImg).addClass('slider-item-active');

		// Hide the header text
		$("#headertxt").css({"display" : "none"});
		// Set the new header text
		$("#firstline").html(photoObject.firstTitle);
		$("#secondline").html(photoObject.secondTitle);
		$("#slider-text").html(photoObject.description);
		$("#slider-button")
			.attr({
				href: photoObject.linkUrl,
				target: photoObject.target
			})
			.html(photoObject.buttonText);
		$(".slider-link")
			.attr({
				href: photoObject.linkUrl,
				target: photoObject.target
			});

		// Set the new URL for the Facebook Share button
		$("#slider-fb-button")
			.attr({
				href: 'http://www.facebook.com/sharer.php?u=' + encodeURI(photoObject.linkUrl)
			})
			.click(function (e) {
				e.stopPropagation();
			});

		// Add a click event to slider-wrapper
		$("#slider-wrapper").unbind("click").click(function (e) {
			e.stopPropagation();
			window.open(photoObject.linkUrl, photoObject.target);
		});

		// Set the new background, make the fading animation
		// and display the header text
		if ($("#headerimg2").is(":visible")) {
			$("#headerimg1").css({
				"background-image" : "url('" + photoObject.image + "')"
			});
			$("#headerimg2").fadeOut(function () {
				animating = false;
			});
		} else {
			$("#headerimg2").css({
				"background-image" : "url('" + photoObject.image + "')"
			}).fadeIn(function () {
				animating = false;
			});
		}
		$("#headertxt").css({"display" : "block"});
	}
}($jq));
