/*

*/
jQuery(document).ready(function($) {
  var $ = jQuery;
	if($('#collectionTitles').length > 0) {
    initCollectionTitleSelect();
	}

  if($('a[rel*=facebox]').length > 0) {
    $('a[rel*=facebox]').facebox();    
  }
    
});

function initViewSearchExamples(){
	var $=jQuery;
	$('.exampleSearch dl').hide();
	$('.exampleSearch h3 a').click(function(o){
		var me = $(this);
		if(me.hasClass('examplesHidden')){
			me.html('View Examples');
			me.removeClass('examplesHidden');
		}else{
			me.html('Hide Examples');
			me.addClass('examplesHidden');
		}
		$('dl', me.parent().parent()).slideToggle();
		return false;
	});
}

// This function isn't necessary anymore: everything gets handled in teiDocformatter.xsl now...
/* This gets called when the page loads */
/*function loadSchoolLogoImage(logo_path){
	// create a url to an image (might not exist)
	
	    

	var logo_source = '/xtf/icons/logos/' + logo_path;
	// use ajax to see if the url is valid
	$.ajax({
		url: logo_source,
		complete: function(xmlHttp){
			// if it's valid, replace the @src of the #schoollogo img with logo_source
			//   - also replace the alt tag with the id of the client
			if(xmlHttp.status==200){
				$('#schoollogo').attr('src', logo_source);
				$('#schoollogo').attr('alt', logo_path);
			}
		}
	});
		
}*/

/*
This pulls together and makes available the individual Collection Titles, pulled from teiHeaders
*/
function initCollectionTitleSelect(){
	var $=jQuery;

	// populate the select element on page load...
	// these values coming from the /xtf/search?browse-collections=true page
	// so be careful when modifying that page
	
	
	$.get('/xtf/search?browse-collections=true', function(data){
		$('#collectionTitles option').html('All Titles');
		var all = $('div.collectionShortTitle a', data);
		$(all).each(function(){
			var v=$(this).html();
			$('#collectionTitles').append('<option value="' + v + '">' + v + '</option>');
		});
	})
	
	function applyCollectionTitleRemove(id_and_text, list_item){
		// apply a click handler so that items can be removed
		$('span', list_item).click(function(){
			// remove the hidden input element
			$('input[value*=' + id_and_text + ']').remove();
			// fade out nicely and remove
			$(this).parent().fadeOut(function(){
				$(this).remove();
			});
		});
	}
	
	// apply remove behaviors to the currently applied collection titles
	// go thru each li item
	$('#selectedCollectionTitles li').each(function(){
		var me = $(this)
		var id = me.attr('id')
		var related_input_element = $('input[value*=' + id + ']');
		applyCollectionTitleRemove(id, me);
	});
	
	// apply a "change" handler to the select that adds the facet titles to the form/view
	$('#collectionTitles').change(function(){
		// grab the text of the option value selected
		var id_and_text = $(this).val() + '';
		// for some ODD reason, finding a node with an exact #id of id_and_text doesn't work...
		var find_string = '[id*=' + id_and_text + ']';
		// see if it's already been added...
		
		if( $(find_string).length != 0){
			// already added, return...
			return;
		}
		// create a list element to display the selected value...
		var list_item = $('<li id="' + id_and_text + '"><span>' + id_and_text + '</span></li>');
		// create a hidden form element so that when the form is submitted, well you know...
		var hidden_input = $('<input type="hidden" name="ctitle" value="' + id_and_text + '"/>');
		// append the input to the form (which form?!)
		$('form').append(hidden_input);
		// setup the remove behaviors
		applyCollectionTitleRemove(id_and_text, list_item);
		// hide so it can fade in...
		list_item.hide();
		// append it to the selected titles view...
		$('#selectedCollectionTitles').append(list_item);
		// now fade it in
		$(find_string).fadeIn();
	})
}


/* This (hopefully) pulls together and makes available the individual Category Titles, pulled from teiHeaders */
function initCategoryTitleSelect(){
	var $=jQuery;
	
	// populate the select element...
	$.get('/xtf/search?browse-subjects-list=true', function(data){
		$('#categoryTitles option').html('All Subjects');
		var all = $('li.subject a', data);
		$(all).each(function(){
			var v=$(this).html();
			$('#categoryTitles').append('<option value="' + v + '">' + v + '</option>');
		});
	})
	function applyCategoryTitleRemove(id_and_text, list_item){
		// apply a click handler so that items can be removed
		$('span', list_item).click(function(){
			// remove the hidden input element
			$('input[value*=' + id_and_text + ']').remove();
			// fade out nicely and remove
			$(this).parent().fadeOut(function(){
				$(this).remove();
			});
		});
	}
	
	// apply remove behaviors to the currently applied collection titles
	// go thru each li item
	$('#selectedCategoryTitles li').each(function(){
		var me = $(this)
		var id = me.attr('id')
		var related_input_element = $('input[value*=' + id + ']');
		applyCategoryTitleRemove(id, me);
	});
	
	// apply a "change" handler to the select that adds the facet titles to the form/view
	$('#categoryTitles').change(function(){
		// grab the text of the option value selected
		var id_and_text = $(this).val() + '';
		// for some ODD reason, finding a node with an exact #id of id_and_text doesn't work...
		var find_string = '[id*=' + id_and_text + ']';
		// see if it's already been added...
		
		if( $(find_string).length != 0){
			// already added, return...
			return;
		}
		// create a list element to display the selected value...
		var list_item = $('<li id="' + id_and_text + '"><span>' + id_and_text + '</span></li>');
		// create a hidden form element so that when the form is submitted, well you know...
		var hidden_input = $('<input type="hidden" name="catTitle" value="' + id_and_text + '"/>');
		// append the input to the form (which form?!)
		$('form').append(hidden_input);
		// setup the remove behaviors
		applyCategoryTitleRemove(id_and_text, list_item);
		// hide so it can fade in...
		list_item.hide();
		// append it to the selected titles view...
		$('#selectedCategoryTitles').append(list_item);
		// now fade it in
		$(find_string).fadeIn();
	})
}

// the next two functions are for the View Examples area
function initExampleCtitleSelect(){
        var $=jQuery;
        
        function applyExampleCtitleRemove(id_and_text, list_item){
            // apply a click handler so that items can be removed
            $('span', list_item).click(function(){
                // fade out nicely and remove
                $(this).parent().fadeOut(function(){
                $(this).remove();
            });
        });
    }
    // apply remove behaviors to the currently applied collection titles
    // go thru each li item
    $('.selectedExampleCtitles li').each(function(){
        var me = $(this)
        var id = me.attr('id')
        applyExampleCtitleRemove(id, me);
    });
    // apply a "change" handler to the select that adds the facet titles to the form/view
    $('#ctitles').change(function(){
        // grab the text of the option value selected
        var id_and_text = $(this).val() + '';
        // for some ODD reason, finding a node with an exact #id of id_and_text doesn't work...
        var find_string = '[id*=' + id_and_text + ']';
        // see if it's already been added...
	      
        if( $(find_string).length != 0){
            // already added, return...
            return;
        }
        // create a list element to display the selected value...
        var list_item = $('<li id="' + id_and_text + '"><span>' + id_and_text + '</span></li>');
        // setup the remove behaviors
        applyExampleCtitleRemove(id_and_text, list_item);
        // hide so it can fade in...
        list_item.hide();
        // append it to the selected titles view...
        $('.selectedExampleCtitles').append(list_item);
        // now fade it in
        $(find_string).fadeIn();
    })
};

function initExampleCatTitleSelect(){
        var $=jQuery;
        
        function applyExampleCatTitleRemove(id_and_text, list_item){
            // apply a click handler so that items can be removed
            $('span', list_item).click(function(){
                // fade out nicely and remove
                $(this).parent().fadeOut(function(){
                $(this).remove();
            });
        });
    }
    // apply remove behaviors to the currently applied collection titles
    // go thru each li item
    $('#selectedExampleCatTitles li').each(function(){
        var me = $(this)
        var id = me.attr('id')
        applyExampleCatTitleRemove(id, me);
    });
    // apply a "change" handler to the select that adds the facet titles to the form/view
    $('#catTitles').change(function(){
        // grab the text of the option value selected
        var id_and_text = $(this).val() + '';
        // for some ODD reason, finding a node with an exact #id of id_and_text doesn't work...
        var find_string = '[id*=' + id_and_text + ']';
        // see if it's already been added...
	      
        if( $(find_string).length != 0){
            // already added, return...
            return;
        }
        // create a list element to display the selected value...
        var list_item = $('<li id="' + id_and_text + '"><span>' + id_and_text + '</span></li>');
        // setup the remove behaviors
        applyExampleCatTitleRemove(id_and_text, list_item);
        // hide so it can fade in...
        list_item.hide();
        // append it to the selected titles view...
        $('#selectedExampleCatTitles').append(list_item);
        // now fade it in
        $(find_string).fadeIn();
    })
};



/* And now THIS pulls together and makes available the individual CENTER Titles, pulled from teiHeaders. 
   Really however, this is hardwired to just do Dewey. Likely have to create initDeweyTitleSelect etc etc to 
   make this work for more than one Center. */
function initCenterTitleSelect(){
var $=jQuery;

// populate the select element...
$.get('/xtf/search?browse-center-dewey=true', function(data){
		$('#centerTitles option').html('Select Title(s)');
		var all = $('div.collectionShortTitle a', data);
		$(all).each(function(){
			var v=$(this).html();
			$('#centerTitles').append('<option value="' + v + '">' + v + '</option>');
		});
	})

function applyCenterTitleRemove(id_and_text, list_item){
// apply a click handler so that items can be removed
$('span', list_item).click(function(){
// remove the hidden input element
$('input[value*=' + id_and_text + ']').remove();
// fade out nicely and remove
$(this).parent().fadeOut(function(){
$(this).remove();
});
});
}

// apply remove behaviors to the currently applied collection titles
// go thru each li item
$('#selectedCenterTitles li').each(function(){
var me = $(this)
var id = me.attr('id')
var related_input_element = $('input[value*=' + id + ']');
applyCenterTitleRemove(id, me);
});

// apply a "change" handler to the select that adds the facet titles to the form/view
$('#centerTitles').change(function(){
// grab the text of the option value selected
var id_and_text = $(this).val() + '';
// for some ODD reason, finding a node with an exact #id of id_and_text doesn't work...
var find_string = '[id*=' + id_and_text + ']';
// see if it's already been added...

if( $(find_string).length != 0){
// already added, return...
return;
}
// create a list element to display the selected value...
var list_item = $('<li id="' + id_and_text + '"><span>' + id_and_text + '</span></li>');
// create a hidden form element so that when the form is submitted, well you know...
var hidden_input = $('<input type="hidden" name="ctitle" value="' + id_and_text + '"/>');
// append the input to the form (which form?!)
$('form').append(hidden_input);
// setup the remove behaviors
applyCenterTitleRemove(id_and_text, list_item);
// hide so it can fade in...
list_item.hide();
// append it to the selected titles view...
$('#selectedCenterTitles').append(list_item);
// now fade it in
$(find_string).fadeIn();
})
}

// the next two functions are for the View Examples area
function initExampleCtitleSelect(){
var $=jQuery;

function applyExampleCtitleRemove(id_and_text, list_item){
// apply a click handler so that items can be removed
$('span', list_item).click(function(){
// fade out nicely and remove
$(this).parent().fadeOut(function(){
$(this).remove();
});
});
}
// apply remove behaviors to the currently applied collection titles
// go thru each li item
$('.selectedExampleCtitles li').each(function(){
var me = $(this)
var id = me.attr('id')
applyExampleCtitleRemove(id, me);
});
// apply a "change" handler to the select that adds the facet titles to the form/view
$('#ctitles').change(function(){
// grab the text of the option value selected
var id_and_text = $(this).val() + '';
// for some ODD reason, finding a node with an exact #id of id_and_text doesn't work...
var find_string = '[id*=' + id_and_text + ']';
// see if it's already been added...

if( $(find_string).length != 0){
// already added, return...
return;
}
// create a list element to display the selected value...
var list_item = $('<li id="' + id_and_text + '"><span>' + id_and_text + '</span></li>');
// setup the remove behaviors
applyExampleCtitleRemove(id_and_text, list_item);
// hide so it can fade in...
list_item.hide();
// append it to the selected titles view...
$('.selectedExampleCtitles').append(list_item);
// now fade it in
$(find_string).fadeIn();
})
};

function initExampleCatTitleSelect(){
var $=jQuery;

function applyExampleCatTitleRemove(id_and_text, list_item){
// apply a click handler so that items can be removed
$('span', list_item).click(function(){
// fade out nicely and remove
$(this).parent().fadeOut(function(){
$(this).remove();
});
});
}
// apply remove behaviors to the currently applied collection titles
// go thru each li item
$('#selectedExampleCatTitles li').each(function(){
var me = $(this)
var id = me.attr('id')
applyExampleCatTitleRemove(id, me);
});
// apply a "change" handler to the select that adds the facet titles to the form/view
$('#catTitles').change(function(){
// grab the text of the option value selected
var id_and_text = $(this).val() + '';
// for some ODD reason, finding a node with an exact #id of id_and_text doesn't work...
var find_string = '[id*=' + id_and_text + ']';
// see if it's already been added...

if( $(find_string).length != 0){
// already added, return...
return;
}
// create a list element to display the selected value...
var list_item = $('<li id="' + id_and_text + '"><span>' + id_and_text + '</span></li>');
// setup the remove behaviors
applyExampleCatTitleRemove(id_and_text, list_item);
// hide so it can fade in...
list_item.hide();
// append it to the selected titles view...
$('#selectedExampleCatTitles').append(list_item);
// now fade it in
$(find_string).fadeIn();
})
};





/*

*/
function initAccordionMenu(){
	//on page load, hide the ajax loading image
	$('.ajaxLoader').hide();
	// re-usable accordion code... gets called below.
	//   "link" is a jQuery "a.accordionLink" tag object
	//   "currentTocTree" is a jQuery "div.tocTree" object
	function doAccordionThing(link, currentTocTree, no_slide){
		// hide the existing accordion item
		if(no_slide){
			$('.accordionized').show().removeClass('accordionized');
		}else{
		           //commenting out the next line allows more than one accordion facet to be open at once
			//$('.accordionized').slideUp('normal').removeClass('accordionized');
		}
		// append the new one to the links' parent
		link.parent().append(currentTocTree);
		// make a new variable, referencing the newly appended toc (Safari needs this)
		var newTocTree = $('.tocTree', link.parent());
		// hide it
		newTocTree.hide(); // needed in Safari for smooth transition
		// now slide it down
		if(no_slide){
			newTocTree.show();
		}else{
			newTocTree.slideDown(500);
		}
		
		// add the class so that other accordion menu calls
		// will know that there is a previously activated one (they'll close it up)
		newTocTree.addClass('accordionized');
		
		// handle the sub expand/collapse using hackety magic
		$('a.tocExpandCollapseLink', newTocTree).click(function(){
			// need to pass in fragment_id=toc - otherwise loading takes too long for some collections
			$.get($(this).attr('href') + '&fragment_id=toc', function(data){
				var expanded_content = $(data);
				//var found = $('.toc-line a[href*="toc.id=;"]', expanded_content);
				var subToc = $('.tocTree', expanded_content);
				$('.tocTree', link.parent()).remove();
				link.parent().append(subToc);
				doAccordionThing(link, subToc, true);
			});
			return false;
		});
	}
	
	// find all accordion links - a.accordionLink
	$('a.accordionLink').click(function(){
		// make jQueryified reference
		var link=$(this);
		// grab the div.tocTree from the links' parent
		var tocTree=$('.tocTree', link.parent());
		// if the .tocTree is already an active accordion item... (has a class of "accordionized")
		if( tocTree.hasClass('accordionized') ){
			// slide it up
			tocTree.slideToggle();
			// remove the class
			tocTree.removeClass('accordionized');
			// return false to prevent link from being followed
			return false;
		}
		// here we are... this link does not have an active/accordionized .tocTree
		// shortcut for href value
		var href = link.attr('href');
		
		// if there is a .tocTree in the DOM for this link (but not the active "accordionized" item)
		if( tocTree.length==1 ){
			// load from "cache" - do the accordion thing...
			doAccordionThing(link, tocTree);
		}else{
			// make an ajax request - turn the loading image on...
			$(link).parent().append( $('.ajaxLoader').show() );
			// pass in fragment_id=toc here as extra param.
			// the teiDocFormatter.xsl stylesheet will
			// then only build the tocTree.
			// - reduces the processing for the remote call
			// - reduces the amount of data being returned here
			$.get(href, {'fragment_id':'toc'}, function(data){
				// hide the associated loading image
				$('.ajaxLoader', link.parent()).hide();
				// make a jQuery object out of the loaded .tocTree element
				var newTocTree = $('div.submenu li div.tocTree', data);
				// do the accordion thing
				doAccordionThing(link, newTocTree);
			})
		}
		return false;
	})
	
	
}
