/**
 * 
 * Perform jQuery library
 * Developed by Perform
 * 
 * Built on top of the jQuery library
 * http://jquery.com
 *
 * Description: Creates a news reader from an unordered list
 *
 * Version: 1.1.2
 *
 * Wiki(s):
 * http://helpdesk.premiumtv.co.uk/mediawiki/index.php/Web_Development_Plugins
 * http://helpdesk.premiumtv.co.uk/mediawiki/index.php/JQuery_Newsreader_Plugin
 * 
**/

/** 
 * 
 * TODO List - 
 * 
 * TODO: #1 Implement improved video library tie in
 * TODO: #2 Create callbacks functions
 * TODO: #3 Handle the direction the newsreader changes
 * 
**/

     
(function($) {

	// default vars
	var newsreaders = [];					// The Newsreader Array - this is to handle multiple newsreaders on one page
	var changeItemsInterval = [];			// Similar to above - this is to handle the setInternal per newsreader on the page
	
    $.fn.newsReader = function(options) {	// Create the newsreader(s)
        return this.each(function(index) {	// For each instance of the match selector create a newsreader
			new $nr(this, options, index);	// Create a new newsreader instance with element, options and index passed to the instance
        });      
    };       

    // Default configuration properties.
    var defaults = {
        speed: 8,							// Default transition speed (8 seconds)
        start: 0,							// Starting index on the UL					
        itemChangeOnHover: true,			// Changes the the UL to the current hovered thumbnail
        // Controls what is displayed on the newsreader
        display: {
        	thumbnails: true,				// Displays the thumbnails if true
        	pagination: true,				// #3 Adds pagination links for galleries // TODO
        	navigation: false               // Adds Next and Prev links 
        },    
        // Controls the thumbnail properties
        thumbnails: {
        	removeClassesAndTagsSelector: [] // Array of classes/tags that need to be removed from the thumbnails clone
        },
        // Controls the newsreader properties
        newsreader: {
        	removeClassesAndTagsSelector: [] // Array of classes/tags that need to be removed from the main newsreader that is needed for the thumbnails
        },
		// Transition 
		transition: {
			command : false,
			loop: false,
			buttons: false,
			type: "crossFade" 				//The only available at the moment
		}					 
    };
    	
    // this create the instance of a newsreader
    $.newsreader = function(e, o, newsreaderIndex) {
    	    								
    	// Show the newsreader - Should be hidden in the CSS to render a cleaner load
    	$(e).show();																
    	
    	// Combine the default and sites configuration options together
        s = $.extend({}, defaults, o || {});					         		
        
        // Check if the current matched element has an id, otherwise set the id as the current date
        var currentElementId = $(e).attr("id"); // Set the current UL id				 
        currentElementId = !currentElementId || currentElementId.length == 0 ? (new Date()).getTime() : $(e).attr("id");
		                
        // Count the length of items in the UL
        var count = $(e).children().length - 1;
        
        // Check that the count isn't less than the starting index position
        s.start = count < s.start ? 0 : s.start;	
		
        // Setup the information for the newsreader array(s). This is too handle multiple newsreaders on one page
		newsreaders.push({
			ul: e,									// The UL Element of the newsreader
			newsreader: {						
				id: currentElementId				// The current Id of the newsreader
			},
			thumbnails: {
				id: currentElementId + "Thumbs"		// The current Id of the thumbnails of the newsreader
			}, 
			pagination: {
				id: currentElementId + "Pag"		// The current Id of the pagination button of the newsreader
			},
			position: s.start, 						// The position is set to the start index of the newsreader
			count: count							// The count of items in the current UL
		});
        
        // Clone the UL to create the thumbnails if the display thumbnails property is true
		if(s.display.thumbnails) {
        	var ulThumbs = $(e).clone().attr("id",newsreaders[newsreaderIndex].thumbnails.id)
        					.removeClass()				// Remove class applied to the original UL element
        					.addClass("thumbnails")		// Add the class thumbnails
        					.insertBefore(e);			// Insert before the original UL Element
    	}
		
		// Creates a list of anchors if the display pagination property is true
		if(s.display.pagination) {
        	var ulPag = $(e).clone().attr("id",newsreaders[newsreaderIndex].pagination.id)
        					.removeClass()				// Remove class applied to the original UL element
        					.addClass("pagination")		// Add the class thumbnails
        					.insertAfter(e);			// Insert after the original UL Element
    		
			$("#" + newsreaders[newsreaderIndex].pagination.id).children().each(function(index){
				$(this).removeAttr("id");
				$(this).html("<a href='#' class='newsPagA'><span class='bullet'>&#8226;</span><span class='number'>"+(index+1)+"</span></a>");
			});
			
			// Bind the onMouseOver and onMouseOut to the anchor tags
            $("#" + newsreaders[newsreaderIndex].pagination.id + " > li > a").each(function(index){             
                // Bind the onMouseOver function - this calls the onHoverIn function 
                $(this).bind("mouseenter",function() {
                	// Bind the onHoverIn Function to the button
                	var avoidAnyTransition = true;
					jQuery.newsreader.onHoverIn(index, newsreaderIndex);  
				});                
                // Bind the onMouseOut function - this calls the onHoverOut function
                $(this).bind("mouseleave",function() {
                	// Bind the onHoverOut Function to the button                	
                	jQuery.newsreader.onHoverOut(index, newsreaderIndex); 
					avoidAnyTransition = false;
                });                
            });	
		}
				
		// Loops over the removeClassesAndTagsSelector and removes any matched selector from the array from the thumbnails
		$.each(s.thumbnails.removeClassesAndTagsSelector, function(index, value) {
			// Remove the matched item
			$("#" + newsreaders[newsreaderIndex].thumbnails.id + " " + this).remove();		
		});

		// Loops over the removeClassesAndTagsSelector and removes any matched selector from the array from the newsreader
		$.each(s.newsreader.removeClassesAndTagsSelector, function(index, value) {
			// Remove the matched item
			$("#" + newsreaders[newsreaderIndex].newsreader.id + " " + this).remove();		
		});			
		
		// Check if the thumbnails should change on hover
        if(s.itemChangeOnHover) {
        	// Bind the onMouseOver and onMouseOut to the anchor tags
            $("#" + newsreaders[newsreaderIndex].thumbnails.id + " > li > a").each(function(index){             
                // Bind the onMouseOver function - this calls the onHoverIn function 
                $(this).bind("mouseenter",function() {
                	// Bind the onHoverIn Function to the anchor
                	jQuery.newsreader.onHoverIn(index, newsreaderIndex);  
                });                
                // Bind the onMouseOut function - this calls the onHoverOut function
                $(this).bind("mouseleave",function() {
                	// Bind the onHoverOut Function to the anchor                	
                	jQuery.newsreader.onHoverOut(index, newsreaderIndex); 
                });                
            });	
        }		
		        
        /* 
         * FUNCTION onHoverIn - This pauses the looping of the UL and changes the
         * selected item to the one the mouse is hovering if the changeOnHover flag
         * is set in the default Properties.
         * 
         * Parameters:
         * index: The index of the thumbnails
         * nrInd: The newsreader index
         * 
         * * START * */
                
        $.newsreader.onHoverIn = function (index, nrInd) {
        	// Stop the newsreader from changes items when the user hovers over a thumbnail
        	$.newsreader.pauseNewsreader(nrInd);            
            // Changes the item to currently hovered thumbnail

			if(s.transition.command){ //If a transition is required when hovering on thumbs
				$.newsreader.changeItemWithTransition(newsreaders[nrInd].position,index,newsreaders[nrInd].count, nrInd);                  				
			}else{
				$.newsreader.changeItem(newsreaders[nrInd].position,index,newsreaders[nrInd].count, nrInd);                  
			}
			
        };
        
        /* END */         
        
        /* 
         * FUNCTION onHoverOut - This restarts the looping of the UL and changes the
         * selected item to the one the mouse has hovered away from one of the thumbnail
         * 
         * Parameters:
         * index: The index of the thumbnails you are hovering away from
         * nrIndex: The newsreader index
         * 
         * START */
        
        $.newsreader.onHoverOut = function (index,nrIndex) {        	
        	// Pauses the newsreader
			$.newsreader.pauseNewsreader(nrIndex);			
			// Set the position of the newreader to that of the last hovered thumbnail
            newsreaders[nrIndex].position = index;            
            // Starts the newsreader
			$.newsreader.startNewsreader(nrIndex);			
        };
        
        /* END */
        
        /* 
         * FUNCTION pauseNewsreader - stops the newsreader from rotating through the UL  
         *  
         * Parameters:
         * nrIndex: Newsreader Index
         * 
         * START */   
        
		$.newsreader.pauseNewsreader = function (nrIndex) {			
			// Clear the setInterval, this stops the newsreader from changing from one Li to another
			clearInterval(changeItemsInterval[nrIndex]);			
		};

        /* END */
		
        /* 
         * FUNCTION startNewsreader - starts the newsreader rotating through the UL one LI at a time
         * 
         * Parameters:
         * nrIndex: Newsreader index 
         *  
         * START */   
        		
		$.newsreader.startNewsreader = function(nrIndex){
			// set interval to call the function changeItem
			changeItemsInterval[nrIndex] = setInterval(function(){
				// Call the changeItem function in the set internal
				if (s.transition.loop){
				$.newsreader.changeItemWithTransition(
						newsreaders[nrIndex].position, // The current show Item in the LI
						newsreaders[nrIndex].position + 1, // The next item to show, so plus 1 in the index
						newsreaders[nrIndex].count, // The items in the newsreader
						nrIndex); // The newsreader Index (for multiple newreaders)					
				}else{
				$.newsreader.changeItem(
						newsreaders[nrIndex].position, // The current show Item in the LI
						newsreaders[nrIndex].position + 1, // The next item to show, so plus 1 in the index
						newsreaders[nrIndex].count, // The items in the newsreader
						nrIndex); // The newsreader Index (for multiple newreaders)
				}
			}
			// Set the speed to change from item to item
			, s.speed * 1000);
		};
		
        /* END */
		
        /* 
         * FUNCTION changeItem - Change one LI to another 
         * 
         * Parameters:
         * changeFrom: The current active LI in the current newsreader
         * changeTo: The new LI to change to in the current newsreader
         * itemCount: The count of items in the LI in the current newsreader
         * nrIndex: Newsreader index
         *   
         * START */  
		
		$.newsreader.changeItem = function(changeFrom,changeTo,itemCount,nrIndex) {
        	
        	// Hide all the li of the newsreader
			$("#" + newsreaders[nrIndex].newsreader.id).children().each(function(){
                $(this).hide();
            });
			
			// Remove the 'active' class of the currently selected item 
			$($("#" + newsreaders[nrIndex].thumbnails.id).children()[changeFrom]).removeClass("active");
			$($("#" + newsreaders[nrIndex].pagination.id).children()[changeFrom]).removeClass("active");

			// Work out if the the loop has reached the end, if so restart the index to 0
			if ((changeFrom >= itemCount) && (changeTo > changeFrom)) {
				changeTo = 0;
			}
			
			// Show the next li
			$($("#" + newsreaders[nrIndex].newsreader.id).children()[changeTo]).show();
			
			// Add the 'active' class to the new item thumb and page
			$($("#" + newsreaders[nrIndex].thumbnails.id).children()[changeTo]).addClass("active");
			$($("#" + newsreaders[nrIndex].pagination.id).children()[changeTo]).addClass("active");

			
			// Set the position of the newsreader to the item that it has changed to
			newsreaders[nrIndex].position = changeTo;
        };
		
        /* END */
		
        /* 
         * FUNCTION changeItemWithTransition  - Change one LI to another with a transition effect 
         * 
         * Parameters:
         * changeFrom: The current active LI in the current newsreader
         * changeTo: The new LI to change to in the current newsreader
         * itemCount: The count of items in the LI in the current newsreader
         * nrIndex: Newsreader index
         *   
         * START */  		
		$.newsreader.changeItemWithTransition = function(changeFrom,changeTo,itemCount,nrIndex) {
        	if (changeFrom != changeTo) { //dubble checks if we are not on the same palce
				// FadeOut the IMG
				$($("#" + newsreaders[nrIndex].newsreader.id).children()[changeFrom]).children().children("img").animate({
					opacity: '0'
				}, 200, function(){
					// When it's done, hides all the li of the newsreader
					$("#" + newsreaders[nrIndex].newsreader.id).children().each(function(){
						$(this).hide();
						$(this).removeClass('active');
					});
					//Hides the next image and put backs the old one, without none to notice it
					$($("#" + newsreaders[nrIndex].newsreader.id).children()[changeTo]).children().children("img").css("opacity", "0");
					$(this).css("opacity", "1");
					// Remove the 'active' class of the currently selected item 
					$("#" + newsreaders[nrIndex].pagination.id).children([changeFrom]).removeClass("active");
					$("#" + newsreaders[nrIndex].thumbnails.id).children([changeFrom]).removeClass("active");
					// Work out if the the loop has reached the end, if so restart the index to 0
					if ((changeFrom >= itemCount) && (changeTo > changeFrom)) {
						changeTo = 0;
					}			
					// Show the next li
					$($("#" + newsreaders[nrIndex].newsreader.id).children()[changeTo]).show();
					// I kept the two events separated, it seems to work better
					$($("#" + newsreaders[nrIndex].newsreader.id).children()[changeTo]).show().children().children("img").animate({
						opacity: '1'
					}, 200, function(){
					// When it's done, hides all the li of the newsreader
			//			$("#" + newsreaders[nrIndex].newsreader.id).children().each(function(){
						//	$(this).children().children(".newsImg").css("opacity", "1");
			//			});
					});
					// Add the 'active' classes
					$($("#" + newsreaders[nrIndex].newsreader.id).children()[changeTo]).addClass("active");
					$($("#" + newsreaders[nrIndex].thumbnails.id).children()[changeTo]).addClass("active");
					$($("#" + newsreaders[nrIndex].pagination.id).children()[changeTo]).addClass("active");
					// Set the position of the newsreader to the item that it has changed to
					newsreaders[nrIndex].position = changeTo;
				});
			}
			  };    
        /* END */
            
        /* 
         * FUNCTION next - just goes to the next item
         */        
        $.newsreader.next = function () {
            // If it is not the last item
            if (newsreaders[newsreaderIndex].position !== count) {
                // Pauses the newsreader
			    $.newsreader.pauseNewsreader(newsreaderIndex);	
                // Moves the next item
				if(s.transition.buttons){
					$.newsreader.changeItemWithTransition(newsreaders[newsreaderIndex].position,newsreaders[newsreaderIndex].position +1,count,newsreaderIndex);
				}else{
					$.newsreader.changeItem(newsreaders[newsreaderIndex].position,newsreaders[newsreaderIndex].position +1,count,newsreaderIndex);
				}
                // Starts the newsreader again
			    $.newsreader.startNewsreader(newsreaderIndex);	
		    }
		};
		/* END */
		 
		/* 
         * FUNCTION prev - just goes to the prev item
         */
		$.newsreader.prev = function () {
		      // If it is not the first item
		      if (newsreaders[newsreaderIndex].position !== 0) {
		        // Pauses the newsreader
			    $.newsreader.pauseNewsreader(newsreaderIndex);	
			    // Moves to the prev item
				if (s.transition.buttons) {
					$.newsreader.changeItemWithTransition(newsreaders[newsreaderIndex].position, newsreaders[newsreaderIndex].position - 1, count, newsreaderIndex);				
				}
				else {
					$.newsreader.changeItem(newsreaders[newsreaderIndex].position, newsreaders[newsreaderIndex].position - 1, count, newsreaderIndex);
				}
				// Starts the newsreader again
			    $.newsreader.startNewsreader(newsreaderIndex);	
		      }
		};
         /* END */
        
        // Check if next and prev buttons should be created
		if(s.display.navigation) {
			$('<a>Next</a>').insertAfter('#' + newsreaders[newsreaderIndex].newsreader.id).attr({'id':'nreaderNext','class':'nreaderButton', 'href':'#'}).bind("click",function() {
                	$.newsreader.next(); 
					return false;;
			});
			$('<a>Prev</a>').insertAfter("#" + newsreaders[newsreaderIndex].newsreader.id).attr({'id':'nreaderPrev','class':'nreaderButton', 'href':'#'}).bind("click",function() {
					$.newsreader.prev();
					return false;;
			});
		} 
        
        /*
         * Initialise the newsreader
         * 
         */ 
        
        // Hide all the li items apart the starting position
        $(e).children().each(function(i){
            if(i!=s.start) {
                $(this).hide();
            }
        });
        
        // Starts the newsreader
		$nr.startNewsreader(newsreaderIndex);
		
        /* END */
		
    };
    
    // Create shortcut for internal use
    var $nr = $.newsreader;
    
})(jQuery);


// TODO: remove / refactor #1

/* 
 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.pauseNewsreader(index);
	$("#" + ulId + "_flashContainer_" + clipId).show();
	flashVars.clipId = clipId;
	swfobject.embedSWF("/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.startNewsreader(index);
		$(this).unbind();
	}, function(){});
	
	return false;
}
