/*****
Changelog:
2011.12.08: v1.3 CRE-4784, CRE-4721 (ddi_669)
- Added call to initAnimation() to allow for animation add on scripts
- Fixed "form jumping" issue
- Updated progress bar functions to call css classes instead of id
- Updated createProgressBar() and added attachment argument

2012.01.05: v1.4 CRE-4825 (ddi_671)
- Updated for new page ddi_671
- Updated default variable values
- Moved Validation related functions to the validation script (validateForm_degreesInfo-3pageU_01.js)
- Added support for server side validation errors. Form flow will start with the first question that has error text
****/


/* Defaults */
var show_progress_bar = true;
var show_back_next = true;
var show_step_edit = false;
var show_collapsable_steps = false;
var auto_hide_continue_button = true;
var show_continue_button_on_back = false;
var progress_bar_attach = '#form_navigation';
var progress_bar_class = 'progress_bar_yellow';

$(document).ready(function() {
	if($('body').hasClass('page1')){	
		$('#container_form').css('visibility','hidden');
		showAosFields();
	    showSubAosFields();
	}
	
	if (errors && errors.length > 0) {
		auto_hide_continue_button = false;
	}
});


$(window).load(function() {

	var body = $('body');

	if(!body.hasClass('pageMatchExclusive')){
		
		if(body.hasClass('page1')){
			
			//Counter Variables
			window.currentQuestion = 0;
			window.currentStep = 1;
			window.totalQuestionGroups = 0;
			window.totalQuestions = 1;
			window.totalFilterSteps = 1;
			
			//If there are server validation errors
			//just show all the questions with an issue
			if (errors && errors.length > 0) {
				$('form[name=form1]').prepend('<div class="c_step" id="c_step_1"><div class="q_group" id="q_group_0"></div></div>');
				
				$('.container_question').css('display','none');
				$('.container_sub_question').css('display','block');
				$('#div_PAGE_1_SUBMIT_1').css('display','none');
				$('#div_DDI_STEP_TWO').css('display','block');
				$('#div_PAGE_1_SUBMIT_2').css('display','block');
				$('.error_message_inline').each(function(){
					if($(this).text() != ''){
						var container_question = $(this).closest('.container_question');
						if((container_question.attr('id')).indexOf('AOS') > -1){
							$(this).closest('.container_question').css('display','block')
							$('.group_aos').appendTo($('#q_group_0'));
						}else{
							$(this).closest('.container_question').css('display','block').appendTo($('#q_group_0'));
						}
						
					}
				});
			}else{
				//Create the seamless flow
				if(show_progress_bar === true || show_back_next === true){
					$('form[name="form1"]').before('<div id="form_navigation"></div>');
				}

				filterUICreate();

				if(show_progress_bar === true){
					createProgressBar(progress_bar_class, progress_bar_attach);
				}

				if(auto_hide_continue_button === true){
					initAutoHide();
				}

				if(show_collapsable_steps === true){
					$('#container_form').attr('class','form_step_1');
				}

				if(typeof initAnimation == 'function'){
					initAnimation();	
				}

				showQuestionGroup(0);
				$('#c_step_1').css('display','block');
			}
			
		}
		
		initializeMilitaryAffiliate(window.document.form1);
		$('#container_form').css('visibility','visible');
	}
	
	/*body.page1 is set to display:none in the default css style
	so that the page can be rendered completely before it is displayed */
	body.css('visibility','visible');

});


/***	
Fixes a bug in Firefox where
select menu elements are given arbitrary values
if the user clicks back or refreshes the page
***/
$(document).ready(function() {
    if($.browser.mozilla){
         $("form").attr("autocomplete", "off");
	}
});


/***
  Override the click event on the
  collapsable edit button
***/
$(document).ready(function(){
	$('#div_DDI_STEP_ONE_EDIT a').click(function(){
		//window.currentStep = 1;
		showQuestionGroup(0);
		updateStepIndicator();
	});
});



/***
This maps the entries in the component variation to their
actual html element identifier
Format is variation id : html id
***/
var questionMap = {
	'military':'#div_DDI_MILITARYAFFILIATE_01',
	'aos':'.group_aos',
	'email':'#div_EMAIL_01',
	'zip':'#div_ZIP_01',
	'citizen':'#div_USCITIZEN_01',
	'start_period':'#div_DDI_START_PERIOD_01',
	'education_level':'#div_DDI_EDUCATION_01',
	'grad_year':'#div_DDI_GRADYEAR_01',
	'age':'#div_DDI_AGE_01'
};


/***	
These are the questions that can be used
in combination with the auto-hide option
If the auto-hide option is true, these quesitons
will get click() events as long as they aren't
grouped with other questions
***/
var autoHideButtonFor = ['#NonMilitaryAffiliate','#DDI_MILITARYBRANCH_01','#Citizen','#country_usa','#country_can','#DDI_START_PERIOD_01','#DDI_EDUCATION_01','#DDI_GRADYEAR_01','#DDI_AGE_01'];


function filterUICreate(){
	
	if($('#div_PAGE_1_SUBMIT_1').outerHeight(true) > $('#div_PAGE_1_SUBMIT_2').outerHeight(true)){
		var buttonHeight = $('#div_PAGE_1_SUBMIT_1').outerHeight(true);
	}else{
		var buttonHeight = $('#div_PAGE_1_SUBMIT_2').outerHeight(true);
	}
	
	var formElement = $('form[name="form1"]');

	/* Loop through each item in the variation question order */
	for(var k in question_order){ 
		formElement.append('<div class="c_step" id="c_step_'+window.totalFilterSteps+'"></div>');
		var c_step = $('#c_step_'+window.totalFilterSteps);
		c_step.css('display','block');
		
		if(question_order[k] != null){
			var group_height_max = 0;
			
			for(var i=0; i<question_order[k].length; i++){	
				c_step.append('<div class="q_group" id="q_group_'+window.totalQuestionGroups+'"></div>');
				var q_group = $('#q_group_'+window.totalQuestionGroups);
				var group_total_q = 0;
				
				
				for(var j=0; j<question_order[k][i].length; j++){
					q_element = $(questionMap[question_order[k][i][j]]);
					if(q_element.length > 0){
						q_group.append(q_element);
					}else if($('#'+question_order[k][i][j]).length > 0){
						q_element = $('#'+question_order[k][i][j]);
						q_group.append(q_element);
						q_element.css('display','block');
						if(q_element.attr('data-buttonHide') == "true"){
							autoHideButtonFor.push('#' + q_element.attr('id'));
						}
					}
					
					group_total_q++;
					window.totalQuestions++;
				}
				
				/*
				  Find out what the tallest question is and set it to
				  group_height_max so that the step container's min-height
				  property can be set to that size and prevent
				  vertical display jump during a seamless flow 
				*/
				var q_group_height = 0;
				
				/*
				  Determine if there are any hidden sub-questions
				  and include their height in the measurement
				*/
				/*
				if($('.container_sub_question', q_group).length > 0){
					q_group_height = q_group.outerHeight(true);
					$('.container_sub_question', q_group).each(function(){
						if($(this).css('display') == 'none'){
							q_group_height += $(this).outerHeight(true);
						}
					});
				}else{
					q_group_height = q_group.outerHeight(true);
				}
				*/
				
				q_group_height = q_group.outerHeight(true);
				
				/*  Determine if this is the tallest question so far */
				if(q_group_height > group_height_max){
					group_height_max = q_group_height;
				}
				
				/* Set reference properties of the question group to be used later */
				q_group.data('question_answered',false);
				q_group.data('group_total_q',group_total_q);
				q_group.data('group_progress_count',window.totalQuestions);	
				q_group.data('group_step',window.totalFilterSteps);
				q_group.data('group_num',window.totalQuestionGroups);				
				q_group.css('display','none');
			
				window.totalQuestionGroups++;
			}
			
			/* Set the step height equal to the tallest question */
			var stepHeight = (group_height_max+buttonHeight)+'px';
			c_step.attr('style', 'height: auto !important; height:'+stepHeight+'; min-height:'+stepHeight);
			c_step.css('display','none');
			
			window.totalFilterSteps++;
		}
	}
	
	/* Append the continue and submit buttons to the first step */
	$('#c_step_1').append($('#div_PAGE_1_SUBMIT_1'));
	$('#c_step_1').append($('#div_PAGE_1_SUBMIT_2'));
	
	/* Hide the submit button */
	$('#div_PAGE_1_SUBMIT_2').css('display','none');
	
	$('#form_cap_bottom').css('margin','0');
	
	/*
	  If show_back_next property is true, then add the seamless navigation
	  "back/next" links into the page structure
	*/
	if(show_back_next === true){
		var historyNavHtml = '<div id="back_link" class="history_link"><a href="#">&laquo; Back</a></div><div id="forward_link" class="history_link"><a href="#">Forward &raquo;</a></div>';
		$('#form_navigation').prepend('<div id="seamless_nav">'+historyNavHtml+'</div>');
		$('#seamless_nav').height($('#back_link').outerHeight());
		$('#back_link').css('display','none').click(previousQuestion);
		$('#forward_link').css('display','none').click(nextQuestion);
	}
}



function initAutoHide(){
		
	$('.q_group').data('auto_hide_continue_button',false);
	
	$('#Citizen').attr('checked','');
	$('#div_COUNTRY_01').css('display','none');
	
	$.each(autoHideButtonFor, function(k,v){
		$q_group = $(v).closest('.q_group')
		parentQuestionTotal = $q_group.data('group_total_q');
		if(parentQuestionTotal == 1){
			if($(v).attr('type') == 'radio'){
				$(v).click(function(){
					if(v == "#Citizen"){
						hideCountryBasedOnCitizen(window.document.form1);
					}
					nextQuestion();
				});
			}else{
				$(v).change(function(){
					nextQuestion();
				});
			}
			$q_group.data('auto_hide_continue_button',true);
		}	
	});

	showHideContinueButton();
}


function previousQuestion(){
	
	window.currentStep = $('#q_group_'+window.currentQuestion).data('group_step');
	
	if(window.currentQuestion > 0){
		window.currentQuestion--;
		hideQuestionGroup(window.currentQuestion+1);
		showQuestionGroup(window.currentQuestion);
	}
	
	return false;
}

function nextQuestion(){
	//validate
	var isValid = validateQuestionGroup(window.currentQuestion);

	if(!isValid){
		return false;
	}
	
	window.currentStep = $('#q_group_'+window.currentQuestion).data('group_step');
	
	if(window.currentQuestion < window.totalQuestionGroups-1){
		if(show_continue_button_on_back === true){
			$('#q_group_'+window.currentQuestion).data('auto_hide_continue_button',false);
		}
		
		$('#q_group_'+window.currentQuestion).data('question_answered',true);
		window.currentQuestion++;
		hideQuestionGroup(window.currentQuestion-1);
		showQuestionGroup(window.currentQuestion);
	}
	
	return false;
}


function updateSeamlessNav(){
	if(show_back_next === true){

		if(window.currentQuestion == 0){
			$('#back_link').css('display','none');
		}else{
			$('#back_link').css('display','block');
		}

		if($('#q_group_'+window.currentQuestion).data('question_answered') === false){
			$('#forward_link').css('display','none');
		}else{
			$('#forward_link').css('display','block');
		}
	}
}

function updateButtonParent(){
	if(window.totalFilterSteps > 1){
		$('#c_step_'+window.currentStep).append($('#div_PAGE_1_SUBMIT_1'));
		$('#c_step_'+window.currentStep).append($('#div_PAGE_1_SUBMIT_2'));	
	}
}

function updateStepIndicator(){
	if(window.totalFilterSteps > 1){
			
		$('#container_form').attr('class','form_step_'+window.currentStep);
	
		if(window.currentStep == 2 && show_step_edit === true){
			$('#div_DDI_STEP_ONE_EDIT').css('display','block');
		}else{
			$('#div_DDI_STEP_ONE_EDIT').css('display','none');
		}
	}
}

function hideQuestionGroup(groupNum){
	$('#q_group_'+groupNum).css('display','none');
}

function showQuestionGroup(groupNum){
	
	$('#q_group_'+groupNum).css('display','block');
	$('#q_group_'+groupNum+' :input:first:not(:radio)').focus();
	
	if($('#q_group_'+groupNum).data('group_step') != window.currentStep){
		$('#c_step_'+window.currentStep).css('display','none');
		window.currentStep = $('#q_group_'+groupNum).data('group_step');
		
		$('#c_step_'+window.currentStep).css('display','block');
		updateButtonParent();
		updateStepIndicator();
	}
	window.currentQuestion = groupNum;
	progressIndicatorUpdate();
	showHideContinueButton();
	updateSeamlessNav();
}


function showHideContinueButton(){
	//If this is the last question
	//hide the continue button and show the submit button
	if(window.currentQuestion == window.totalQuestionGroups-1){
		$('#forward_link').css('display','none');
		$('#div_PAGE_1_SUBMIT_1').css('display','none');
		$('#div_PAGE_1_SUBMIT_2').css('display','block');
	}else{
		$('#div_PAGE_1_SUBMIT_1').css('display','block');
		$('#div_PAGE_1_SUBMIT_2').css('display','none');
		
		hide_button_this_question = $('#q_group_'+window.currentQuestion).data('auto_hide_continue_button');
		if(auto_hide_continue_button === true && hide_button_this_question === true){
			$('#div_PAGE_1_SUBMIT_1').css('visibility','hidden');
		}else{
			$('#div_PAGE_1_SUBMIT_1').css('visibility','visible');
		}
	}
}


function createProgressBar(css_class, element_parent){
	var progressBarHtml = '<div id="meter" class="'+css_class+'"><div id="div_progress" style="width: 0%;"></div><div id="progress_label">progress</div></div>';
	$(element_parent).prepend(progressBarHtml);
}

function progressIndicatorUpdate(){
	if(show_progress_bar === true){
		if(window.currentQuestion == 0){
			$('#div_progress').css('width','0%');
		}else{
			var progBarPercent = ($('#q_group_'+(window.currentQuestion-1)).data('group_progress_count') / window.totalQuestions)*100;
			$('#div_progress').css('width',progBarPercent+'%');
		}
	}
}
