(function($){
	$.fn.erbHelpWizard = function(options,etc){
		var _self = this;
		
		// main 
		_self.each(function(){
			var o = _processArgs(this, options, etc);
			
			if(typeof o == 'boolean'){
				/**
				 * a bool will only be returned if we are invoking an api method
				 * in which case processArgs handles invoking that method
				 */
				
				return o;
			}
			// merge args to the defaults
			o = $.extend({}, $.fn.erbHelpWizard.defaults, o);
			
			// everything after this point expects the jQuery version of the element
			_loadData($(this), o);
		});
		
		return _self;
		
		// private 
		
		function _processArgs(c, o, v){
			
			if(o === undefined || o === null){
				o = {};
			}
			
			if(typeof o == 'string'){
				// public api
				
				switch(o){
					case 'reset':
					case 'destory':
						return _reset($(c), v||{});
					default:
						return {'section': o};
				}
			} 
			return o;
		}
		
		function _loadData(wizardInstance, opt){
			$.ajax({
				"url": opt.xmlpath,
				"dataType": 'xml',
				"error": function(req, statText){
					wizardInstance.data('dataError', statText);
					_init(wizardInstance);
				},
				"success": function(xmlData){
					wizardInstance.data('decisionSchema', $(xmlData));
					_init(wizardInstance, opt);
				}
			});
		}
		
		function _reset(wizardInstance, opt){
			if(wizardInstance.data('isInit') === true){
				opt = opt||{};
				var newOptions = _processArgs(opt);
				var oldOptions = wizardInstance.data('options');
				opt = $.extend(oldOptions, newOptions);
				
				if(opt.resetEvent != null && oldOptions.resetEvent != null){
					wizardInstance.unbind(oldOptions.resetEvent);
				}
				wizardInstance.html(wizardInstance.data('initialContent'));
				_init(wizardInstance, opt);
				return true;
			}
			
			return false;
			
		}
		
		function _init(wizardInstance, opt){
			var data = wizardInstance.data('decisionSchema');
			var dataError = wizardInstance.data('dataError');
			if(!data){
				
				return false;
			}
			
			if(!wizardInstance.data('options')){
				// we need to store thes for context aware global access
				wizardInstance.data('options', opt);
			}
			
			var currentChoice;
			
			if(!wizardInstance.data('decisionTree')){
				currentChoice = data.find('decisionTree[section='+opt.section+']');
				wizardInstance.data('decisionTree', currentChoice);
				wizardInstance.data('currentChoice', currentChoice);
				/**
				 * we will be replacing all this on the fly so we need to store the origanl 
				 * content for resetting later
				 */
				wizardInstance.data('initialContent', wizardInstance.html());
			} else {
				currentChoice = wizardInstance.data('decisionTree'); 
				wizardInstance.data('currentChoice', currentChoice);
			}
			
			var linkSelector = 'a.help-wizard-choice';
			
			var links = $(linkSelector, wizardInstance);
			//console.log(links.filter('.help-wizard-update').click(function(){alert('Have handler!');}));
			$('a.help-wizard-update').live('click',
	        function(e){
	          e.preventDefault();
	          _updateChoices(e.target, wizardInstance); 
	          return false;
	      });
			/*$('a.help-wizard-update', links).live('click',
				function(e){
					e.preventDefault();
					_updateChoices(e.target, wizardInstance); 
					return false;
			});*/
			
			// set up our click handlers...
			_assignLinkData(links, wizardInstance);

			wizardInstance.data('isInit', true);
		}
		
		function _assignLinkData(links, wizardInstance){
			links.each(function(index){
				var contextSelector = '> choice:eq('+index+')';
				var choice = wizardInstance.data('currentChoice').find(contextSelector);
				$(this).data('xmlContext', choice);
			});
			
			return links;
		}
		
		function _updateChoices(domChoice, wizardInstance){
			var currentChoice = $(domChoice).data('xmlContext');
			var opt = wizardInstance.data('options')||{};
			
			
			wizardInstance.data('currentChoice', currentChoice);

			var choices = currentChoice.find('> choice');

			
			if(choices.length > 0){
				var hasContainerDecoration = false;
				if(typeof opt.decorators.container != 'undefined'){
					var container = $(opt.decorators.container);
					hasContianerDecoration = true;
				} else {
					var container = $('<div></div>');
				}
				
				$.each(choices, function(i){
					var choiceTemplate;
					var dataNode = $(this); // the xml node with the data
					
					if(typeof opt.decorators.choice == 'undefined'){
						choiceTemplate = '<a class="help-wizard-choice"></a>'; // default decorator is nothing
					} else {
						choiceTemplate = opt.decorators.choice.replace(
							/[%]choice[%]/, 
							'<a class="help-wizard-choice"></a>'
						);
					}
					
					var url = dataNode.find('> url');
					var label = dataNode.find('> label');
					var choice = $(choiceTemplate);
					var link = choice.is('a') ? choice : $('a', choice);
					
					link.attr('href', (url.length == 1 ? url.text() : '#')
					).addClass((url.length == 1 ? 'help-wizard-endpoint' : 'help-wizard-update')
					).text(label.text());
					
					$(choice).appendTo(container);
				});
				
				// associate the proper xml data to the links
				_assignLinkData($('a', container), wizardInstance);

				if(!hasContainerDecoration){
					container = $(container).children();
				}
				
				wizardInstance.html(container);
				return true;
			} else {
				return false;
			}	
		}
	};
	
	$.fn.erbHelpWizard.defaults = {
		"section": "parents", // the section attribute value for the decsicionPath element to be accessed
		"decorators": {}, // a decorator template like <a href="%href%" class="help-wizard-choice">%label%</a> u can use one for "container" and another for "choice"
		"xmlpath": "/uploads/help_wizard/helpconfig.xml", // the url to the xml file
		"resetEvent": null
	};
	
})(jQuery);
