

// global
var curDepths = new Array();
var arrayPath = new Array();
var startSection = '';

function clickSection(section){
	
	// hide initial image if it's visible
	// then show the requested section
	if ($('.right-box .ct').css('display') != 'none') {
		$('.right-box .ct').fadeOut(300, function() {
			showSection(section, true);
		});
	} else {
		showSection(section, true);
	}
	
}

function showSection(section, trans) {
	
	// make the requested section active, hiding all other sections
	// if trans is true a transition effect will be used (fade in), otherwise none will be used
	
	// if the active section was clicked, do nothing
	if ($('#section' + section).css('display') != 'none') {
		return;
	}
	
	// hide all sections
	$('.get-started').hide();
	
	// show target section
	if (trans) {
		$('#section' + section).fadeIn(400);
	} else {
		$('#section' + section).show();
	}
	
	// would like to fade out previous section and fade in target, need to queue animations - check docs
	
	// store starting section for reporting
	startSection = $(xmldoc).find('section[id=' + section + '] title').text();

	
}

function initSection(section){
	
	arrayPath[section] = new Array();

	$(xmldoc).find('section[id=' + section + ']').each(function(){
		
		title = $(this).find('title').text();
		firstQ = $(this).attr('initialStep');
		descText = $(this).find('body').text();
		bgimage = $(this).find('bgimage').text();
	});


	// build container, title and history list
	
	$('<div class="get-started" style="display:none;" id="section' + section + '"></div>').appendTo('.right-box');
	if (bgimage.length>0) {
		$('<h1 style="background-image:url(' + bgimage + ');">' + title + '</h1>').appendTo('#section' + section);		
	} else {
		$('<h1>' + title + '</h1>').appendTo('#section' + section);		
	}



	// load description from xml
	$("<p>" + descText + "</p>").appendTo('#section' + section);

	// set nav for this section, next disabled for now b/c implementation questions
	$('<div class="nav"><a id="nav-back" href="javascript:navBack(' + section + ');"><img src="images/btn-back.gif" alt="Back" /></a><a id="nav-so" href="javascript:startOver(' + section + ');"><img src="images/btn-startover.gif" alt="Start Over" /></a></div>').appendTo('#section' + section);

	// load first question to depth (slot) 1
	loadQuestion(section,firstQ,1);
	
}


function navBack(section) {
	
	// move to previous question
	
	// if we're not at the first question
	if (curDepths[section] > 1) {
	
		arrayPath[section].pop(); // remove last item from arrayPath
	
//		alert('fade out ' + curDepths[section] + ' fade in ' + (curDepths[section] - 1));
	
		// remove the current question, uncheck all answers from previous question, set current depth to one less

		goToDepth(section,curDepths[section] - 1);

		
	}
	
}

function goToDepth(section, targetDepth) {
	

			$('#section'+section+' #qd'+ curDepths[section]  ).fadeOut(300,function() {

	//			alert('fade in ' + (curDepths[section] -1));
				$('#section' + section + ' #qd' + targetDepth).fadeIn(400);

			});

			$('#section' + section + ' #qd' + targetDepth + ' ul input').attr('checked',false);

			curDepths[section] = targetDepth;

			// update the history list based on new depth
			updateHistory(section);
	
}

function startOver(section) {

	// remove this section, call initSection to rebuild it and then show it (w/ no transition)
//	$('#section' + section).remove();
//	initSection(section);
//	showSection(section, false);
	
	arrayPath[section] = new Array();
	goToDepth(section, 1);
	
	
	
}


function updateHistory(section) {
	
//	alert('cur depth: ' + curDepths[section]);
	
	// adjust the number of completed steps to refelct the current depth 
	
	// remove 'checked' class from all history items, add 'unchecked' class to all history items
//	$('#section'+section+' .history ul li').removeClass('checked').addClass('unchecked');
	
	// for all steps completed up to current question, remove 'unchecked' and add 'checked' classes
//	for (i=1;i<(curDepths[section]);i++) {
//		$('#section'+section+' .history ul li#step'+i).removeClass('unchecked').addClass('checked');
//	}
	
	// update nav also
	
	if (curDepths[section] <= 1) {
		$('#section' + section + ' #nav-so , ' + '#section' + section + ' #nav-back').hide();
	} else {
		$('#section' + section + ' #nav-so , ' + '#section' + section + ' #nav-back').show();		
	}
	
}



function loadQuestion(section, question, depth){



	oldDepth = curDepths[section];
	curDepths[section] = depth;

	if ($('#section' + section + ' #qd' + depth).length > 0) { // question does not already exist (and is hidden)
		$('#section' + section + ' #qd' + depth).remove();
	}
		



	
	$(xmldoc).find('step[id=' + question + ']').each(function(){

		questionText = '';
		pathQuestionText = '';
		questionText = $(this).find('question').text();
		if (questionText.length > 0) {
			pathQuestionText = encodeURIComponent(questionText.replace(/['"]/g,''));
			questionText = '<p class="question q' + depth + '">' + questionText + '</p>';
		}
		
		txtBody = '';
		txtBody = $(this).find('body[type!=after]').text();
		if (txtBody.length > 0) {
			txtBody = '<p class="before">' + txtBody.replace(/\@SECTION\@/g,section) + '</p>';
		}

		txtBody2 = '';
		txtBody2 = $(this).find('body[type=after]').text();
		if (txtBody2.length > 0) {
			txtBody2 = '<p class="after">' + txtBody2.replace(/\@SECTION\@/g,section) + '</p>';
		}

		debugTxt = '';
//		debugTxt = '<small id="debug">Q:' + question + '</small>';
		
		$('#section' + section + ' .nav').before('<div style="display:none;" id="qd' + depth + '">' + debugTxt + txtBody +  questionText + txtBody2 + '<ul class="qq"></ul></div>');
	
		$(this).find('option').each(function(){
			goToQ = $(this).attr('nextstep');
			opt = $(this).text();
			pathOpt = encodeURIComponent(opt.replace(/['"]/g,''));

      if (goToQ == -1) {
      
            $('<li><label><input onclick="addPath('+section+',\''+pathQuestionText+'|'+pathOpt+'\');startOver(' + section + ');" type="radio" name="rad'+section+'-'+question+'" />' + opt + '</label></li>').appendTo('#section' + section + ' #qd' + depth + ' ul.qq');
      
      
      } else {
  
        switch($(this).attr('type')) {
        
          case 'text':
			tempLink = 'upload-form.php?start=' + encodeURIComponent(startSection) + '&path='+encodeURIComponent(arrayPath[section].join('~'));
			opt = opt.replace(/\@UPLOADFORM\@/g,tempLink);
            $('<li class="bulleted"><label>' + opt + '</label></li>').appendTo('#section' + section + ' #qd' + depth + ' ul.qq');
          break;
          
          case 'link':
            $('<li class="bulleted"><label><a href="javascript:addPath('+section+',\''+pathQuestionText+'|'+pathOpt+'\');loadQuestion(' + section + ',' + goToQ + ',' + (depth + 1) + ');">' + opt + '</a></label></li>').appendTo('#section' + section + ' #qd' + depth + ' ul.qq');
          break;
        
          case 'radio':
          default:
            $('<li><label><input onclick="addPath('+section+',\''+pathQuestionText+'|'+pathOpt+'\');loadQuestion(' + section + ',' + goToQ + ',' + (depth + 1) + ');" type="radio" name="rad'+section+'-'+question+'" />' + opt + '</label></li>').appendTo('#section' + section + ' #qd' + depth + ' ul.qq');
          break;
        
        }
        
      }

			
		});

	});


	
	if (depth > oldDepth) {
		$('#section' + section + ' #qd' + oldDepth).fadeOut(300,function() {
			$('#section' + section + ' #qd' + depth).fadeIn(400);		
//					alert('fade out ' + oldDepth + ' fade in ' + depth);
					
		});
	} else {
		$('#section' + section + ' #qd' + depth).fadeIn(400);
//		alert('fade in ' + depth);
	}

	updateHistory(section);
		
}

function addPath(section,text) {
	
	arrayPath[section].push(text);
	
}

function inlineFormSub(section, subBtn) {

	var fail = false;
	$('input, textarea', $(subBtn).parent().parent().parent()).each(function() {
		//alert($(this).attr('name'));
		if ($(this).hasClass('required')) {
			if ($(this).val() == '') {
				fail = true;
				$(this).addClass('missingRequired');
			} else {
				$(this).removeClass('missingRequired');
			}
		}
	});
	
	if (!fail) {

		$.post("inline-form-sub.php", $(subBtn).parent().parent().parent().serialize() + '&start=' + encodeURIComponent(startSection) + '&path='+encodeURIComponent(arrayPath[section].join('~')), function(data){
			$('#section' + section + ' #formarea').html('<ul><li><strong>Thank you for contacting Burkholder\'s Heating and Cooling.  A representative will contact you shortly.</strong></li></ul><br />');		
		});
	
	} else {
		
		alert('Please complete all required fields.');
		
	}
	
}


// cached globally
var xmldoc;

function loadHelpXML(xmlFile) {

	$(document).ready(function() {

	    $.ajax({
	      type: "GET",
	      url: xmlFile,
	      dataType: "xml",
	      success: function(xml) {
	          xmldoc = xml;

				$(xmldoc).find('section').each(function(){
					initSection($(this).attr('id'));
				});				
	        }
	      });

	});
	
}
