/**
 *   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',
			target: '_self',
			photos: [],
			url:'',
			hightlightLinkUrl:'programacion'
		},
		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);
			}

			// 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="slider-hour"><p id="highlightTime"></p></div>\
					<div id="headertxt" class="isat-bold-font">\
						<h1 id="secondline"></h1>\
						<p id="slider-text"></p>\
					</div>\
					<ul id="slider-selector" class="noDisplay"></ul>\
				</div>\
							<div id="back" class="btn noDisplay"></div>\
							<div id="next" class="btn noDisplay"></div>\
				</div>\
				<div class="isat-slider-highlight isat-bold-font">\
					<a class="isat-slider-highlight-link" href="'+defaults.hightlightLinkUrl+'">\
						<div class="isat-slider-highlight1 isat-slider-highlight-elem"></div>\
						<div class="isat-slider-highlight2 isat-slider-highlight-elem"></div>\
						<div class="isat-slider-highlight3 isat-slider-highlight-elem"></div>\
						<div class="isat-slider-highlight4 isat-slider-highlight-elem"></div>\
					</a>\
				</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].onerror = function (){
					for (var i = 0; i < photos_length; i += 1) {
						if(defaults.photos[i].image==this.src){
							defaults.photos[i].image = defaults.url+'\default.jpg';
							imagesArray[i].src = defaults.photos[i].image;
							imagesArray[i].onerror="";
						}
					}
					return true;
				};
				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;
		var description,
			photoTarget = typeof photoObject.target !== 'undefined' ? photoObject.target : defaults.target;

		// 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);
		//Length Check
		if(photoObject.description.length>170){
			photoObject.description=photoObject.description.substring(0,170)+" ...";
		}
		$("#slider-text").html(photoObject.description);
		$("#highlightTime").html(photoObject.highlightTime);
		if (typeof photoObject.linkUrl !== 'undefined') {
			$(".slider-link")
				.attr({
					href: photoObject.linkUrl,
					target: photoTarget
				});
		}
		/* 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
		if (typeof photoObject.linkUrl !== 'undefined') {
			$("#slider-wrapper").unbind("click").click(function (e) {
				e.stopPropagation();
				window.open(photoObject.linkUrl, photoTarget);
			});
		} else {
			$("#slider-wrapper").unbind("click");
		}

		// 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));
