/**
 * Perform jQuery library
 * Developed by Adam Coogan, Hugh Maclachlan, Ben Affleck
 *
 * Built on top of the jQuery library
 * http://jquery.com
**/

(function($) {

     /**
     * Creates a news reader from an unordered list
     **/
    //var e;
	
	
    // Default vars
    //var changeItemsInterval = [];
	var newsReaders = [];
	var changeItemsInterval = [];
	//var readerId = [];
	//var thumbnailsId = [];
	
    $.fn.newsReader = function(o) {
		              
        return this.each(function(index) {
			//newsReaders.push[this];
			//return 
			new $nr(this, o, index);
        });      
    };

    // Default configuration properties.
    var defaults = {
        speed: 8,
        start: 0,
        tooltips: false,
        focus: true,
        thumbsInFocus: true,
		headlineLimits:
			{
				thumb: null,
				newsReader: null,
				indicator: ""
			},
		thumbDisplay: 
			{
				image: true,
				teaser: false,
				headline: 
					{
						show:false,
						onHover:false
					},
				timestamp: false,
				relatedlinks: false,
				videoIcon: ""
			},
		newsReaderDisplay:
			{
				image: true,
				headline: 
					{
						show:true,
						onHover:false
					},
				teaser: true,
				timestamp: false,
				relatedlinks: false
			},
		fuzzyDates:false
    };

	
	function limitHeadlines(containerDiv, headlineLimit, indicator) {
		if (headlineLimit != null) {
			textPath = "#" + containerDiv + " li div h1";
			if ($(textPath + ":first").find("a")) {
				textPath += " a";
			}
			
			addSpan = ($(textPath + ":first").find("span"));
			$(textPath).each(function() {
				var headlineHTML = $(this).remove("span").html();
				if (headlineHTML.length > headlineLimit) {
					$(this).html(jQuery.trim(headlineHTML.substr(0, (headlineLimit - indicator.length))) + indicator);
				}
				if (addSpan) {
					$(this).append("<span></span>");
				}
			});
		}
		
		
	}
	
	function setDisplay(containerDiv, options) {
		if (!options.image) {
			$("#" + containerDiv + " > li > a").remove();
		}
		if (!options.headline.show) {
			$("#" + containerDiv + " li div h1").hide();
		}
		if (!options.timestamp) {
			$("#" + containerDiv + " div .timestamp").hide();
		}
		if (!options.teaser) {
			$("#" + containerDiv + " div p").remove();
		}
		if (!options.relatedlinks) {
			$("#" + containerDiv + " div .related").remove();
		}
	}
	
	function addHover(anchorLocation, nrIndex){
		// Bind the onMouseOver and onMouseOut to the anchor tags
        $("#" + newsReaders[nrIndex].thumbsId + " > li > " + anchorLocation).each(function(index){
         
            // Bind the onMouseOver function 
            $(this).bind("mouseenter",function() {
                jQuery.newsReader.onHoverIn(index, nrIndex);
            });
            
            // Bind the onMouseOut function
            $(this).bind("mouseleave",function() {
                jQuery.newsReader.onHoverOut(index, nrIndex);
            });
            
        });
	}
    $.newsReader = function(e, o, nrIndex) {
        // Stylesheet should be set to display none so browsers can render more cleaner
        $(e).show();
        
        // Combine the default and user configurations together        
        this.settings = $.extend({}, defaults, o || {});
        s = this.settings;
		
		var tempReaderId = $(e).attr('id');
		if ((!tempReaderId) || (tempReaderId.length==0)) {
			//make up an id for our reader container ul
			tempReaderId = (new Date()).getTime();
		}
		//readerId.push(tempReaderId);
		//thumbnailsId.push(tempReaderId + "Thumbs");
		
		// The default position of News Reader
        var tempPos = s.start;
        
        // Count the length of items
        var tempCount = $(e).children().length-1;
        
        // Check that the count isn't less than the start position
        if(tempCount<tempPos) {
            tempPos = 0;
        } else {
            tempPos = s.start;
        }
		
		newsReaders.push({
			ul: e, 
			readerId: tempReaderId, 
			thumbsId: tempReaderId + "Thumbs",
			pos: tempPos,
			count: tempCount
		});
		
        // Default vars
        //var changeItemsInterval;
        
        // Clone the UL to create the thumbnails
        var ulThumbs = $(e).clone().attr("id",newsReaders[nrIndex].thumbsId).removeClass("newsReader").addClass("thumbnails").insertBefore(e);
		$("#" + newsReaders[nrIndex].thumbsId + " div.flashDiv").remove();
				
		//do it the new way
		setDisplay(newsReaders[nrIndex].thumbsId, s.thumbDisplay);
		setDisplay(newsReaders[nrIndex].readerId, s.newsReaderDisplay)
		
		limitHeadlines(newsReaders[nrIndex].thumbsId, s.headlineLimits.thumb, s.headlineLimits.indicator);
		limitHeadlines(newsReaders[nrIndex].readerId, s.headlineLimits.newsReader, s.headlineLimits.indicator);
		
		//work out if each item is a video, and if it is, include the play video icon in the thumbnail
		$("#" + newsReaders[nrIndex].readerId + " > li > a").each(function (index) {
			if(!($(this).find(".overlay").attr("src") === undefined)) {
				var liVideoIcon = $("#" + newsReaders[nrIndex].thumbsId + " > li:eq(" + index + ")").find(".timestamp");
				$('<div class="videoIcon"><img src="' + s.thumbDisplay.videoIcon + '" alt="Video" title="Video" /></div>').insertBefore(liVideoIcon);
			}
		});
		
		//add hovers
		addHover("div > h1 > a", nrIndex);
		addHover("a", nrIndex);
		
        // Hide all the li items apart the starting position
        $(e).children().each(function(i){
            if(i!=tempPos) {
                $(this).hide();
            }
        });
        
        // Function onHoverIn, this stops the looping and changes the selected item to the one the mouse is hovering on
        $.newsReader.onHoverIn = function (index, nrInd) {
            clearInterval(changeItemsInterval[nrInd]);
            if(s.thumbsInFocus) {
                //changeItem(e,pos,index,count);
				 changeItem(newsReaders[nrInd].pos,index,newsReaders[nrInd].count, nrInd);
            }
            if(s.thumbDisplay.headline.onHover) {
                $($("#" + newsReaders[nrInd].thumbsId + " div").children("h1")[index]).show();
           	}
        };
        
        // Function onHoverOut, this starts the looping again
        $.newsReader.onHoverOut = function (index,nrInd) {
			$.newsReader.pauseReader(nrInd);
			//clearInterval(changeItemsInterval);
            newsReaders[nrInd].pos=index;
			//$.newsReader.startReader();
			$.newsReader.startReader(nrInd);
			//changeItemsInterval = setInterval(function(){changeItem(e, readerId, pos, pos + 1, count)}, s.speed * 1000);
            if(s.thumbDisplay.headline.onHover) {
                $($("#" + newsReaders[nrInd].thumbsId + " div").children("h1")[index]).hide();
            }
        };
        
		$.newsReader.pauseReader = function (nrInd) {
			clearInterval(changeItemsInterval[nrInd]);
		}

		$.newsReader.startReader = function(nrInd){
			// set interval to call the function changeItem
			changeItemsInterval[nrInd] = setInterval(function(){
			 		changeItem(newsReaders[nrInd].pos, newsReaders[nrInd].pos + 1, newsReaders[nrInd].count, nrInd)
			 	}
				, s.speed * 1000);
		}
		
		$.newsReader.resetReader = function(nrInd, resetValue){
			$.newsReader.pauseReader(nrInd);
			changeItem(newsReaders[nrInd].pos, resetValue, newsReaders[nrInd].count, nrInd);
			$.newsReader.startReader(nrInd);
		}

		$nr.startReader(nrIndex);
		//startReader(nrIndex);
		
        // Change one LI to another
        function changeItem(from,to,count, nrInd) {
			$("#" + newsReaders[nrInd].readerId).children("> li").each(function(){
			//$(e).children("> li").each(function(){
                $(this).hide();
            });
			
			$("#" + newsReaders[nrInd].thumbsId).children([from]).removeClass("active");
			
			if ((from >= count) && (to > from)) {
				to = 0;
			}
			
			$($("#" + newsReaders[nrInd].readerId).children("> li")[to]).show();
			//$($(e).children("> li")[to]).show();
			$($("#" + newsReaders[nrInd].thumbsId).children("> li")[to]).addClass("active");
			newsReaders[nrInd].pos=to;
        }
    }
    
    // Create shortcut for internal use
    var $nr = $.newsReader;

})(jQuery);

/* 
 This function is used to play video items within the newsreader. 
 Stops the rotation and plays the video.
 When the user hovers over the thumbnails section, the rotation starts up again.
*/
function pauseNewsreaderAndPlay(ulId, clipId, index){
	var divReplace = '<div id=\"' + ulId + '_flashPlayer_'+clipId+'\" />';
	
	<!-- hide the overlay when we click on video -->
	$("#" + ulId + " > li > a").css("visibility","hidden");
	$("#" + ulId + " li .item").css("visibility","hidden");
	$.newsReader.pauseReader(index);
	$("#" + ulId + "_flashContainer_" + clipId).show();
	flashVars.clipId = clipId;
	swfobject.embedSWF("http://www.chelseafc.co.uk/flash/unifiedplayer/UnifiedPlayer.swf", ulId + "_flashPlayer_" + clipId, "640", "360", requiredFlashVersion, false, flashVars, flashParams, {});
	
	<!-- show the video again when we move over another thumbnail -->
	$("#" + ulId + "Thumbs").hover(function(){
		$("#" + ulId + " > li > a").css("visibility","visible");
		$("#" + ulId + " li .item").css("visibility","visible");
		swfobject.removeSWF(ulId + "_flashPlayer_" + clipId);
		$("#" + ulId + "_flashContainer_" + clipId).html(divReplace);
		$("#" + ulId + "_flashContainer_" + clipId).hide();
		$.newsReader.startReader(index);
		$(this).unbind();
	}, function(){});
	
	return false;
}
