/**
	Account Expander
	jQuery plug-in
	expands and contracts the accounts in the side column
	@author Michael Turnwall

	Revised by		Date		Summary of changes
	Lane Roathe		06/16/10	[DE392] & [DE1003] Save and restore collapsed state of anchor elements
	Lane Roathe		06/22/10	[DE1411] check window.viewController usage to fix deferred printing
								(Some reports do not have a viewController or attached method)
*/

(function($) {
	
	/** define the plugin */
	$.fn.accountsExpander = function(options)
	{
		// var opts = $.extend({}, $.fn.accountExpander.defaults, options);

		// preserve chaining
		return this.each(function(i)
		{
			var $_accountList = $(this);
			var _aList = $("a",$_accountList);
			_aList.bind("click",function() { clickAction(this); return false; });

			// use jQuery iterator to set start state of known anchors
			// (function passed index & value, 'this' also set to value)
			$.each(_aList, function() {
				var newState;
				if( window.viewController && window.viewController.StateOfAnchor )
					newState = window.viewController.StateOfAnchor( this.title );

				// We are assuming all anchors are of the opened class in the XSLT file, so only update opened ones here
				if( newState && newState == "closed" )
					$(this.parentNode).removeClass("opened").addClass("closed");
			});

			var clickAction = function(linkage) {
				var parent = linkage.parentNode;
				this.subMenu = $("ul",parent);
				blind(250);
				if(parent.className.match(/\bclosed\b/)) {
					changeClass(parent,"closed","opened");
					if( window.viewController && window.viewController.StateOfAnchor )
						window.viewController.SetAnchorState( "opened",linkage.title );
				}
				else if(parent.className.match(/\bopened\b/)) {
					changeClass(parent,"opened","closed");
					if( window.viewController && window.viewController.StateOfAnchor )
						window.viewController.SetAnchorState( "closed",linkage.title );
				}
			};
			
			var changeClass = function(el,oldClass,newClass) {
				$(el).removeClass(oldClass).addClass(newClass);
			};
			
			var blind = function(speed) {
				// this.subMenu.css({opacity:0});
				return this.subMenu.animate({
					opacity: "toggle",
					height: "toggle"
				},speed);
			};
		});
	};
	
})(jQuery);