/**
 * The pagination JQuery plugin.
 * Creation inspiration in @see: http://malsup.com/jquery/cycle/lite/
 */
;(function($){

var ver = '0.1';

/**
 * Is used for starting the plugin. Like:
 *
 *  $('#selector').pagination({
 *		pagingSelector: '#something'
 *	});
 *
 */
$.fn.pagination = function(options){
		if(!this.length) {
			log("The selector " + this.selector + " wasn't found in page.");
			return;
		}

	    return this.each( function() {
	        options = options || {};

	        // support metadata plugin (v1.0 and v2.0)
	        var opts = $.extend({}, $.fn.pagination.defaults, options || {}, $.metadata ? $cont.metadata() : $.meta ? $cont.data() : {});

	        if(!opts.pagingSelector) {
	            log('terminating; there is no information about what element should be paged');
	        	return; // nothing to do
	        }

	        opts.nextImg = opts.nextImage ? ("<img src=" + opts.nextImage + "/>"):"<span class='btAvancarcases replace'>&gt;&gt;</span>";
	        opts.prevImg = opts.prevImage ? ("<img src=" + opts.prevImage + "/>"):"<span class='btVoltarcases replace'>&lt;&lt;</span>";
	        opts.pageSize = (opts.pageSize && opts.pageSize>0) ? opts.pageSize : 5;
			opts.pagingMenuClass = opts.pagingMenuClass ? opts.pagingMenuClass : "";
			opts.paggingMenuActiveClass = opts.pagingMenuActiveClass ? opts.pagingMenuActiveClass : "";

	        var $pagingMenu = $(this); // paging menu content
	        var $startElement = opts.wrapperPagingSelector ? $(opts.wrapperPagingSelector) : $(document);
	        var $pagingElements = $startElement.find(opts.pagingSelector);

	        // preparing data
	        var pagingRecord = 1;
	        var pages = [];
	        var page = [];
	        $pagingElements.each( function(index)
	        {
	        	page.push($(this));
	        	$(this).hide(); // hide all pagination records

	        	if(pagingRecord >= opts.pageSize || (index + 1) >= $pagingElements.length)
	        	{
	        		pages.push(page);
	        		page = [];
	        		pagingRecord = 1;
	        	}

	        	pagingRecord++;
	        });

	        // Defining the information that will be passed to the paging functions
	        opts.pages = pages;
	 		opts.countPage = pages.length;
	        opts.currPageIndex = 0;

	        // Creating menu and show the first page
	        var $menu = createPaginationMenu(opts, $pagingMenu);
	        showPage(opts, opts.currPageIndex);

			// When there is not enought pages - hide all pagination
			if(opts.countPage <= 1) {
				$menu.hide();
			}

	        //console.log("pages length: " + pages.length + " , pagingElements count: " + $pagingElements.length);
	    }); // end each function
	};

	/**
	 * Create HTML elements for menu and register triggers.
	 * @param opts	the global passing variable with data about pages and current state
	 * @param $menuElement	element that the user set to be a element where the menu will be put to
	 * @returns	the created menu HTML element
	 */
	function createPaginationMenu(opts, $menuElement) {
		$menuWrapper = $(document.createElement('div'));
		$menuElement.empty();
		$menuElement.append($menuWrapper);

	    var cssObj = {
	      'float' : 'left',
	      'display' : 'block',
	      'cursor' : 'pointer'
   	    };

		$wrapperPrevImg = $(document.createElement('div')); // wrapper
		$prevImg = $(opts.prevImg); // creating element for prev img
		$wrapperPrevImg.append($prevImg);
		$wrapperPrevImg.css(cssObj);
		$wrapperPrevImg.click(function(e){
			if(opts.currPageIndex == 0) {return false;}
			showPage(opts, opts.currPageIndex - 1);
			e.preventDefault();
		});
		opts.prevImg = $wrapperPrevImg;

		$wrapperNextImg = $(document.createElement('div')); // wrapper
		$nextImg = $(opts.nextImg); // creating element for next img
		$wrapperNextImg.append($nextImg);
		$wrapperNextImg.css(cssObj);
		$wrapperNextImg.click(function(e){
			if(opts.currPageIndex >= opts.countPage - 1) {return false;}
			showPage(opts, opts.currPageIndex + 1);
			e.preventDefault();
		});
		opts.nextImg = $wrapperNextImg; // adding the created elements to opts parameter that is passed through all class

		$menuWrapper.append($wrapperPrevImg);

		var anchors = []; // data structure by index saved data
		for(var i=0; i<opts.countPage; i++) {
			$anchor = $(document.createElement('a'));
			$anchor.text(i+1);
			$anchor.css({'float': 'left', 'display':'block', 'cursor': 'pointer'});
			$anchor.addClass(opts.pagingMenuClass);
			$anchor.bind('click', i, function(e){
				showPage(opts, e.data);
				e.preventDefault();
			});
			anchors.push($anchor);

			if(i == 0) {
				opts.activeAnchor = $anchor; // setting active anchor
			}
			$menuWrapper.append($anchor);
		}
		opts.anchors = anchors;

		$menuWrapper.append($wrapperNextImg);
		return $menuWrapper;
	}

	/**
	 * Change the visibility of records.
	 */
	function showPage(opts, index) {
		//console.log("Show page index: " + index);

		// hide current records
		var page = opts.pages[opts.currPageIndex];
		if(page == null) return;
		for(var i=0; i< page.length; i++) {
			page[i].hide();
		}
		// show the new page
		page = opts.pages[index];
		for(var i=0; i< page.length; i++) {
			page[i].show();
		}

		hideArrows(opts, index);
		setActiveAnchor(opts, index);
		// set the current page number
		opts.currPageIndex = index;
	}

	/**
	 * Hide or show the previous and finish arrows.
	 */
	function hideArrows(opts, index) {
		if((index <= 0 && index >= opts.countPage - 1) || opts.hideArrows) {
			opts.prevImg.css('visibility', 'hidden');
			opts.nextImg.css('visibility', 'hidden');
		}
		else if(index <= 0) {
			opts.prevImg.css('visibility', 'hidden');
			opts.nextImg.css('visibility', 'visible');
		} else if (index >= (opts.countPage - 1)) {
			opts.prevImg.css('visibility', 'visible');
			opts.nextImg.css('visibility', 'hidden');
		} else {
			opts.prevImg.css('visibility', 'visible');
			opts.nextImg.css('visibility', 'visible');
		}
	}

	function setActiveAnchor(opts, index) {
		opts.activeAnchor.removeClass(opts.paggingMenuActiveClass);
		opts.anchors[index].addClass(opts.paggingMenuActiveClass);
		opts.activeAnchor = opts.anchors[index];
	}

	/**
	 * Log for Firefox.
	 */
	function log() {
		if (window.console && window.console.log)
			window.console.log('[pagination plugin] ' + Array.prototype.join.call(arguments,' '));
	}

	$.fn.pagination.ver = function() { return ver; };

	/**
	 * Defining default settings.
	 */
	$.fn.pagination.defaults = {
			pagingSelector: "", // the elements that will be in document search for and will be hidden by pagination
			wrapperPagingSelector: null, // the selector that will be used for getting the info about pagingSelector - when nothing is set then the all document will be searched for the pagingSelector
			nextImg: null, // image for the next, for NULL will be used >>
			prevImg: null, // image for the back, NULL = <<
			pageSize: 5, // number of elements on one page
			hideArrows: false,
			pagingMenuClass: null, // class that will be added to the anchor that will work for changing pages
			paggingMenuActiveClass: null // class that will be set to anchor of the active page number
	};

})(jQuery);

