(function($){$.fn.questionTree=function(options){var opts=$.extend({},$.fn.questionTree.defaults,options);return this.each(function(){var content=$(this).find('.content');var treePath=[];var dataUrl=$(this).data('url');var tree=null;content.empty();content.append('<p class="loading">Loading...</p>');$.getJSON(dataUrl,function(data){tree=data;init();});function init(){content.empty();content.append('<a class="back">Back</a>');treePath=[];treePath.push(tree);content.append(renderQuestion(tree));$(content).off('click','a.back');$(content).off('click','.answers li a');$(content).on('click','a.back',goBack);$(content).on('click','.answers li a',gotoAnswer);updateUi(0);};function renderQuestion(data){console.log('renderQuestion');var question=$('<div class="question"><p>'+data.question+'</p></div>');question.css({width:'100%',height:content.height(),position:'absolute',top:0});var answers=$('<ul class="answers"></ul>');question.append(answers);var answerCount=0;if(data.answer1){answers.append('<li><a href="#" data-a="1">'+data.answer1+'</a></li>');answerCount++;}
if(data.answer2){answers.append('<li><a href="#" data-a="2">'+data.answer2+'</a></li>');answerCount++;}
if(data.answer3){answers.append('<li><a href="#" data-a="3">'+data.answer3+'</a></li>');answerCount++;}
if(answerCount==0){question.addClass('leaf');}
return question;};function gotoAnswer(event){console.log('gotoAnswer');event.preventDefault();var a=$(event.target).data('a');var thisQuestionNode=treePath[treePath.length-1];var nextQuestionNode=thisQuestionNode['answer'+a+'Next'];var width=content.width();var lastQuestion=content.find('.question').last();var nextQuestion=renderQuestion(nextQuestionNode);nextQuestion.css('left',width);content.append(nextQuestion);lastQuestion.animate({'left':-width},opts.speed/2,opts.easing,function(){nextQuestion.animate({'left':0},opts.speed,opts.easing,function(){treePath.push(nextQuestionNode);updateUi()});});};function goBack(){console.log('gotoBack');var thisQuestionElement=$('.question',content).last();var lastQuestionElement=thisQuestionElement.prev();var width=content.width();thisQuestionElement.animate({'left':width},opts.speed,opts.easing,function(){});lastQuestionElement.animate({'left':0},opts.speed,opts.easing,function(){thisQuestionElement.remove();treePath.pop();updateUi();});};function updateUi(speed){if(typeof speed=='undefined'){speed=opts.speed;}
if(treePath.length<=1){$('.back',content).fadeOut(speed);}
else{$('.back',content).fadeIn(speed);}};});};$.fn.questionTree.defaults={speed:400,easing:'easeOutExpo'};})(jQuery);