/*
	Package: JumpList
	
	This js file sets up a JumpList package or namespace.  All javascript 
	jumplist related functions and variables exists within this namespace and
	are static methods, there are no instances or instance methods in use.
	
	The jumplist functions on this page depend upon several elements of the
	page being set:
	
	* There must be exactly one element with a class 'pagination_jumplist_filename_base'
		containing the filename_base of the current jumplist.
	
	{code}
		<span class="pagination_jumplist_filename_base style="display:none">dis_index123</span>
	{code}

	* There must be at least one <select> element with a class of pagination_jumplist_picker.
		Matching select boxes will have their contents replaced with the
		constructed jumplist <option> tags
	* There must be at least one element with the class 'pagination_jumplist_label'
		containing the label appropriate for that slice of the jumplist.
	
	{code}
		<span class="pagination_jumplist_label style="display:none">2009</span>
	{code}
	
	This package depends on jQuery being available
	
Example:

{code}
<body>
<script src="/assets/scripts/JumpList.js"></script>

<h1 jumplist_filename_base="<macro filename_base>"><macro dissertations.title></h1>

<form name="jumplist_form">
	Jump to:
	<select class="pagination_jumplist_picker">
		<option value="" disabled="true">-</option>
	</select>
</form>

<magic define_constant old_date></magic> 
 <ul>
<magic iterate Article field='paged_items'>

    <magic define_constant new_date><macro Article.publication_date format="%Y"></magic> 
    <magic if test="new_date ne old_date">
<br>
        <b jumplist_label="<macro new_date>">DISSERTATIONS FROM <macro new_date></b>
        <a name="<macro new_date>"></a><br>
        <macro jumplist_target label="<macro new_date>" url="<macro current_page_url>#<macro new_date>">
    </magic if> 

    <li>
    ...magic stuff listing the item and link...
    </li>

</magic iterate> 
</ul>


<form name="jumplist_form2">
	Jump to:
	<select class="pagination_jumplist_picker">
		<option value="" disabled="true">-</option>
	</select>
</form>
{code}

*/

if ( typeof console === 'undefined' )
{
	// TODO: strip this out in favor of the YUI // console and/or a more 
	// comprehensive dependancy resolver
	document.write('<script type="text/javascript" src="/assets/scripts/Console.js"><\/script>');
}

// Setup the package/namespace
var JumpList = {};

/*
	Function: JumpList.getJSONFileName
	
	Returns the name of the JSON file containing this page's jumplist data.
	It determines this by search the page for an element with an id of
	'paged_list_header' and an attribute named 'filebase'.  The value of
	that attribute is used to build the default json filename:
	
	{begin}
	
	fileNameBase + '_jumplist.json'
	
	{end}
	
	Returns:
		The filename or null.
	
*/
JumpList.getJSONFileName = function()
{
	var fileNameResult = null;
	
	var filenameBase = $( ".pagination_jumplist_filename_base" ).html();
	
	if ( filenameBase != null )
	{
		fileNameResult = filenameBase + "_jumplist.json";
	}
	
	return fileNameResult;
}

/*
	Function: JumpList.populateOptionsFromResponse
	
	This function handles the AJAX request's successful return by parsing
	the JSON file and populating the page's jumplist <select> box with the
	label and first url of that label for all available 'jump' pages.
	
*/
JumpList.populateOptionsFromResponse = function( inJsonObj )
{
	// console.log( "populateOptionsFromResponse" );
	
	var optionHTML = '';
	
	// When the user has jumped to the current page, the full url will be
	// recognisable as having come from the JSON file.  It is possible that
	// url is associated with a label within that file, and we can use it
	// to determine which of the <option> tags to select on page load.
	var asRecordUrlLabel = {};
	
	var pickers = $( ".pagination_jumplist_picker" );

	if ( inJsonObj.length == 0 )
	{
		// console.log( "inJsonObj.length = " + inJsonObj.length );
		
		// we've received a valid JSON file but there's just no pages
		// to worry about beyond this one.
		
		for ( var g = 0; g < pickers.length; g++ )
		{
	
			var selectEl = pickers[ g ];
			selectEl.options[ 0 ] = new Option( '- none -', '' );
		}
		
		return;
	}
	
	var start = new Date();

	// For each of the <select> boxes on the page, populate them with
	// new Option() objects for the jumplist targets in the json file.
	// We must do this explicitly versus constructing a string of html
	// containing the <option> tags because IE6 will only treat the new
	// set of options as real, scriptable, 'normal' elements of the page if
	// they are created via 'new Option(...)' - not via something like
	// 'selectObj.innerHTML = theOptHTML'
	for ( var g = 0; g < pickers.length; g++ )
	{

		var selectEl = pickers[ g ];

		for(var i=0; i < inJsonObj.length; i++)
		{
			var record = inJsonObj[i];
			
			// console.log ("label: " + record.label + " url:" + record.url );
			
			selectEl.options[ i ] = new Option( record.label, record.url );
			
			if ( ! asRecordUrlLabel[ record.url ] )
			{
			
				// console.log( "url '" + record.url 
				//	+ "' has first label of '" + record.label + "'" );
					
				asRecordUrlLabel[ record.url ] = record.label;
			}
			else
			{
				/*
				console.log( "url '" + record.url 
					+ "' has next label '" + record.label
					+ "' but using '"
					+ asRecordUrlLabel[ record.url ] + "'" );
				*/
			}
	
		}
	}	
	
	// We want to set the currently selected option to either the first label
	// that appears on this screen OR the URL fragment denoting the label that 
	// we have been sent to, so long as it appears in the list.
	var selectLabel = null;
	
	var locationStr = window.location.toString();
	var urlLabel = asRecordUrlLabel[ locationStr ];
	
	if ( urlLabel != null )
	{
		// there may be more than one <select> box on the page, so loop through
		// them all
		for ( var i = 0; i < pickers.length ; i++ )
		{			
			if ( $( pickers[ i ] ).find( "option:contains(" + urlLabel + ")" ).size() > 0 )
			{
				// console.log( "Label '" + urlLabel + "' exists in options" );
				selectLabel = urlLabel;
				break;
			}
		}
	}
	
	// selectLabel will be null if there is no url fragment that has a label 
	// in the options list.  So then just grab the contents of the first 
	// found .pagination_jumplist_label class element
	if ( selectLabel == null )
	{
		selectLabel = $( ".pagination_jumplist_label" ).html();
	}

//	console.log( "setting selected property for current label " + selectLabel );
	
	for ( var i = 0; i < pickers.length ; i++ )
	{
		var theOption = $( pickers[ i ] ).find( "option:contains(" + selectLabel + ")" )[ 0 ];
		
		theOption.selected = true;	
	}

//	console.log( "assigning onchange handler" );
	
	// assign the onchange handler to all the select boxes.
	pickers.change( function() {
	
		var theOption = $( this ).find( "option:selected" )[ 0 ];
		
		document.location = theOption.value;
		
		} );

}


JumpList.handleAJAXError = function (XMLHttpRequest, textStatus, errorThrown) {
  // typically only one of textStatus or errorThrown 
  // will have info
  
	this; // the options for this ajax request
  	$( ".pagination_jumplist_picker option" ).text( "JumpList Error" );
  	
	if ( textStatus )
	{
		$( ".pagination_jumplist_picker" ).after( '<em style="color: red">Unable to build jumplist: ' + textStatus + '<\/em>' );
	}
	if ( errorThrown )
	{
		$( ".pagination_jumplist_picker" ).after( '<em style="color: red">Unable to build jumplist: ' + errorThrown + '<\/em>' );
	}
  
}


// called when page load is complete 
$( document ).ready( function(){

	// Verify that we have the required page elements to build a jump list
	// control
	var errors = new Array();
	
	var jumplistElements = $( ".pagination_jumplist_picker" );
	
	if ( jumplistElements.size() == 0 )
	{
		errors[ errors.length ] = 'Unable to find any jumplist select boxes.';
	}

	var filenameBaseEl = $( ".pagination_jumplist_filename_base" );
	if ( filenameBaseEl.size() == 0 )
	{
		errors[ errors.length ] = 'Unable to find the jumplist filename base.';
	}

	var jumpLabels = $( ".pagination_jumplist_label" );
	if ( jumpLabels.size() == 0 )
	{
		errors[ errors.length ] = 'Unable to find any jumplist labels.';
	}


	
	// page has the required elements for a jumplist?  go for it
	if ( errors.length <= 0 )
	{
		var jsonURL = JumpList.getJSONFileName();
		
		// console.log( "requesting " + jsonURL );

			$.ajax({
				url: jsonURL,
				dataType: "json",
				success: JumpList.populateOptionsFromResponse,
				error: JumpList.handleAJAXError
			});
	}
	else
	{
		// otherwise we could bark here
		for ( var i = 0 ; i < errors.length; i++ )
		{
			console.log( errors[ i ] );
		}
//		alert( 'Error:\n' + errors.join( "\n" ) );
	}
} 
);
