//this function could be optimized to only handle parts of the menu which need handlers added instead of unbinding/rebinding all each time
//however, it doesn't seem to discernably affect execution time
function menuBehavior() {
	jQuery("#referenceList li").unbind('click');
	//drop down menu behavior
	jQuery("#referenceList li").click(
		function () {
			jQuery(this).children("img:nth-child(2)").toggle();
			jQuery(this).children("img:first-child").toggle();
			
			if(jQuery(this).children("ul:hidden").length) {
				//jQuery(this).children("ul").show("fast");
				jQuery(this).children("ul").show();
			}
			else {
				//jQuery(this).children("ul").hide("fast");
				jQuery(this).children("ul").hide();
			}
			return false;
		}
	);
}

jQuery(document).ready(
	function() {
		setTimeout ( "refInit()", 100 );
	}
);
function refInit() {
		//initialize menu
		//jQuery("#referenceList").hide();
		//jQuery("#refList-div").append('<div id="refLoading">Loading...</div>');
		jQuery("#referenceList li ul").hide();
		jQuery("#refLoading").hide();
		jQuery("#referenceList").show();
		myBehaviors = new oAjaxAttacher(
			'#referenceList',
			'#referenceTopicPanel',
			'#main',//'#',
			".messages:contains('updated'), .messages:contains('created'), .messages:contains('deleted')",//'.messages',
			['#page', '#pageType', '#pageNode', '#pageNodeType'],
			[collapseAutoAttach, activeselectAutoAttach, uploadAutoAttach,optionEmulationInit],
			".messages:contains('updated'), .messages:contains('created'), .messages:contains('deleted')",
			refTrigger,
			"Loading...",
			{'topicLink' : '#referenceTopicPanel'}, //specific filters(value) for links with classes(key)
			{0:'external'}	//exclude these classes from ajax loads
		);
		myBehaviors.linkTarget = jQuery(myBehaviors.linkTarget);
		myBehaviors.linkSource = jQuery(myBehaviors.linkSource);
		attachLinksToTarget(myBehaviors.linkSource, myBehaviors);
		
		searchFormBehavior = new oAjaxAttacher(
			'#searchForm',
			'#referenceTopicPanel',
			'#main',
			'#searchResults',
			['#page', '#pageType', '#pageNode', '#pageNodeType'],
			[collapseAutoAttach, activeselectAutoAttach, uploadAutoAttach],
			".messages:contains('updated'), .messages:contains('created'), .messages:contains('deleted')",
			refTrigger,
			"Loading...",
			{},
			{0 : 'external'}	//exclude these classes from ajax loads
		);
		searchFormBehavior.linkTarget = jQuery(searchFormBehavior.linkTarget);
		searchFormBehavior.linkSource = jQuery(searchFormBehavior.linkSource);
		attachSubmitsToTarget(searchFormBehavior.linkSource, searchFormBehavior);
		
		
		timelyTopicsBehavior = new oAjaxAttacher(
			'#timelyTopics',
			'#referenceTopicPanel',
			'#main',
			'.messages',
			['#page', '#pageType', '#pageNode', '#pageNodeType'],
			[collapseAutoAttach, activeselectAutoAttach, uploadAutoAttach],
			".messages:contains('updated'), .messages:contains('created'), .messages:contains('deleted')",
			refTrigger,
			"Loading...",
			{},
			{0:'external'}	//exclude these classes from ajax loads
		);
		timelyTopicsBehavior.linkTarget = jQuery(timelyTopicsBehavior.linkTarget);
		timelyTopicsBehavior.linkSource = jQuery(timelyTopicsBehavior.linkSource);
		attachLinksToTarget(timelyTopicsBehavior.linkSource, timelyTopicsBehavior);
//		oBindBehaviors.linkTarget = jQuery(oBindBehaviors.linkTarget);
//		oBindBehaviors.linkSource = jQuery(oBindBehaviors.linkSource);
//		oBindBehaviors.attachLinksToTarget(oBindBehaviors.linkSource);
//		var searchForm = jQuery('#searchForm');
//		oBindBehaviors.attachSubmitsToTarget(searchForm, '#searchResults');
		menuBehavior();
	}
//);

var listState;
var listStateVisible;
function saveListState(selector) {
	//listState = jQuery('#referenceList :hidden');
	//listStateVisible = jQuery('#referenceList :visible');
	listState = jQuery(selector+' :hidden');
	listStateVisible = jQuery(selector+' :visible');
}

function restoreListState() {
	var selector;
	for(var i in listState) {
		selector = '#' + listState[i].id;
		jQuery(selector).hide();
	}
	for(var i in listStateVisible) {
		selector = '#' + listStateVisible[i].id;
		jQuery(selector).show();
	}
}

var refTrigger = function (scope, oOptions) {
	//jQuery("*",oOptions.linkSource).unbind();
	var cssId = aaLinkId.split('_');
	saveListState("#refCenter_"+cssId[1]);
	//jQuery("#referenceList").html('Loading...');
	jQuery("#refLoading").show();
	jQuery.ajax({
		oOptions : oOptions,
		url: '/reference',
		data: 'menu=1&linkId='+aaLinkId,
		dataType:"html",
		complete: function(res, status) {
			if ( status == "success" || status == "notmodified" ) {
				//var responseText = res.responseText;
			
				//Hide the link target to our manipulations to it do not look messy.
				//jQuery("#referenceList").hide();
				//var div = document.createElement('div');
				//var text = document.createTextNode(res.responseText);
				//div.appendChild(text);
				//document.getElementById('referenceList').innerHTML = res.responseText;
				var cssId = aaLinkId.split('_');
				if(res.responseText == '') {
					//means we're deleting a category
					jQuery("#refCenter_"+cssId[1]).remove();
				}
				else {
					var temp = jQuery("<div/>").prepend(res.responseText);
					if(cssId[1] == 'new') {
						
					}
					jQuery("#refCenter_"+cssId[1]).html(jQuery("#refCenter_"+cssId[1],temp).html());
				}
				
				jQuery("#refLoading").hide();
				temp = undefined;
				/*
				//Store the response in a temporary jQuery object so we can more easily operate on it
				//var temp = jQuery("<div/>").prepend(res.responseText.replace(/<script(.|\s)*?\/script>/g, ""));
				//res = undefined;
				//delete res;
							
							
				//Filter the html response by the designated responseFilter.  If that element is not found, simply inject all the HTML
				if(jQuery('#referenceList', temp).length) {
					jQuery("#referenceList").html(jQuery('#referenceList', temp).html());
				}
				else {
					jQuery("#referenceList").html(temp.html());
				}
				temp = undefined;	
				
				//call other js functions that may need to responsd to the new html
				for(var i in this.oOptions.jsResponseCallbacks) {
					this.oOptions.jsResponseCallbacks[i]();
				}
				*/
				menuBehavior();
				restoreListState();
				listState = undefined;
				listStateVisible = undefined;
				jQuery("#referenceList").show();
				//attachLinksToTarget(jQuery("#referenceList"), this.oOptions);	
				if(res.responseText){
					//if we didn't just delete a category (which yields no response) attach links to the part of the menu that was just refreshed
					attachLinksToTarget(jQuery("#refCenter_"+cssId[1]), this.oOptions);	
				}
				
			}
			else {
				jQuery("#referenceList").html("Error loading page, please try again later.")
			}
		}
	});
}