/* 
 * WNF Homepage trailer jQuery plugins
 * 
 * Author: Gerwert Stevens <gerwert@fier.nl> - Fier Concept & Design
 * Version: 0.15 - december 2010
 *
 */

/* 
 * WNF Home trailer jQuery plugin
 *
 * Dependent on:
 *	- jQuery 1.4+
 * 	- jCarouselLite (http://www.gmarwaha.com/jquery/jcarousellite/#doc)
 */
 (function($) {
    $.fn.wnf_home_trailer = function(options) {
        var defaults = {
            start: 2,
            speed: 10000,
            auto: true,
            items: new Array()
        };

        // Extend our default options with those provided.
        var options = $.extend(defaults, options);
        var items = options.items;
        var start = options.start;

        // Booleans that indicate animation status
        var headlineHiding = false;
        var headlineShowing = false;
        var imageShowing = false;

        // Prefetched jQuery objects
        var self = $(this);
        var $he = $(".headline");
        var $hdViewPort = $(".headline-viewport");
        var $mainLink = $("#main-link");
        var $mainImg = self.find("#main-image");

        // timer
        var timer;

        // Create story items
        var imgPreloadQueue = new Array();
        $.each(items, function(index, value) {
			// Create HTML for list item
            var html = "<li class='story generated' id='s" + index + "'>";
            var thumb = value["THUMBIMAGE"] || "images/ht_dummy_thumbnail1.jpg";
            html += "<div class='thumbnail'>";
            html += " <img width=\"64\" height=\"50\" src=\"" + thumb + "\" alt=\"\" />";
            html += "</div>";
            html += "<div class='title'>";
            html += "<span>" + value["BUTTONTEXT"] + "</span>";
            html += "</div>";
            html += "</li>";
            // Create jQuery object from list item
            var $el = $(html);
            // Append list item to end of list
            $("ul.stories").append($el);
			// Add image to preload queue
            imgPreloadQueue.push(value["BACKGROUNDIMAGE"]);
            // Add hidden image; to be used in cross-fade
            $simg = $("<img style='position: absolute; top: 0; border: none !important; left: 0; display: none; width: 980px; height: 310px' id='slideImage" + index + "' style='display: none' src='" + value["BACKGROUNDIMAGE"] + "'  />");
            $mainLink.append($simg);
        });
		// preload images
        $.preLoadImages(imgPreloadQueue);
        		
        var $stories = $("li.story");

        var storyCarousel = jQuery('#home-trailer .body').jCarouselLite({
            btnNext: "#ht_nav_up",
            btnPrev: "#ht_nav_prev",
            vertical: true,
            beforeStart: beforeStorySlide,
            afterEnd: afterStorySlide
        });

        $stories.live('click', function() {
            var clickedIndex = ($(this).index());
            var clickedId = $(this).attr("id");
            if (! ($(this).hasClass("active"))) {
                storyCarousel.slideTo(clickedIndex - 2);
            } else {
                $mainLink.click();
                // Gecko does not respond to click events on links, so we manually follow the link
                window.location = $mainLink.attr("href");
            }
        });

        $stories.live({
            mouseenter: function() {
                $(this).addClass("hover");
            },
            mouseleave: function() {
                $(this).removeClass("hover");
            }
        });

        init();

        function init() {
            setHeadline(start);
            // set initial content: third item
            setImage(start);
            $stories.eq(start).addClass("active");
            /*
				// After 2 secondes: show stories panel
				var timer = setTimeout(function() {
						$(self).find(".stories-panel").fadeIn("fast");
				}, 2000);
				*/
            if (options.auto) {
                clearAndSetTimer();
            }
        }

        function clearAndSetTimer() {
            if (timer)
                clearTimeout(timer);
            timer = setInterval(function() {
                storyCarousel.next();
            }, options.speed);
        }

        function headlineHide() {
            headlineHiding = true;
            $hdViewPort.hide('slide', {
                direction: 'right'
            }, 800, function() {
                headlineHiding = false;
            });
            $(self).find(".headline").fadeOut(300);
        }

        function headlineShow() {
            headlineShowing = true;
            $hdViewPort.show('slide', {
                direction: 'right'
            }, 1000, function() {
                headlineShowing = false;
            });
            $(self).find(".headline").fadeIn(800);
        }

        function beforeStorySlide(visibleElements) {
            if (headlineShowing || headlineHiding) {
                console.log("cancel");
                cancel();
            }
            $("li.story").removeClass("active");
            headlineHide();
        }

        function cancel() {
            $hdViewPort.stop(true, true);
            $he.stop(true, true);
            $mainImg.stop(true, true);
        }

        function afterStorySlide(visibleElements) {
            var selectedId = $(visibleElements).last().attr("id");
            var index = selectedId.substr(1);
            setHeadline(index);
            setImage(index, true);
            headlineShow();
            $(self).find("#" + selectedId).addClass("active");            
            clearAndSetTimer(timer); // Reset timer
        }

        function setHeadline(index) {
            var item = items[index];
            // set content of headline
            if (item != undefined) {
                $he.find("h1").text(item["TITLE"]);
                $he.find("#subtext").text(item["TEXT"]);
                $mainLink.attr("href", item["DETAILURL"]);
                
				// Set icon
				$icon = $he.find("#subtext-icon");
                if (! (item["VIDEOFLV"] == "")) {
					$icon
					  .removeClass("video goto")
					  .addClass("video");
                } else {
					$icon
					  .removeClass("video goto")
					  .addClass("goto");
                }
            }
        }

        function setImage(newIndex, animate) {
            var item = items[newIndex];
            if (animate == true) {
                if (imageShowing == true) {
				}
                imageShowing = true;
                /*
				  $mainImg.fadeOut(400, function() {
					$(this).attr("src", item["BACKGROUNDIMAGE"]).fadeIn(400, function() {					
						imageShowing = false;
					});
				  });              
				  */
                $mainImg.fadeOut(400, function() {
                    $(this).attr("src", item["BACKGROUNDIMAGE"]);
                    imageShowing = false;
                });
                id = "slideImage" + newIndex;
                $hiddenImage = $(self).find("#" + id);
                $hiddenImage.fadeIn(700, function() {
                    $(this).hide();
                    $mainImg.show();
                });

            } else {
                $mainImg.attr("src", item["BACKGROUNDIMAGE"]);
            }
        }
    };

})(jQuery);

/*
 * A simple jQuery plugin to preload images.
*/
 (function($) {
    var cache = [];
    // Arguments are image paths relative to the current page.
    $.preLoadImages = function(arguments) {
        var args_len = arguments.length;
        for (var i = args_len; i--;) {
            var cacheImage = document.createElement('img');
            cacheImage.src = arguments[i];
            cache.push(cacheImage);
        }
    }
})(jQuery)
