glow.ready(function() {

	var $ = glow.dom.get;
	
	createTabbedLists(".li-tabbed");
	createCarousels(".li-carousel");
	createPopups("#blq-main a");


	function createTabbedLists(selector) {

	    var self; 
	        
	    // Process each tabbed list
	    $(selector).each(function() {
	        
	        self = this;
	        
	       	// Add a class to indicate JS modification
			$(self).addClass("js-tabbed");
	    
	        var currentTabList = $($(this).get("ul").item(0));
	        var currentTabNode = currentTabList.parent();
	        var activeClass="li-selected";
	        var currentActiveTab = 0;
	        var i = 0;    
	
	        this.currentTabList = currentTabList;
	        this.currentTabNode = currentTabNode;
	        this.currentActiveTab = currentActiveTab;
	        this.tabCount = currentTabList.get("> li").length;
	        
	        // Add hook to tabbed content
	        currentTabList.addClass("tabs-content");	        
	
	        // Create Nav
	        currentTabNode.append(
	            '<ul class="tabs-nav"></ul>'
	        );
	        var currentTabNav = currentTabNode.get(".tabs-nav");
	
		    currentTabList.get("> li").each(function(i) {
	            var tabTitleNode = glow.dom.get(glow.dom.get(this).get(".title").item(0));
	            currentTabNav.append(
	                '<li class="tab tab-' + (i+1) + '"><span class="title">' + tabTitleNode.html() + '</span></li>'
	            );
	            glow.dom.get(tabTitleNode).remove();
	        });
	
	        // Add .first to first item in Nav and Content
	        currentTabNode.get(".tab-1").addClass("first");
	        
	        // Attach events to nav
	        currentTabNode.get(".tabs-nav li").each(function(i) {
	            glow.events.addListener(this, 'click', function() {
	                activateTab(i);
	                self.rotate = false;
	                return false;
	            });
	        });      
	        
	        // Activate the first tab
	        activateTab(0);        
	
	    });    
	    
	    
	    function activateTab(tabIndex) {
	    
	        var tabNode = self.currentTabNode.get(".tabs-content");
	        var fadeSpeed = 1;
	        var allTabs = self.currentTabList.get('> li');
	        var showTab = self.currentTabList.get('> li').item(tabIndex);
	        
	        $(self.currentTabNode.get(".tabs-content > li, .tabs-nav > li")).removeClass('li-selected');
	        $(self.currentTabNode.get(".tabs-content > li").item(tabIndex)).addClass('li-selected');
	        $(self.currentTabNode.get(".tabs-nav > li").item(tabIndex)).addClass('li-selected');
	        self.currentActiveTab = tabIndex;    
	    
	    }
    }
    
    
    function prepareCarousel(carousel, visible, size) {
    	
	    // Process each .li-carousel 
	    $(carousel).each(function() {         	
    	
  			// Sort items in carousel into descending order by timestamp ('freshness')
  			var allItems = $($(this).get(".li-carousel-list > li"));			
  			var sortOrder = allItems.sort(function(a, b) {
  				return ((getTimestamp(a)) < (getTimestamp(b))) ? 1 : -1;				
  			});  			  		  	
  		  	var allItemsSorted = sortOrder.clone();  	
  		  		
			// Delete .updated
  			allItemsSorted.get(".updated").destroy();  		
  		 			
  			// Delete the current list content
  			$($(this).get(allItems)).destroy();  	
  			
  			//  Populate list with the sorted items  			
  			$($(this).get("ul")).append(allItemsSorted);  	
  			
  			// Regrab the items in the list
  			allItems = $($(this).get(".li-carousel-list > li"));		  			
  			  			  			  			  		
  			// Adjust number of items so is exactly divisible by visible
  			var totalItems = allItems.length;  			
  			if (totalItems % visible) {
  				var maxPages = Math.floor(totalItems / visible);  
  				// Calculate the maximum number of items the list can contain	
  				var maxItems = 0;			
  				if (maxPages > 1) {  				
  					// Enough items for more than one page	
					maxItems = maxPages * visible; 								  					
  				} else {
  					// Only enough items for a single page
  					maxItems = size; 					
  				}	  	
				allItems.each(function(i) {
	  				if (i > (maxItems - 1)) {
	  					// Delete surplus item
	  					$(this).destroy();
	  				}
	  			});  
  			}			
  			// Regrab the items in the list
  			allItems = $($(this).get(".li-carousel-list > li"));		
			
			// Recount total number of items in list
			totalItems = allItems.length;
   		  	
   		  	// Recalculate total number of pages					
  			maxPages = Math.floor(totalItems / visible);
  			this.pages = maxPages;
  			
  			if (maxPages > 1) {
	  			// Move the last item to first position as first item will be semi-obscured  						
	  			var lastItem = $(allItems).item(totalItems-1);
	  			var lastItemClone = $(lastItem).clone(true);
	  			$(lastItem).destroy();
	  			$(allItems.item(0)).before(lastItemClone); 
	  			
	  			// Regrab the items in the list
	  			allItems = $($(this).get(".li-carousel-list > li"));   
  			}
  			
  			
  			// Delete .first	
  			$(allItems.parent()).get(".first").removeClass("first");

  		});
  		
	    function getTimestamp(listItem) {
	  		var timestampElement = $($(listItem).get(".updated .timestamp")).item(0);  		
	  		var originalTimestamp = (timestampElement.innerText || timestampElement.textContent);
	  		var formattedTimestamp = originalTimestamp.substring(0,4).concat(originalTimestamp.substring(5,7),originalTimestamp.substring(8,10),originalTimestamp.substring(11,13),originalTimestamp.substring(14,16),originalTimestamp.substring(17,19));  				
	  		return formattedTimestamp;
	    }  		
    }
 

    
    function createCarousels(selector) {
    
    	var self;     	  	    
    	    	
	    // Process each .li-carousel 
	    $(selector).each(function() { 
	    
  			self = this;	
  			var size = 5;
  			var step = 3;
  			var obscured = 2;
  			
			prepareCarousel(this, (size - obscured), size);  
			
			if (this.pages > 1) { 			
  			  				      	
		      	// Create a new Glow carousel widget			
				var carousel = new glow.widgets.Carousel($($(this).get("> .content > ul")), {
					loop: true,
					size: size,
					step: step				
				});								  			
			
				// Add a class to indicate JS modification
				$(self).addClass("js-carousel");
				
				// Fetch all items in the carousel
				var allItems = $($(this).get(".li-carousel-list > li"));
				
				// Count the items in the carousel						    	    	
		    	var totalItems = allItems.length; 	    		    		    	
		    	var realItems = allItems.filter(function(i) {return $(this).hasClass("carousel-added") != true;});
		    	var totalRealItems = realItems.length;
		    	
		    	// Calculate the number of pages in the carousel    	   	
		    	var totalPages = Math.ceil(totalRealItems / carousel.visibleItems().length);    	
		 		
		 		// Add custom page navigation
		 		$($(this).get(".carousel-window")).parent().append(
		            '<ul class="pageNav" style="width: ' + (totalPages * 20) + 'px;"></ul>'
		        );
		 		var pageNav = $($(this).get(".pageNav"));	 			 			
				for(var i = 0; i < totalPages; i++){
					var currPage = i + 1;
					pageNav.append(
						'<li class="dot dot' + currPage + '"><a class="dotLabel" href="#">' + currPage + '</a></li>'
					);
				}	     					
				
				// Add a hook to the first item in the page navigation
		 		$(pageNav.get(".dot").item(0)).addClass('dotActive');
		 		
		 		// Add a hook to the first item in the carousel	 		
		 		$(realItems.item(0)).addClass('itemActive');
		 					 							 				
		 		this.currentNavNode = pageNav;
		 		this.currentCarousel = carousel;
		 		this.visible = carousel._opts.size;
		 		this.step = carousel._opts.step;		 	
		 		this.currentCarouselRealItems = realItems; 
		 		this.totalPages = totalPages;
		 				
		        // Attach events to carousel controls
		        $($(this).get(".carousel-nav")).each(function(i) {
		            glow.events.addListener(this, 'click', function() {	            	         
		                moveItemActive(this);
		                showPage();
		                return false;
		            });
		        });  
		        
		        // Attach events to page navigation
		        pageNav.get("li").each(function(i) {
		            glow.events.addListener(this, 'click', function() {
		                turnPage(i);
		                return false;
		            });
		        }); 
			} else {
				// Not enough pages for a carousel
				$(self).addClass("li-carousel-disabled");
			}
			
		});      	
		
		
	    function turnPage(requestedPageIndex) {		    
	    
	    	// Work out which page the carousel is currently showing	    	  		    	
	    	var currentPageIndex = getCurrentPageIndex();	    	    	
	    	var currentPageNode = $($(self.currentNavNode).children().item(currentPageIndex));		    		    
	    	
	    	// If the requested page isn't the current page, 
	    	// scroll the carousel to show the requested page		    	    			    
	    	if (requestedPageIndex != currentPageIndex) {
	    		
	    		var firstItemOnRequestedPage = ((self.visible -1) * requestedPageIndex);  		
	    		var allItems = currentPageNode.parent().get(".carousel-window li.carousel-item");
	    		self.currentCarousel.moveTo(firstItemOnRequestedPage,true);	    							    		
	    		
	    		// Update page navigation to show new page
				showPage(requestedPageIndex);
				
				// Move .itemActive
	    		moveItemActive(self.currentNavNode, firstItemOnRequestedPage);
	    					
	    	}	    
	    		    		  
	    }    	    	   
	    
	    
	    function moveItemActive(currentNavOptionNode, newItemActiveIndex) {	    
	    	
			var realItems = self.currentCarouselRealItems;
    		
			// Find the item that's currently active
    		var currentItemActiveIndex;	    		
    		realItems.each(function(i){	    				    		
    			if ($(this).hasClass("itemActive")) {	    				    				
    				currentItemActiveIndex = i;
    			}
    		});
	    	
	    	// If the index for the new active item hasn't been provided,
	    	// work it out
	    	if (!(newItemActiveIndex >= 0)) {
	    	   	   		    	
		    	// Calculate movement required	       	
		       	var movement;
		       	if ($(currentNavOptionNode).hasClass("carousel-next")) {
		       		movement = self.step; 
		       	} else if ($(currentNavOptionNode).hasClass("carousel-prev")) {
		       		movement = (self.step * -1);
		       	} else {
		       		movement = 0;
		       	}	    	
	    	
				// Calculate where to move the hook to	    	
		    	if (movement != 0) {		    									
					newItemActiveIndex = currentItemActiveIndex + movement;	    				    								
				}
			}
			
			// Adjust for reaching either end of the list
			if (newItemActiveIndex < 0) {
				newItemActiveIndex = realItems.length + newItemActiveIndex;
			} else if (newItemActiveIndex >= realItems.length) {
				newItemActiveIndex = newItemActiveIndex - realItems.length;
			}								    			
			
			if (currentItemActiveIndex != newItemActiveIndex) {
				// remove hook from currently active item
				$(realItems.item(currentItemActiveIndex)).removeClass("itemActive");
				
				// add hook to new active item
				$(realItems.item(newItemActiveIndex)).addClass("itemActive");
			}	    	
	    	   	
	    }        	
	    
	    
	    function showPage(newPageIndex) {	   	    
	    
	    	// If the index for the new page hasn't been provided,
	    	// work it out
	    	if (!(newPageIndex >= 0)) {
	    	
				var realItems = self.currentCarouselRealItems;
    		
				// Find the item that's currently active
	    		var currentItemActiveIndex;	    		
	    		realItems.each(function(i){	    				    		
	    			if ($(this).hasClass("itemActive")) {	    				    				
	    				currentItemActiveIndex = i;
	    			}
	    		});	    	    		  	
	    		
	    		var newPageIndex = Math.ceil(currentItemActiveIndex / self.visible);   	   	    		
	    	}	    	     

			// Update the navigation to show new page as current page
    		var currentPageNode = $(self.currentNavNode.get(".dotActive"));
    		currentPageNode.removeClass("dotActive");
    		var requestedPageNode = $(self.currentNavNode.children().item(newPageIndex));
    		requestedPageNode.addClass("dotActive");
	    }
	    
	    function getCurrentPageIndex() {
	    
	    	// Work out which page the carousel is currently showing	    	
	    	var currentPageNode = $(self.currentNavNode.get(".dotActive"));	    	
	    	
	    	var currentPageIndex;
	    	for (currentPageIndex = 0; currentPageIndex <= self.currentNavNode.children().length; ++currentPageIndex) {	    			    		
	    		
	    		var currentNode = $(self.currentNavNode).children().item(currentPageIndex);	    						
				if ($(currentNode).hasClass("dotActive")) {
	    			break;
	    		}	    			    		
	    	}	    
	    	
	    	return currentPageIndex;
	    }
	}
	
  	function createPopups(selector) {
		$(selector).filter(function(e){                    
			if (this.className.match('popup')) {
				var popupOptions = this.className.match(/([0-9]+)x([0-9]+)/i);
				var popupUrl = this.href;                    
				if (this.className.match('-scrolling')) { 
					popupOptions[3] = 'yes'; 
				} else { 
					popupOptions[3] = 'no'; 
				}
				glow.events.addListener(glow.dom.get(this), 'click', function(){ 
					var popupWin = null;
					if(!popupWin) { 
						popupWin=window.open(popupUrl,'popup','width='+parseInt(popupOptions[1])+',height='+parseInt(popupOptions[2])+',scrollbars='+popupOptions[3]+',toolbar=no,personalbar=no,location=no,directories=no,statusbar=no,menubar=no,resizable=yes,status=no,left=60,screenX=60,top=100,screenY=100');
					} else { 
						popupWin.focus(); 
					}
					return false;                
				})
			}
		});
	}

});  
