var debugging = false; // or true
if (typeof console == "undefined" || typeof console.log == "undefined") var console = { log: function() {} };
else if (!debugging && typeof console != "undefined") console.log = function() {};

// Create our namespaces
Ext.namespace('BLACKLIGHT','BLACKLIGHT.util','BLACKLIGHT.data');


// Any variables or settings that we might want to change later
BLACKLIGHT.config = {
	limitsMenusContainer : '#availableFilters' // JQuery selector string
}


BLACKLIGHT.app = function() {
	
	var $ = jQuery;
	$.ajaxSetup({'timeout':20000});
	var cfg = BLACKLIGHT.config;
	
	/* private methods */
	
	function makeTooltips() {
		/*
		find all elements with a class of tooltipContent
		iterate through
		extract config options from remainder of classes
		create Ext.ToolTip instances using options, insert the HTML of the tooltipContent element
		or get the content via ajax from the title attribute
		*/ 
		new Ext.ToolTip({
			/*
			  This is causing a javascript error in IE - still to be debugged.
			 */
			//target: $('#search .tabNav a[@href=/music]').get(0),
			//html: 'Search only in music',
			//autoHide: true,
		});
		Ext.QuickTips.init();
	}
	
	function makeLimitsMenus() {
		
		var container = $('#availableFilters').get(0);
		
		// make the menus from dl lists in the original html
		$('#availableFilters dl').each(function(i){

			// build the panel html
			var panelHTML = ['<ul class="limitsList menu">'];
			var moreLink, moreLinkHTML, itemsBeforeGrow = 0;
			$('dd',this).each(function(){
				if(this.className == 'moreLink') {
					moreLink = $('a.moreLink',this).get(0).href+'&facet.limit=60&col_len=15';
					moreLinkHTML = $(this).html();
				} else {
					panelHTML.push('<li>'+$(this).html()+'</li>');
					itemsBeforeGrow++;
				}
			});
						
			panelHTML.push('</ul>');
			panelHTML.push(moreLinkHTML);
			var panelHTML = panelHTML.join('\n');
			
			var menu = new BLACKLIGHT.LimitsMenu({
				bodyContents: panelHTML,
				titleContents: $('dt',this).html(),
				moreLink: moreLink,
				itemsBeforeGrow: itemsBeforeGrow,
				baseZIndex: 3
			});

			// add menu to the public limitsMenus array
			pub.limitsMenus.push(menu);
		});

		// strip out all the old <dl> menus
		$('#availableFilters dl.menu').remove();
	}
	
	/*
		Load cover images
		Sample HTML:
		<span class="coverImage">ANYTHING HERE GETS REPLACED BY img TAG</span>
	*/
	
	function loadCoverImages(){
		var isbn = null;
		$('span.coverImage').each(function(i,span){
			var el = $(span);
			var doc_id = el.attr('title'); // comma separated list of bib keys
			$.get('/catalog/' + doc_id + '/image_load', function(data){
				var i = $(data)
				el.html(i);
			});
		});
	}
	
	
	/*
		Bind the availability links to a handler
		
		SAMPLE CSS:
		.hide{display:none;}
		
		SAMPLE HTML:
		<div class="document" id="DocXXX">
			<div>
				<img src="loader.gif" class="ajaxLoader hide"/>
				<a href="#" class="availability">Check Availability...</a>
			</div>
		</div>
	*/
	
	function makeAvailabilityLinks(){
		$('.availability a').click(function(e){
			e.preventDefault();
			var el = $(this);
			el.addClass('hide');
			$('.ajaxLoader', this.parentNode).removeClass('hide');
			var id = el.parents('.document').attr('id').replace(/^Doc/, '');
	
	// TODO: change this path to /availability (remove UVA specific reference) 
	      //          $.get('/catalog/' + id + '/availability',
				          $.get('/catalog/' + id + '/status',
	
				{no_layout:true },
				function(data){
					el.parent().html(data);
				}
			);
		});
	}
	
	function makeBookmarkLinks(){
		$('.addUserBookmarkForm .submitForm').click(function(e){
			e.preventDefault();
			var el=$(this);
			el.parent().ajaxSubmit({
				success:function(){
					el.parent().html('This is in your <a href="/bookmarks">Favorites</a>')
				}
			});
		})
	}
	
	function processConfig() {
		pub.limitsMenusContainer = $(cfg.limitsMenusContainer).get(0);
	}
		
	function init(){
		processConfig();
		makeTooltips();
		makeLimitsMenus();
		loadCoverImages();		
		makeAvailabilityLinks();		
		makeBookmarkLinks();
	}
		
	// public properties and methods
	var pub = {
		limitsMenus : [],
		limitsMenusContainer : {} // eventually set to a DOM node
	}

	Ext.onReady(init);
	
	return pub;
}();
