(function($){

// Creating the sweetPages jQuery plugin:
$.fn.paginate = function(opts){

	// If no options were passed, create an empty opts object
	if(!opts) opts = {};

	var resultsPerPage = opts.perPage || 3;

	// The plugin works best for unordered lists, althugh ols would do just as well:
	var ul = this;
	var li = ul.find('li.page');

	li.each(function(){
		// Calculating the height of each li element, and storing it with the data method:
		var el = $(this);
		el.data('height',el.outerHeight(true));
	});

	// Calculating the total number of pages:
	var pagesNumber = Math.ceil(li.length/resultsPerPage);

	// If the pages are less than two, do nothing:
	if(pagesNumber<2) return this;

	// Creating the controls div:
	var swControls = $('<ul class="swControls">');
  swControls.append('<li><a href="#page-1" class="swShowPage prev" rel="1_1">&lt; Previous</a></li>');
  
	for(var i=0;i<pagesNumber;i++)
	{
		// Slice a portion of the lis, and wrap it in a swPage div:
		li.slice(i*resultsPerPage,(i+1)*resultsPerPage).wrapAll('<div class="swPage" />');

		// Adding a link to the swControls div:
		swControls.append('<li><a href="#page-'+(i+1)+'" class="swShowPage" rel="'+(i+1)+'">'+(i+1)+'</a></li>');
    /*
    if(i<pagesNumber-1) {
      swControls.append('<li>|</li>');
    }
    */
	}

  swControls.append('<li><a href="#page-3" class="swShowPage next" rel="2_2">Next &gt;</a></li>');

	ul.append(swControls);

	var maxHeight = 0;
	var totalWidth = 0;

	var swPage = ul.find('.swPage');
	swPage.each(function(){

		// Looping through all the newly created pages:

		var elem = $(this);

		var tmpHeight = 0;
		elem.find('li').each(function(){tmpHeight+=$(this).data('height');});

		if(tmpHeight>maxHeight)
			maxHeight = tmpHeight;

		totalWidth+=elem.outerWidth();

		elem.css('float','left').width(ul.width());
	});

	swPage.wrapAll('<div class="swSlider" />');

	// Setting the height of the ul to the height of the tallest page:
	ul.height(maxHeight);

	var swSlider = ul.find('.swSlider');
	swSlider.append('<div class="clear" />').width(totalWidth);

	var hyperLinks = ul.find('a.swShowPage');
  var maxlinks = 15;
	var gotopage = function(e){
		var baseuri = $.address.baseURL();
    var temp = $(this).attr('href').split(baseuri);
		var loc;
		if(temp.length==2) {
			loc = temp[1];
		} else {
			loc = temp[0];
		}
    var pageid = parseInt(loc.split('#')[1].split('-')[1]);
    var page = $('li.page')[pageid-1];
    if(pageid!=1) {
      $.address.value(loc.replace(/^#/, ''));
    } else {
      $.address.value('');
    }
    ul.stop().animate({'height':$(page).data('height')});
		swSlider.stop().animate({'margin-left':-(pageid-1)*ul.width()},'normal',function() {
      $('.swControls a.active').removeClass('active');
      $('.swControls a[href$=page-'+pageid+']').each(function() {
				if(!$(this).hasClass('next') && !$(this).hasClass('prev')) {
					$(this).addClass('active');
				}
			});
      if(pagesNumber>maxlinks) {
        var i;
        $('.swControls a').show();
        if(pageid<=maxlinks/2) {
          for(i=maxlinks+1; i<=pagesNumber; i++) {
            $('.swControls a[href$=page-'+i+']').hide();
          }
        } else if((pagesNumber-pageid)<=maxlinks/2) {
          for(i=1; i<=pagesNumber-maxlinks; i++) {
            $('.swControls a[href$=page-'+i+']').hide();
          }
        } else {
          for(i=1; i<=pagesNumber; i++) {
            if(i<=pageid-(maxlinks/2) || i>=pageid+(maxlinks/2)) {
              $('.swControls a[href$=page-'+i+']').hide();
            }
          }
        }
      }
      var nextrel, prevrel;
      if(pageid==1) {
        prevrel = 1;
        nextrel = 2;
        $('.swControls a.prev').hide();
        $('.swControls a.next').show();
      } else if(pageid==pagesNumber) {
        prevrel = pagesNumber - 1;
        nextrel = pagesNumber;
        $('.swControls a.prev').show();
        $('.swControls a.next').hide();
      } else {
        prevrel = pageid - 1;
        nextrel = pageid + 1;
        $('.swControls a.prev').show();
        $('.swControls a.next').show();
      }
      $('.swControls a.prev').attr('href', '#page-'+prevrel);
      $('.swControls a.next').attr('href', '#page-'+nextrel);
    });
		e.preventDefault();
	}
	hyperLinks.click(gotopage);
	$("a.page-link").click(gotopage);
	// Mark the first link as active the first time this code runs:
	hyperLinks.eq(1).addClass('active');
	return this;

}})(jQuery);


$(document).ready(function(){
	$('#holder').paginate({perPage:1});
	var controls = $('.swControls').detach();
	controls.appendTo('.pagination');
  var loc = window.location.toString();
  var pageid;
  if(loc.indexOf('#')>=0) {
    pageid = loc.split('#')[1].split('-')[1];
  } else {
    pageid = 1;
  }
	//$('.swControls a[href$=page-'+pageid+']').click();
	$.address.change(function(event) {
		pageid = event.value.split('-')[1];
    if(typeof(pageid)=='undefined') {
      pageid = 1;
    }
		var firstlink = $('.swControls a[href$=page-'+pageid+']')[0];
    var activePage = $('li.page')[pageid-1];
    $('#topSecretPage').html($(activePage).html());
    $(firstlink).click();
	});
});
