
//  Any copy/code to be displayed before the actual pagination
var paginationInitialization = 'Pages: ';
//  The previous page indicator; must implement the previousPage() function
var previousPageIndicator = '<a href="#" class="previousPage" onclick="previousPage(); return false;"><</a> ';
//  The previous page disabled indicator
var previousPageOffIndicator = '<a href="#" style="visibility: hidden;" class="previousPage" onclick="previousPage(); return false;"><</a> ';
//  The next page indicator; must implement the nextPage() function
var nextPageIndicator = '<a href="#" class="nextPage" onclick="nextPage(); return false;">></a> ';
//  The next page disabled indicator
var nextPageOffIndicator = '<a href="#" style="visibility: hidden;" class="nextPage" onclick="nextPage(); return false;">></a> ';
//  Any copy/code to be displayed after the actual pagination
var paginationConclusion = '&nbsp;&nbsp;|&nbsp;&nbsp;';
//  The ellipses to be displayed in the early part of pagination when necessary
var preEllipsesDisplay = '...&nbsp;';
//  The ellipses to be displayed in the later part of pagination when necessary
var postEllipsesDisplay = '...';
//  The div id selector that holds the pagination
var paginationDivId = ".pagination-pagenumbers";
//  The number of products per page
var pageSize = 9;
//  The selector for the div and links for the show all pages link
var viewAllPagesSelector = "#mira-productResults-pageNavigation a.showAllPages";
//  The page number section selector
var pageNumbersSelector = ".pagination-pagenumbers";

function setHeight() {
    var headerHeight = 0;
    var elements = [];
    var numColumns = 0;
    var xOffset = -9999;

    // first, find the number of columns
    var items = $(".productResult").get();
    for (var i = 0; i < items.length; i++) {
        var left = $(items[i]).offset().left;
        if (left <= xOffset) {
            break;
        }
        xOffset = left;
        numColumns =  numColumns + 1;
    }

    $('p.productResult-prodName').each(function(i) {
		$(this).css('height','auto');
        headerHeight = Math.max($(this).height(), headerHeight);
        elements.push(this);
        if (i % numColumns == numColumns - 1) {
            $(elements).css("height", headerHeight + "px");
            elements = [];
            headerHeight = 0;
        }
    });
	$(elements).css("height", headerHeight+'px');

    var resultHeight = 0;
    elements = [];
    $('.productResult').each(function(i) {
		$(this).css('height','auto');
        resultHeight = Math.max($(this).height(), resultHeight);
        elements.push(this);
        if (i % numColumns == numColumns - 1) {
            $(elements).css("height", resultHeight + "px");
            elements = [];
            headerHeight = 0;
        }
    });
	$(elements).css("height", resultHeight+'px');
}

function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  }
  else {
    window.onload = function() {
      if (oldonload) {
        oldonload();
      }
      func();
    }
  }
}

addLoadEvent(setHeight);

// This will do the initial binding of functions to events within the page.
$(function() {
	$(viewAllPagesSelector).live('click',function() {
        $(pageNumbersSelector).css('display','none');
        $('.results-page').css('display','block');
		$('.productResult').removeClass('productResult-firstRow');
		$('.productResult:lt(3)').addClass('productResult-firstRow');
        $('a.showAllPages').html("View as multiple pages");
        $('a.showAllPages').addClass('showPaginated');		
        $('a.showAllPages').removeClass('showAllPages');
        setHeight();
    });
    $('#mira-productResults-pageNavigation a.showPaginated').live('click',function() {
        $('.pagination-pagenumbers').css('display','inline');
        $('.results-page').css('display','none');
        $('#results-1').css('display','block');
        $('a.showPaginated').html("View as 1 page");
        $('a.showPaginated').addClass('showAllPages');
        $('a.showPaginated').removeClass('showPaginated');
        setHeight();
    });
    createPagination(productCount,1);
});


var whichActive = 1;
function showPage(id) {
		var showwhich = '';
		showwhich = id;
        whichActive = id;
		$('#mira-productResults-pageNavigation a').removeClass('activePage')
		$('#'+id).addClass('activePage')
		$('.results-page').css('display','none');
		$('#results-' + showwhich).children('.productResult:lt(3)').addClass('productResult-firstRow');
		$('#results-' + showwhich).css('display','block');
        createPagination(productCount, id)
		setHeight();
    }

function nextPage() {
        whichActive++;
		$('#mira-productResults-pageNavigation a').removeClass('activePage')
		$('#' + whichActive).addClass('activePage')
		$('.results-page').css('display','none');
		$('#results-' + whichActive).children('.productResult:lt(3)').addClass('productResult-firstRow');
		$('#results-' + whichActive).css('display','block');
        createPagination(productCount, whichActive);
		setHeight();
    };

function previousPage() {
		whichActive--;
		$('#mira-productResults-pageNavigation a').removeClass('activePage')
		$('#' + whichActive).addClass('activePage')
		$('.results-page').css('display','none');
		$('#results-' + whichActive).children('.productResult:lt(3)').addClass('productResult-firstRow');
		$('#results-' + whichActive).css('display','block');
        createPagination(productCount, whichActive);
		setHeight();
    }



/**
 * This function builds and returns a page link for the given page in the pagination sequence.
 * When using this file this method can be overwritten with site specific display code
 * @param pageNumber the page number of the link being built
 * @param currentPage the current page number of the results being shown
 */
function buildPageLink(pageNumber,currentPage) {
    var pageLinkPartOne = '<a href="#" class="pageNumber ';
    var pageLinkActiveClass = ' activePage ';
    var pageLinkPartTwo = '" id="';
    var pageLinkPartThree = '" onclick="showPage(';
    var pageLinkPartFour = ');return false;">';
    var pageLinkPartFive = '</a>';
    var pageLink = pageLinkPartOne;
    if(pageNumber == currentPage) {
        pageLink += pageLinkActiveClass;
    }
    pageLink += pageLinkPartTwo + pageNumber + pageLinkPartThree + pageNumber+ pageLinkPartFour + pageNumber + pageLinkPartFive;
    return pageLink;
}

/**
 * This function creates a string of the pagination to be displayed and inserted into the
 * div configured for pagination.
 * @param totalProducts the total number of products
 * @param currentPage the current page number of the results being shown
 */
function createPagination(totalProducts, currentPage) {
    var pagination = paginationInitialization;
    var totalPages = totalProducts/pageSize;
    var firstSlot;
    var lastSlot;
    var preEllipses = false;
    var postEllipses = false;
    var numberOfSlots = 9;
    if(totalProducts%pageSize!=0) {
      totalPages = Math.floor(totalPages+1);
    }

    //  Determine slots
    if(totalPages > 1) {
      firstSlot = getFirstSlot(totalPages, numberOfSlots, currentPage);
      lastSlot = getLastSlot(totalPages, numberOfSlots, firstSlot);

      if(firstSlot >= 2 && (currentPage - (numberOfSlots/2) >1)) {
          preEllipses = true;
          numberOfSlots -= 2;
          firstSlot = getFirstSlot(totalPages, numberOfSlots, currentPage);
          lastSlot = getLastSlot(totalPages, numberOfSlots, firstSlot);
      }

      if(firstSlot > 2 && (totalPages == (lastSlot+1))) {
          ++firstSlot;
          ++lastSlot;
      } else if(totalPages > lastSlot) {
          postEllipses=true;
          numberOfSlots -= 2;
          firstSlot = getFirstSlot(totalPages,numberOfSlots,currentPage);
          lastSlot = getLastSlot(totalPages,numberOfSlots,firstSlot);
      }

    }
    //  Print previous arrow if not first page
    if(currentPage > 1) {
        pagination += previousPageIndicator;
    } else {
        pagination += previousPageOffIndicator;
    }

    //  Print page 1 crumb
    pagination += buildPageLink(1,currentPage);

    //  If ellipses are due use them
    if(preEllipses) {
      pagination += preEllipsesDisplay;
    }

    //  Update the first slot if page 1
    if(firstSlot==1) {
      firstSlot = 2;
    }

    //  Loop over the slots
    for(var i= firstSlot; i<=lastSlot;i++) {
      if(i!= totalPages) {
          pagination += buildPageLink(i,currentPage);
      }
    }

    //  If ellipses are due, use them
    if(postEllipses) {
      pagination += postEllipsesDisplay;
    }

    //  Print last page crumb
    pagination += buildPageLink(totalPages, currentPage);

    //  If not last page use next link
    if(currentPage != totalPages && currentPage != 0) {
        pagination += nextPageIndicator;
    } else {
        pagination += nextPageOffIndicator;
    }

    pagination += paginationConclusion;
    if(totalPages == 1) {
        pagination = '';
    }
    $(paginationDivId).html(pagination);

    $("#mira-productResults-pageNavigation a.showPaginated").click();
}

/**
 * Gets the first slot in the pagination sequence after the first page.
 * @param totalPages the total number of pages
 * @param numberOfSlots the number of slots to be filled
 * @param currentPageNumber the current page number of the results being displayed
 */
function getFirstSlot(totalPages, numberOfSlots, currentPageNumber) {
    var howManyPerSide = Math.floor(numberOfSlots / 2);
    var firstSlot;
    if (totalPages <= numberOfSlots || currentPageNumber <= howManyPerSide) {
        firstSlot = 1;
    } else if ((currentPageNumber + howManyPerSide) >= totalPages) {
        firstSlot = totalPages - numberOfSlots + 1;
    } else {
        firstSlot = currentPageNumber - howManyPerSide;
    }
    return firstSlot;
}

/**
 * Gets the last slot in the pagination sequence before the last page.
 * @param totalPages the total number of pages
 * @param numberOfSlots the number of slots to be filled
 * @param firstSlot the value of the first slot
 */
function getLastSlot(totalPages, numberOfSlots, firstSlot) {
    var lastSlot;
    if (totalPages <= numberOfSlots) {
        lastSlot = totalPages;
    } else {
        lastSlot = firstSlot + numberOfSlots - 1;
    }
    return lastSlot;
}

