/*
 * pagerView.js - DHTML pager/slider views
 *
 * PREREQUISITES:
 * - prototype.js v1.6
 * - lowpro.js v0.5
 *
 * v0.1   - 2010-04-02 - Morgan Aldridge <morgant@makkintosshu.com>
 *                       Initial development (based on tabbedView.js)
 * v0.2   - 2010-06-21 - Morgan Aldridge
 *                       Auto-centering of pager view nav & animation delay now set by variable.
 * v0.3   - 2010-09-30 - Morgan Aldridge
 *                       Only animate if more than one page in the pager view.
 */

//console.log("Begin: pagerView.js...");

if (!window['smalldog']) { window['smalldog'] = {}; }
if (!window['smalldog']['pagerView']) { window['smalldog']['pagerView'] = {}; }
smalldog.pagerView = {
	animationDelay: 8	// amount of time (in seconds) to display each page before animating to next
}

function selectPage( page )
{
	// step through all the pages in this pager view
	var allPages = page.up().select('.page');
	for ( var i = 0; i < allPages.length; i++ )
	{
		var singlePage = allPages[i];
		
	    // is this page in the same pager view we're working with?
	    if ( singlePage.up().id == page.up().id )
	    {
	    	// if this is not the page we want to select
	    	if ( singlePage != page )
	    	{
	    		// hide it and make sure it doesn't have the class 'selected'
	    		if ( singlePage.hasClassName('selected') )
	    		{
	    			singlePage.removeClassName('selected');
	    		}
	    		singlePage.hide();
	    	}
	    	// otherwise, if this is the page we want to select
	    	else
	    	{
	    		// show it and make sure it has the class 'selected'
	    		if ( !singlePage.hasClassName('selected') )
	    		{
	    			singlePage.addClassName('selected');
	    		}
	    		singlePage.show();
	    	}
	    }
	    // if it's not, then honor its existing selected/unselected page states
	    else
	    {
	    	if ( singlePage.hasClassName('selected') )
	    	{
	    		singlePage.show();
	    	}
	    	else
	    	{
	    		singlePage.hide();
	    	}
	    }
	}
}

function selectPageById( pageId )
{
	selectPage( $(document.getElementById(pageId)) );
}

document.observe('dom:loaded', function() {
	
	//console.log("\tBegin: pagerView.js, document.observe('dom:loaded', function () { ... }) ...");
	
	$$('div.pager').each(function(element) {
	    // get all the pager view's individual pages
	    var pages = element.select('.page');
	    
	    // set the size of the page div
	    element.setStyle({
			display: 'block',
			width: '53em',
			height: '19.643em',
			overflow: 'hidden'
	    });
	    
	    // count the number of pages in this pager view
	    var numPages = 0;
	    for ( var i = 0; i < pages.length; i++ )
	    {
	    	// is the page in this pager view?
	        if ( pages[i].up().id == element.id )
	        {
	        	numPages++;
	        }
	    }
	    //console.log("\t\t"+numPages+" pages in this pagerView...");
	
	    // create the pager nav element
	    element.insert({
		top: "<ul class=\"nav\"></ul>"
	    });

	    
	    // step through all the pages again
	    var thisPageIndex = 0;
	    var defaultPage;
	    for ( var i = 0; i < pages.length; i++ )
	    {
	    	var page = pages[i];
	    	
	    	// is the page in this pager view?
	    	if ( page.up().id == element.id )
	    	{
	    		//console.log("\t\t\tpage "+thisPageIndex+":");
			
			// remember the default page
	    		if ( page.hasClassName('default') )
	    		{
	    			defaultPage = page;
	    		}
	    		// or at least the first page
	    		else if ( thisPageIndex == 0 )
	    		{
	    			defaultPage = page;
	    		}
			
			// add a link to this page to the pager nav list
			newAnchor = new Element('a', { href: '#'+page.id });
			newListItem = new Element('li');
			if ( i == 0 )
			{
				newListItem.addClassName('selected');
			}
			element.down('.nav').insert({
				bottom: newListItem.insert({
					top: newAnchor.observe('click', function (targetId, event) {
						var thisAnchor = event.findElement('a');
						// deselect whichever li is marked as 'selected'
						thisAnchor.up('ul.nav').select('.selected').invoke('removeClassName', 'selected');
						// and mark our parent li as 'selected'
						thisAnchor.up().addClassName('selected');
						// show the target id
						selectPageById(targetId);
						event.stop();
					}.curry(page.id))
				})
			});
	    		
	    	    // increment the index of this page in this pager view
	    	    thisPageIndex++;
	    	}
	    }
	    
	    if ( location.hash )
	    {
	    	var urlAnchor = location.hash.substring(location.hash.lastIndexOf('#')+1);
	    	if ( $(urlAnchor).hasClassName("page") )
	    	{
	    		selectPageById(urlAnchor);
	    		
	    		//  scroll to the parent pager view
	    		var pagerViewPos = $(urlAnchor).cumulativeOffset();
	    		window.scrollTo(pagerViewPos.left, pagerViewPos.top);
	    	}
	    	else
	    	{
	    		// show the first/default page
	    		selectPage( defaultPage );
	    	}
	    }
	    else
	    {
	    	// show the first/default page
	    	selectPage( defaultPage );
	    }
		
		// horizontally center the pager view's navigation list

		navList = element.down(".nav");
		navList.setStyle({
			left: ((element.getWidth() - navList.getWidth())/2) + 'px'
		});

		// automatically switch between the pages periodically (only if there's more than one)
		if ( pages.length > 1 )
		{
			new PeriodicalExecuter(function (pe) {
				cur = $(this).down(".page.selected");
				next = cur.next(".page");
				if ( !next )
				{
					next = this.down(".page:first");
				}
				curAnchor = $(this).down(".nav .selected");
				nextAnchor = $(this).down(".nav a[href=\"#"+next.id+"\"]").up("li");
				// animate the transition between the current & next pages
				cur.blindUp({ duration: 1.0 }).removeClassName('selected');
				next.blindDown({ duration: 1.0 }).addClassName('selected');
				// update the nav links to denote which is now selected
				curAnchor.removeClassName('selected');
				nextAnchor.addClassName('selected');
			}.bind(element), smalldog.pagerView.animationDelay);
		}
	});
	
	$$('a.pageLink').each(function(element) {
	    element.observe('click', function(event) {
	    	// parse the anchor link and select the specified page
	    	var pageId = this.href.substring(this.href.lastIndexOf('#')+1);
	    	selectPageById(pageId);
	    	
	    	//  scroll to the parent pager view so the pages are in view
	    	var pagerViewPos = $(pageId).cumulativeOffset();
	    	window.scrollTo(pagerViewPos.left, pagerViewPos.top);
	    	
	    	// prevent the default click event from occurring and scrolling to the id
	    	event.stop();
	    });
	});
	
	//console.log("\tEnd: pagerView.js, document.observe('dom:loaded', function () { ... }) ...");
	
});

//console.log("End: pagerView.js.");

