/* ########################################################################### *
/* ***** ECLIPSE GROUP  ****************************************************** *
/* ########################################################################### *
 * ##### DOCUMENT NAME:  custom.js
 * ##### DOCUMENT INFO: 
 * ##### Original v1.0: 15/11/07 (Eclipse Group)
/* ########################################################################### *

/* ########################################################################### *
/* ***** INDEX *************************************************************** *
/* ########################################################################### *
/* ##### INITIALISATION
/* ########################################################################### */

/* ########################################################################### *
/* ##### INITIALISATION
/* ########################################################################### */

$(".heroFeature").ready(init_heroFeature);
$(document).ready(init_global);
$(window).load(init_globalLoaded);
$(window).unload(init_globalUnload);

function init_global()
{
	// Typography
	ecl_init_typography();

	// Email & Print links
	ecl_emailAndPrint();
	
	// Newsletters form
	if ($('.ecl_newsletter_02').length > 0)
	{
		ecl_init_subscribe();
	}
	
	// Pagination
	if ($('.ecl_setUpPagination').length > 0)
	{
		ecl_setUpPagination();
	}
	
	// Table filtering
	if ($('.ecl_init_filtering').length > 0)
	{
		ecl_init_filtering();
	}
	
	// Table header row
	if ($('table').length > 0)
	{
		ecl_init_tableHeaders();
	}

	// Miscellaneous Global Scripts
	ecl_init_anchorSmoothScroll();		// Smooth scroll to in page anchors
	ecl_lists();						// Lists
	
}


function init_globalLoaded()
{
	// Rounded Corners
	ecl_init_corners();
	
	// Home page content
	init_homePage();
}


// Fired when the page unloads
function init_globalUnload()
{

}




////////////////////////////////////
// MISCELLANEOUS GLOBAL SCRIPTS
////////////////////////////////////

// Smooth scroll to in page anchors
function ecl_init_anchorSmoothScroll()
{
	// Enable only if browser is NOT ie
	if (jQuery.browser.msie == false)
	{
		var nodes = $('a[href*=#]');
		for(var i = 0; i < nodes.length; i++) 
		{
			if ($(nodes[i]).attr("href") != "#")
			{
				$(nodes[i]).click(function() 
				{
					if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'')
					&& location.hostname == this.hostname) {
						var $target = $(this.hash);
						$target = $target.length && $target
						|| $('[name=' + this.hash.slice(1) +']');
						if ($target.length) {
						var targetOffset = $target.offset().top;
						$('html,body')
						.animate({scrollTop: targetOffset}, 1000);
						 return false;
						}
					}
				});
			}
		}
	}
}

// LISTS 
function ecl_lists()
{
	$('ul li:first-child').each(function(){
		$(this).addClass("first");
	});
	$('ul li:last-child').each(function(){
		$(this).addClass("last");
	});
}


// CONTENT GRAPHIC GRID ALIGNMENT
// NB: Not functional
function ecl_contentGraphicsGridAlignment()
{
	var imageNodes = $('.content img');
	for (var i = 0; i < imageNodes.length; i++)
	{
		var imageHeight = $(imageNodes[i]).height();
		var mod = imageHeight % 18; // 18 is the number of pixels per line (ie. lineheight as px)
		if (mod != 0)
		{
			// set the new height imageHeight(mod);	
			var newHeight = imageHeight - mod;
			$(imageHeight[i]).height(newHeight);
		}
	}
}




//////////////////
// HERO FEATURE
//////////////////
// DEV NOTES: 
// #1. To hide a hero banner on load, the class 'hidden' should be added to the .heroContent div
//////////////////

function init_heroFeature()
{
	// Hero Feature Functionality
	ecl_heroFeature();
}

function ecl_heroFeature()
{
	// Hero flash link and image
	$("#heroFeatureFlashContainer").hover(ecl_heroFeature_flashHover, ecl_heroFeature_flashHover);
	if ($("#heroFeatureFlashContainer #heroFeatureFlash").length > 0)
	{
		$(".heroFeatureFlashAlt").hide();
	}
	
	// Hero hide / expand link
	// If the expand / collapse link exists then add all functionality
	if ($(".heroFeature .divider a").length > 0)
	{
		$(".heroFeature .divider a").attr("href", "javascript: return false;");
		$(".heroFeature .divider").click(ecl_expandCollapseHero);
		$(".heroFeature .divider").hover(hoverOver, hoverOut);
		
		// Collapse the banner if the hero feature has "hidden" class applied
		if ($(".heroFeature .heroContent").hasClass("hidden"))
		{
			$('.heroFeature').addClass('collapsed');
		}
		
		// If has class collapsed (nb: removed the cookie functionality 190207)
		// Hide banner if the cookie is set (#1 & #2)
		// if (($.cookie('ecl_sv_heroBannerIsHidden') == "true") || $('.heroFeature').hasClass('collapsed'))
		if ($('.heroFeature').hasClass('collapsed'))
		{
			$(".heroContent").hide();
			// Add the classes to let everything know it's been toggled.
			$(".heroFeature .divider").find("a").addClass("collapsed");
			$(".heroFeature .divider").find("a").html("Expand");
			$.cookie('ecl_sv_heroBannerIsHidden', 'true');
		} else {
			$(".heroContent").show();
		}
	}
	// Remove dummy classes from hero to enable visibility	
	$(".heroFeature .heroContent").removeClass("hidden");
}

/// Pass true in to cause instant toggle, or pass false (or leave blank) for slide toggle.
/// Will still perform teh toggle in IE because it doens't behave well.
function ecl_expandCollapseHero(event, instantToggle)
{	

	// Handle the default method call - which has no parameters supplied.
	if (typeof instantToggle == "undefined" || instantToggle == null) 
	{
		instantToggle = false;
	}
	
	if (instantToggle)
	{
	  $(".heroFeature .heroContent").toggle();
	}
	else
	{
		jQuery.browser.msie ? $(".heroFeature .heroContent").toggle() : $(".heroFeature .heroContent").slideToggle("fast");
	}
	
	// Add the classes to let everything know it's been toggled.
	$(this).find("a").toggleClass("collapsed");
	
	if ($(this).find("a").hasClass("collapsed"))
	{
		$(this).find("a").html("Expand");
		$.cookie('ecl_sv_heroBannerIsHidden', 'true');
	} else {
		$(this).find("a").html("Hide");
		$.cookie('ecl_sv_heroBannerIsHidden', 'false');		
	}
	return false;
}

function ecl_heroFeature_flashHover()
{
	
}






//////////////////
// HOMEPAGE
//////////////////

function init_homePage()
{
	if ($(".homePage").length > 0) 
	{
		init_homePageWhereStart();
	}
}

function init_homePageWhereStart()
{
	// Check if the markup indicates which segment should be visible, if not, make home visible
	if ($(".homePage .ecl_segmentListExpandoCollapso li.active").length == 0)
	{
		$(".homePage .ecl_segmentListExpandoCollapso li:first").addClass("active");
	}
	
	$(".homePage .ecl_segmentListExpandoCollapso li.segment .articles").hide();
	$(".homePage .ecl_segmentListExpandoCollapso li.active .articles").show();
	$(".homePage .ecl_segmentListExpandoCollapso li.segment").hover(hoverOver, hoverOut);
	$(".homePage .ecl_segmentListExpandoCollapso li.segment h2").click(ecl_segmentListExpandoCollapso);
	$(".homePage .ecl_segmentListExpandoCollapso li.segment h2 a").attr("href", "javascript:return false;");	
}

function ecl_segmentListExpandoCollapso()
{
	if (!$(this).parent("li").hasClass("active")) 
	{
		$(".homePage .ecl_segmentListExpandoCollapso li.active .articles").slideUp("fast");
		$(".homePage .ecl_segmentListExpandoCollapso li.active").removeClass("active");	
		$(this).parent("li").addClass("active");
		$(this).parent("li").children(".articles").slideDown("normal");
		$(this).parent("li").blur();
	}
	return false;	
}




/////////////////////
// ROUNDED CORNERS //
/////////////////////

function ecl_init_corners()
{
	$('.divider').corner("top");
	$('.content .module').corner();
	$('dl.feedback').corner("");
	$('.footer').corner("bottom");
	$('p.feedback').corner("");
	$('.content .nav-inPageTertiary').corner("");
	

	// Buttons
	var buttonNodes = $('button');
	for (var i = 0; i < buttonNodes.length; i++)
	{
		$(buttonNodes[i]).html($(buttonNodes[i]).html() + "<span></span>");
	}
	
	var buttonNodes = $('a.button');
	for (var i = 0; i < buttonNodes.length; i++)
	{
		var newText = $(buttonNodes[i]).html() + "<span></span>";
		$(buttonNodes[i]).html(newText);
	}


	if ($('.rightColumn .segmentList').length > 0)
	{
		var nodes = $('.rightColumn .segmentList .roundCornersWrap img');
		for (var i = 0; i < nodes.length; i++)
		{
			$(nodes[i]).addClass("roundCorners");
			var contents = $(nodes[i]).parent("a");
			$(contents).before('<div class="roundCornerImage"><div class="corners_2x2"></div>');
			$(contents).after('</div>');
		}
	}
		
	if ($('.content .articleList').length > 0)
	{
		var nodes = $('.content .articleList .roundCornersWrap img');
		for (var i = 0; i < nodes.length; i++)
		{
			$(nodes[i]).addClass("roundCorners");
			var contents = $(nodes[i]).parent("a");
			$(contents).before('<div class="roundCornerImage"><div class="corners_72x72"></div>');
			$(contents).after('</div>');
		}
	}

}



/////////////////////////
// EMAIL & PRINT LINKS //
/////////////////////////

function ecl_emailAndPrint()
{
	if ($(".nav-contentFunctions").length > 0)
	{
		// Add the HTML for the Email & Print buttons
		$(".nav-contentFunctions").html('<ul class="nav-horizontal"><li class="first"><a href="#Email" class="ecl_emailToAFriend">Email</a></li><li class="last"><a href="#Print" class="ecl_print">Print</a></li></ul>');
		
		// Wire the click events for the Email & Print buttons
		$(".nav-contentFunctions .ecl_emailToAFriend").click(ecl_emailToAFriend);
		$(".nav-contentFunctions .ecl_print").click(ecl_print);
		
		// Add the HTML container for the Email a Friend form
		$('.contentLinks').after('<div id="emailPage" class="form-container"></div>');
		
		jQuery.browser.msie ? $("#emailPage").hide() : $("#emailPage").slideUp();
		
		if($(".nav-contentFunctions").length == 2)
		{
			$(".nav-contentFunctions:last a").addClass("secondaryEmailPageLink");
		}
	}
}

function ecl_print()
{
	window.print();
	return false;
}

function ecl_emailToAFriend()
{
	if ($(this).hasClass("secondaryEmailPageLink"))
	{
		window.location.href = "#top";
	}
	
	if ($("#emailPage").hasClass("isVisible") && ($(this).hasClass("secondaryEmailPageLink") == false))
	{
		$("#emailPage").removeClass('isVisible');
		jQuery.browser.msie ? $("#emailPage").hide() : $("#emailPage").slideUp("slow", function() 
			{
				$("#emailPage").empty(); 
			});
	}
	else if ($("#emailPage").hasClass("isVisible") && ($(this).hasClass("secondaryEmailPageLink") == true))
	{
		return false;
	}
	else 
	{
		$("#emailPage").empty(); 
		$("#emailPage").addClass("isVisible");
		$.get(ecl_emailToAFriend_formHtml, function(data){
			
			// Insert the email form HTML into the #emailPage div
			$('#emailPage').append($(data));

			// Add corner to fieldset & buttons
			ecl_init_corners();
			
			// Add button hover events
			ecl_init_buttons("#emailPage");
			
			jQuery.browser.msie ? $("#emailPage").show() : $("#emailPage").slideDown("slow");
			
			$("#emailSubmit").click(function(){
				$('#emailPage #errorPanel').remove();
				$('#emailPage .error').removeClass('error');
				$("#emailPage .error").hide();
				var hasError = false;
				var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
				var errorMessages = "";
				
				var toNameVal = $("#toname").val();
				if(toNameVal == '') {
					errorMessages += '<dd class="listItem emphasis">Recipient\'s name is required.</dd>';
					$("#toname").parents(".formRow").addClass("error");
					hasError = true;
				}
						
				var emailToVal = $("#toemail").val();
				if(emailToVal == '') {
					errorMessages += '<dd class="listItem emphasis">Recipient\'s email address is required.</dd>';
					$("#toemail").parents(".formRow").addClass("error");
					hasError = true;
				} else if(!emailReg.test(emailToVal)) {	
					errorMessages += '<dd class="listItem emphasis">Please review the recipient\'s email address as it appears to be in an incorrect format.</dd>';
					$("#toemail").parents(".formRow").addClass("error");
					hasError = true;
				}
				
				var fromNameVal = $("#yourname").val();
				if(fromNameVal == '') {
					errorMessages += '<dd class="listItem emphasis">Your name is required.</dd>';
					$("#yourname").parents(".formRow").addClass("error");
					hasError = true;
				}
				
				var emailFromVal = $("#youremail").val();
				if(emailFromVal == '') {
					errorMessages += '<dd class="listItem emphasis">Your email address is required.</dd>';
					$("#youremail").parents(".formRow").addClass("error");
					hasError = true;
				} else if(!emailReg.test(emailFromVal)) {	
					errorMessages += '<dd class="listItem emphasis">Please review your email address as it appears to be in an incorrect format.</dd>';
					$("#youremail").parents(".formRow").addClass("error");
					hasError = true;
				}			
								
				var messageVal = $("#emailMessage").val();
				if(messageVal == '') {
					errorMessages += '<dd class="listItem emphasis">A message is required.</dd>';
					$("#emailMessage").parents(".formRow").addClass("error");
					hasError = true;
				}

				if(messageVal.length > 300) {
					errorMessages += '<dd class="listItem emphasis">The message cannot be longer than 300 characters.</dd>';
					$("#emailMessage").parents(".formRow").addClass("error");
					hasError = true;
				}
								
				if(hasError == false) {
					var title = $("title").html();
					var url 	= window.location.href;
					$("#emailPage input").add("#emailPage textarea").attr("disabled", "disabled");
					jQuery.browser.msie ? $("#emailPage .formRowWrapper").hide() : $("#emailPage .formRowWrapper").slideUp();
					ecl_emailToAFriend_loading($(this).parent());
					
					// If in ecl_staticTestMode then do not attempt to send via server side script, instead execute dummy client side test
					if (ecl_staticTestMode)
					{
						setTimeout ( ecl_emailToAFriend_success, 2000 );
					} else {
						$.post(ecl_ajaxUrl_emailToAFriend,
							{ 'emailPageDetails.toName': toNameVal, 'emailPageDetails.toAddress': emailToVal, 'emailPageDetails.fromName': fromNameVal, 'emailPageDetails.fromAddress': emailFromVal, 'emailPageDetails.message': messageVal, 'emailPageDetails.pageTitle':title, 'emailPageDetails.pageUrl':url },
								function(data){
									if (data == "success") {
										ecl_emailToAFriend_success();	
									}
									else {
										ecl_emailToAFriend_fail();
									}									
								}
							 );
					}
				} else {
					// If errors exist show the feedback
					$('#emailPage').prepend('<dl id="errorPanel" class="feedback"><dt><strong>Sorry, the following issues were found. Please correct the information before submitting the form again.</strong></dt>' + errorMessages + '</dl>');
					$('#errorPanel').corner("");
					setTimeout( (function()
																{ 
																	jQuery.scrollTo($(".contentLinks"), 500);
																}), 500);
					return false;
				}
				
				return false;
			});
			$("#emailCancel").click(function(){
				jQuery.browser.msie ? $("#emailPage").hide() : $("#emailPage").slideUp("slow");					 
				$("#emailPage").removeClass('isVisible');
				return false;
			});
		});
	}
	return false;
}

function ecl_emailToAFriend_loading(node)
{
	$(node).empty();
	$('#emailPage legend').after("<p>Sending now, please wait a moment...</p>");
}

function ecl_emailToAFriend_success()
{
	if (jQuery.browser.msie)
	{
		$("#emailPage").hide();
		$("#emailPage").html('<p class="feedback success emphasis">Thank you, your email has been sent.</p>');
		$("#emailPage p").corner("");
		$("#emailPage").show();
		setTimeout(function() 
			{
				$("#emailPage").hide();
				$("#emailPage").removeClass('isVisible');
			}, 3000);
	}
	else
	{
		$("#emailPage").slideUp("normal",function()
				{
					$("#emailPage").html('<p class="feedback success emphasis">Thank you, your email has been sent.</p>');
					$("#emailPage p").corner("");
					$("#emailPage").slideDown("normal",function()
						{
							setTimeout(function() 
								{
									$("#emailPage").slideUp("slow");
									$("#emailPage").removeClass('isVisible');
								}, 3000);
						});
				});
	}
}

function ecl_emailToAFriend_fail()
{
	if (jQuery.browser.msie)
	{
		$("#emailPage").hide();
		$("#emailPage").html('<p class="feedback success emphasis">Unable to send email. Please try again.</p>');
		$("#emailPage p").corner("");
		$("#emailPage").show();
		setTimeout(function() 
			{
				$("#emailPage").hide();
				$("#emailPage").removeClass('isVisible');
			}, 3000);
	}
	else
	{
		$("#emailPage").slideUp("normal",function()
				{
					$("#emailPage").html('<p class="feedback success emphasis">Unable to send email. Please try again.</p>');
					$("#emailPage p").corner("");
					$("#emailPage").slideDown("normal",function()
						{
							setTimeout(function() 
								{
									$("#emailPage").slideUp("slow");
									$("#emailPage").removeClass('isVisible');
								}, 3000);
						});
				});
	}
}



/////////////////////////////////
// SUBSCRIPTION FORM HIDE/SHOW //
/////////////////////////////////

function ecl_init_subscribe()
{
	$(".ecl_newsletter_02 #radSubscribe1").click(function()
		{
			if ($("#radSubscribe2:checked"))
			{
				$(".ecl_newsletter_03").show();
			}
			$('.content .newsletters .module .jquery-corner').remove();
			//alert($('.content .newsletters .module .jquery-corner').length);
			$('.content .newsletters .module').corner();
		});	
	
	$(".ecl_newsletter_02 #radSubscribe2").click(function()
		{
			if ($("#radSubscribe1:checked"))
			{
				$(".ecl_newsletter_03").hide();
			}
			$('.content .newsletters .module .jquery-corner').remove();
			//alert($('.content .newsletters .module .jquery-corner').length);
			$('.content .newsletters .module').corner();			
		});
	
	if ($(".ecl_newsletter_02 #radSubscribe2").attr("checked"))
	{
		$(".ecl_newsletter_03").hide();
	}
}



/////////////////////////////
// TABLE HEADERS //
/////////////////////////////

function ecl_init_tableHeaders()
{
	$('table tr:first').addClass("tableHeaderRow");
}


/////////////////////////////
// TABLE CONTENT FILTERING //
/////////////////////////////


// These consts are shared by FILTERING and PAGING.
var RESULTS_PER_PAGE = 10;
var unfilteredRowSelector = 'table.articleList tbody tr:not(.filtered)';	

function ecl_init_filtering()
{
	// Write the filter fieldset into the markup (nb: gets placed after all fieldsets within .ecl_init_filtering
	$('.ecl_init_filtering fieldset').after('<fieldset class="ecl_filtering_filters"><span class="emphasis">Filter by:</span><input name="energy" id="filter1" value="1" type="checkbox" checked="checked" /> <label for="filter1">Energy</label><input name="waste" id="filter2" value="2" type="checkbox" checked="checked" /> <label for="filter2">Waste &amp; recycling</label><input name="water" id="filter3" value="3" type="checkbox" checked="checked" /> <label for="filter3">Water</label><input name="other" id="filter4" value="4" type="checkbox" checked="checked" /><label for="filter4">Other</label></fieldset>');

	// Wire up the click events.
	$(".filterList input[@type=checkbox]").click(ecl_filteringCheckbox_Click);

	// Execute the filtering method on load to ensure that the paging and the filter options are in sync.
	ecl_filteringCheckbox_Click();
}

function ecl_filteringCheckbox_Click()
{
		var checkedBoxes = $(".filterList input:checked");
		var notcheckedBoxes = $(".filterList input:not(:checked)");
					
		// Hide all rows with unchecked categories
		for (var i = 0; i < notcheckedBoxes.length; i++)
		{
			var category = $(notcheckedBoxes[i]).next("label").text();
			var filterString = ":contains(" + category + ")";
			$(".articleList tbody .articleCategory").filter(filterString).each(function(){
				// adding filtered class.
				$(this).parent().addClass('filtered');
				$(this).parent().hide();					 
			});
		}
		// Show all rows with checked categories
		for (var i = 0; i < checkedBoxes.length; i++)
		{
			var category = $(checkedBoxes[i]).next("label").text();
			var filterString = ":contains(" + category + ")";
			$(".articleList .articleCategory").filter(filterString).each(function(){
				$(this).parent().removeClass('filtered');
				$(this).parent().show();
			});
		}
		
		// We've potentially changed the result set, so update the paging (and results display)	
		ecl_setUpPagination();
		
		// Cater for no results by hiding table + paging and displaying the 0 results paragraph.
		if ($(unfilteredRowSelector).length > 0)
		{
			// show the table etc.
			$('div.pagination').show();
			$('table.articleList').show();
			$('p.noResultsToShow').remove();
		}
		else
		{
			// hide the table etc.
			$('div.pagination').hide();
			$('table.articleList').hide();
			if ($(".noResultsToShow").length < 1) {
				$("table.articleList").after('<p class="noResultsToShow success feedback emphasis">Sorry, there are no results matching your current filter settings.</p>');
			}
			$('p.noResultsToShow').corner();	
		}
}





//////////////////////////////////////////
/// Table paging for Publications page ///
//////////////////////////////////////////
			
function ecl_setUpPagination(currentPage)
{	
	// Support table or form list by changing the jQuery filter string
	if ($('ul.ecl_setUpPagination').length > 0)
	{
		// If there are no articles hide pagination & sorting
		if ($('ul.ecl_setUpPagination li').length < 1)
		{
			$(".content .pagination:first").after('<p class="noResultsToShow success feedback emphasis">Sorry, there are currently no articles in this section.</p>');
			$('.pagination').hide();
			$('.sortOrder').hide();
			$('ul.ecl_setUpPagination ').hide();
			return false;
		}
					
		unfilteredRowSelector = '.ecl_setUpPagination li:not(.filtered)';
	} else if ($('table.ecl_setUpPagination').length > 0) {
		unfilteredRowSelector = 'table.articleList tbody tr:not(.filtered)';	
	} else {
		unfilteredRowSelector = 'table.articleList tbody tr:not(.filtered)';
	}


	// Handle the default method call - which has no parameters supplied.
	if (typeof currentPage == "undefined" || currentPage == null) 
	{
		currentPage = 1;
	}
	
	// Get the unfiltered rows and calculate the item & page count.
	var unfilteredItemCollection = $(unfilteredRowSelector);
	var unfilteredItemCount = $(unfilteredItemCollection).length;
	var pagesNeeded = Math.ceil(unfilteredItemCount / RESULTS_PER_PAGE);
		
	// Determine the leftBoundary and rightBoundary to the paged section of items.
	var leftBound = (currentPage - 1) * RESULTS_PER_PAGE;
	var rightBound = leftBound + RESULTS_PER_PAGE - 1; // - 1 for greater than (not equal to).
	// Create a collection of all items to the left and right of the paged section.
	var leftCollection = $(unfilteredItemCollection).filter(':lt(' + leftBound + ')').log('leftCollection');
	var rightCollection = $(unfilteredItemCollection).filter(':gt(' + rightBound + ')').log('rightCollection');

	// Generate and apply the paging HTML to the placeholder div. 
	var pagingHTML = generatePagingHTML(pagesNeeded, currentPage);			
	$('div.nav-pagination ul.nav-horizontal').log('writing pagingHTML to each of the paging ul').each(function () {
		$(this)[0].innerHTML = pagingHTML;
	});
	
	// Wire up the paging link event handlers (ensuring previous/next don't get the numeric link handler too).				
	$('div.nav-pagination ul.nav-horizontal li:not(.previous):not(.next) a').log('numeric link items').click(pagingLink_click);	
	$('div.nav-pagination ul.nav-horizontal li.previous a').log('previous link item').click(previousLink_click);
	$('div.nav-pagination ul.nav-horizontal li.next a').log('next link item').click(nextLink_click);
	
	// Set the visibility of the itemCollections.
	var currentPageItems = $(unfilteredItemCollection).not(leftCollection).not(rightCollection).log('items to be shown').show();							
	$(unfilteredItemCollection).not(currentPageItems).log('items to be hidden').hide();
	
	// Setup (update) the paging / filter results.
	setUpResults();	

	return false;		
}

var PAGING_LINKS = 5; // Number of links in the paging. (MUST BE AN ODD NUMBER)

function generatePagingHTML(pagesNeeded, currentPage)
{
	// Variables used to build the paging HTML - the % is replaced with the current loop index (page number).
	var pagingLinkHTML = '<li><a href="#">%</a></li>';
	var currentLinkHTML = '<li><span>%</span></li>';
	var pagingHTML = ""; var htmlLine = "";

	// Generate paging if there is at least 2 pages
	if (pagesNeeded >= 2) 
	{

		// Add link html / the span html depending on if the current page is the first / or there is only 1 page needed. 
		htmlLine = (pagesNeeded <= 1 || currentPage == 1 ? '' : '<li class="previous"><a href="#">Previous</a></li>');
		pagingHTML += htmlLine;
	
		var startIndex = 1;                     
		if (pagesNeeded > PAGING_LINKS)
		{
			// We have more paging links than we want to show
			// Ideally, the currentLink will be in the center.
			// (However, if the currentLink is toward the end of the pagesNeeded
			//  it will end up being closer to the rightSide - that is...
			//  the itemsOnLeft will need to make up for the lack of itemsOnRightSide)
			var desiredItemsEitherSide = Math.floor(PAGING_LINKS / 2);
															
			if (currentPage <= desiredItemsEitherSide)
			{
				// This is the case that the span is closer to the left side...
				startIndex = 1;
			}
			else
			{                                   
				if (currentPage > (pagesNeeded - desiredItemsEitherSide))
				{
					// This is the case that the span is closer to the right side...
					var itemsOnRightSide = pagesNeeded - currentPage;
					var itemsOnLeftSide = desiredItemsEitherSide + (desiredItemsEitherSide - itemsOnRightSide);                   
					startIndex = currentPage - itemsOnLeftSide;
				}
				else
				{
					// This is the case that the span is in the middle...
					startIndex = currentPage - desiredItemsEitherSide;
				}
			}                       
		}
		
		// If that lastPageIndex would push beyond the desired amount - revert to the pagesNeeded amount.
		var lastPageIndex = startIndex + PAGING_LINKS - 1; // This -1 is needed because the loop starts at the number of the link.
		if (lastPageIndex > pagesNeeded) 
		{
			lastPageIndex = pagesNeeded;
		} 
		for (var i = startIndex; i <= lastPageIndex; i++)
		{           
			// Add link html / the span html depending on if this is the 
			htmlLine = (i == currentPage ? currentLinkHTML : pagingLinkHTML);
			pagingHTML += htmlLine.replace('%', i);
		}
																										
		// Add link html / the span html depending on if the current page is the last. 
		htmlLine = (pagesNeeded == 1 || currentPage >= pagesNeeded ? '' : '<li class="next"><a href="#">Next</a></li>');
		pagingHTML += htmlLine;

	}
	
	return pagingHTML;
}

function previousLink_click()
{
	var currentPage = getCurrentPage();	
	return ecl_setUpPagination(--currentPage);
}

function nextLink_click()
{
	var currentPage = getCurrentPage();	
	return ecl_setUpPagination(++currentPage);			
}

function pagingLink_click()
{
	var linkClicked = $(this).log('link clicked').text();					
	return ecl_setUpPagination(linkClicked);
}

// Returns the current page in the table pagination (based on the list item that is a span.
// Returns 1 as the default.
function getCurrentPage()
{
	var currentPage = $('div.nav-pagination ul.nav-horizontal li span:first').log('current page').text();	
	if (currentPage == null || currentPage == "") 
	{
		currentPage = 1;
	}
	
	return currentPage;
}

function setUpResults()
{		
	var currentPage = getCurrentPage();	
	// Determine how many items are actually appearing on the 'current page',
	// for cases like the last page which may not be full.						
	var visibleItems = $(unfilteredRowSelector).filter(':visible').length;		
					
	// Determine the values to place in the results string.
	var resultsFrom = (currentPage - 1) * RESULTS_PER_PAGE + 1;
	var resultsTo = (currentPage - 1) * RESULTS_PER_PAGE + visibleItems; 			
	var resultsCount = $(unfilteredRowSelector).length;
	
	// Generate and replace any existing results with the new results.
	var resultsHTML = "Showing " + resultsFrom + " - " + resultsTo + " of " + resultsCount;	
	$('div.results').each(function () {
		$(this)[0].innerHTML = resultsHTML;					
	});
}

