// Account Selector Javascript
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
// global configuration
// these are defaults with actual values updated on page load
var as_lang = "en";
var as_debug = false;
var as_olb = false;
var as_branch = false;
var as_branch_id = "";
var as_session_id = "";
// number of steps
var as_stepNum = 4;
// current step
var as_step = 1;
// highest step reached, used to set top wayfinding states
var as_step_reached = 0;
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// when page is loaded	
$(document).ready(function()
{
	//alert('document ready, step' + as_step);
	
	// check for the debug string
 	var debug = $.jqURL.get('debug');	
    if (debug != undefined) 
    {
		as_debug = true;
        $("#as_debugsettings").show();
		$("input[name='debug']").val(debug);		
        as_debug_writeline('show debug');
    }
    
	// set language (saves having to get it from the DOM everytime)
	as_lang = $('input:hidden[name=language]').val();
	
    // check for the branch string
    as_branch_id = $.jqURL.get('transit');
    as_session_id = $.jqURL.get('id');
    if (as_branch_id) 
    {
		document.getElementById('branch__id').innerHTML = as_branch_id;
		document.getElementById('session__id').innerHTML = as_session_id;
		as_branch_id = as_branch_id.replace("#top", "");
        as_branch = true;
        as_debug_writeline('show branch');
		// add the compare to non-rbc account option
		$('#as_compare_rbc').append('<option value="O_NL">' + as_string_otheraccount + '</option>');
		// set the branch options		
        as_setBranchMode();
		
		// change the page title
		$('#pagetitle').html(as_string_branchtitle);
		
		// turn off olb mode if branch id is set 
		as_olb = false;
		
		if(document.getElementById('as_cash_atm_rbc,f')){document.getElementById('as_cash_atm_rbc,f').value = 2;}
		if(document.getElementById('as_ppdebit_can,f')){document.getElementById('as_ppdebit_can,f').value = 10;}
		if(document.getElementById('as_bill_selfserve,f')){document.getElementById('as_bill_selfserve,f').value = 2;}
		if(document.getElementById('as_trf_selfserve,f')){document.getElementById('as_trf_selfserve,f').value = 1;}
		if(document.getElementById('as_cash_atm_other,f')){document.getElementById('as_cash_atm_other,f').value = 3;}
		if(document.getElementById('as_trfother_email,f')){document.getElementById('as_trfother_email,f').value = 2;}
		as_initialize_autototal('activity_banking_selfserve_total', new Array('as_cash_atm_rbc', 'as_ppdebit_can', 'as_bill_selfserve', 'as_trf_selfserve', 'as_cash_atm_other', 'as_trfother_email', 'as_payroll'));
		
		if(document.getElementById('as_chq_num,f')){document.getElementById('as_chq_num,f').value = 1;}
		if(document.getElementById('as_bill_branch,f')){document.getElementById('as_bill_branch,f').value = 1;}
		as_initialize_autototal('activity_banking_assisteddebits_total', new Array('as_cash_branch', 'as_chq_num', 'as_bill_branch', 'as_trf_branch','as_chqcert_num','as_drafts_num'));
		
		if(document.getElementById('as_ccard,2')){document.getElementById('as_ccard,2').checked = true;}
		if(document.getElementById('as_ccard_coapp,yn,1')){document.getElementById('as_ccard_coapp,yn,1').checked = true;}
		if(document.getElementById('as_sdb,f,1')){document.getElementById('as_sdb,f,1').checked = true;}
		if(document.getElementById('as_overdraft,yn,1')){document.getElementById('as_overdraft,yn,1').checked = true;}
		if(document.getElementById('as_multiaccts,1')){document.getElementById('as_multiaccts,1').checked = true;}
		if(document.getElementById('as_ccardupsell,yn,1')){document.getElementById('as_ccardupsell,yn,1').checked = true;}
		if(document.getElementById('as_travel,yn,1')){document.getElementById('as_travel,yn,1').checked = true;}
		if(document.getElementById('as_travelchq,1')){document.getElementById('as_travelchq,1').checked = true;}
		if(document.getElementById('as_investing,yn,1')){document.getElementById('as_investing,yn,1').checked = true;}
		if(document.getElementById('as_purchasehome,yn,1')){document.getElementById('as_purchasehome,yn,1').checked = true;}
		if(document.getElementById('transitpreload')){document.getElementById('transitpreload').style.display = '';}	
    }
	
    // initialize olb settings
    as_olb = ($.jqURL.get('olb') != undefined);
    if (as_olb) 
    {
        $('input:hidden[name=olb]').val("1");
		as_debug_writeline('open from olb');
	    var width = 810;
	
	    // non IE
	    if (typeof window.innerWidth != "undefined") 
	    {
	       window.innerWidth = width;
	    }
	    else 
	    {
			// BUG: this IE resize is still incorrect (at least in IE 8). How to get browser *window* height?
			//alert('ie resize ' +  document.documentElement.clientHeight);
			self.resizeTo(width + 20,document.body.offsetHeight); //document.documentElement.clientHeight);
	    }		
		
    }
	
	// see if age is passed in
	var age = $.jqURL.get('age');
    if (age) 
    {
		as_debug_writeline('set age: ' + age);
		//$('input[name=as_age]').val(age);
		$('#as_age_' + age + '').attr('checked', 'checked');
		//as_form.as_age = age;
   }	
	var student = $.jqURL.get('student');
    if (student) 
    {
		as_debug_writeline('set student: ' + student);
		//$("input[name='as_student']").val(student);
		$('#as_student_' + student + '').attr('checked', 'checked');
    }		
    
    // initialize scenario selection
    s = $("input[type=radio][name=scenario]");
    
    // add callback
	if (!as_branch)
    	s.change(as_scenarioSelected);
    
    // enable					
    s.removeAttr('disabled');
	
	// initialize all dynamic questions
	$('input.as_dynamicquestion:checked').each( function ()
	{
		var name = this.name;
		as_SetDynamicQuestion(name);
	});
    
	// setup dynamic question callbacks
	$('input.as_dynamicquestion').click(as_DynamicQuestionHandler);
	
    
	as_toggleIcon('activity_banking_assisteddebits', 'activity_banking_assisteddebitsicon', as_branch ? true : true);
	as_toggleIcon('activity_banking_selfserve','activity_banking_selfserveicon', true);
    as_toggleIcon('activity_banking_intl', 'activity_banking_intlicon', as_branch ? true : true);
	
	// clear the form when page is refreshed
	//$(window).unload(as_clear);
	
	// set step and wayfinding
    //as_refreshStep();
	as_setScenarios();
	as_scenarioSelected();	
	
	// hide the "loading" div and show the parts of the page
	$('#topwayfinding').show();
	$('#as_stepnav').show();
    $('#as_page_loading').hide();
		
	as_debug_writeline('loaded');
	    
});
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// image pre-loading
jQuery.preloadImages = function()
{
    for (var i = 0; i < arguments.length; i++) 
    {
        jQuery("<img>").attr("src", arguments[i]);
    }
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// switch to custom and (optionally) set step
function as_switchToCustom(step)
{
	// check the custom scenario
	$('#scenario_custom').attr("checked","checked");		
	
	as_scenarioSelected();
		
	if (!step)
	{
		step = 2;
	}
	// taken from as_clear()
    $('#topwayfinding img.topwayfinding-check').remove();
    //$('input:hidden[name=step_reached]').val(0);
	// reset step progression	
	as_step_reached = 0;
    as_absStep(step);
	// reset scenario 
	as_scenarioSelected();
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// show or hide scenarios depending on age and student values
function as_setScenarios()
{
	// in branch mode, only CUSTOM scenario is available
	if (!as_branch) 
	{
		// hide them all
		$('#scenarios_main').hide();
		$('#scenarios_main_student').hide();
		
		$('#scenarios_senior').hide();
		$('#scenarios_senior_student').hide();
		
		$('#scenarios_youth').hide();
		$('#scenarios_youth_student').hide();
		// this will be the id for set of scenarios to show based on age and student		
		var id = "";
		// start by setting id to age related base 
		var age = $('input:radio[name=as_age]:checked').val();
		switch (age)
		{
			case "1":
				id += "youth";
				break;
				
			case "2":
				id += "main";
				break;
				
			case "3":
				id += "senior";
				break;
		}
		
		// if student, then append student to get student specific scenarios
		var student = $('input:radio[name=as_student]:checked').val();
		switch (student)
		{
			case "1":
				id = id + "_student";
				break;
		}
		
		// see if they already selected a scenario which will be hidden
		var current = $('input:radio[name=scenario]:checked').val();
		// a non CUSTOM scenario was selected, need to clear it		
		if (current != undefined && current != 'custom') 
		{
			current = current.substr(0, current.length - 2);
			if (current != id) 
			{
				$('input:radio[name=scenario]:checked').attr("checked", false);
				as_stepReached = 0;
				$('#topwayfinding img.topwayfinding-check').remove();
			}
		}
		
		// show set of scenarios with the id
		$('#scenarios_' + id).show();
	}
    
	// set the steps    
    as_refreshStep();
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// update steps when a specific scenario is selected
function as_scenarioSelected()
{
    //console.log('set scenario: ' + this.value);
	
    var current = $('input:radio[name=scenario]:checked').val();	
	
	// set wayfinding according to scenario type and step
	if (current == 'custom')
	{
        $('#topwayfinding-steps-2').hide();
        $('#topwayfinding-steps-4').show();		
	}
	else
	{
		$('#topwayfinding-steps-2').show();
        $('#topwayfinding-steps-4').hide();
	}
 
 	// reset the steps
 	as_stepReached = 0;
	$('#topwayfinding img.topwayfinding-check').remove();
    as_refreshStep();
   
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// set scenario state for branch mode
function as_setBranchMode()
{
        $("#as_branchsettings").show();
        $("input[name='branch_transit']").val(as_branch_id);
        $("input[name='session_id']").val(as_session_id);
		// hide the scenarios
	    $('#scenarios_main').hide();
	    $('#scenarios_main_student').hide();
	    
	    $('#scenarios_senior').hide();
	    $('#scenarios_senior_student').hide();
	    
	    $('#scenarios_youth').hide();
	    $('#scenarios_youth_student').hide();
		
		$('#scenarios_header').hide();
		
		// check the custom scenario
		$('#scenario_custom').attr("checked","checked");		
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// helper function to call language dependent UOS help toggle functions
function as_toggleHelpAbsolute( id_content, id_link)
{
	//alert(id_content);
	if (as_lang == "fr")
		toggleHelpAbsoluteFrench(id_content, id_link);	
	else
		toggleHelpAbsolute(id_content, id_link);
	return false;
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// function replaces UOS icon toggle (which was throwing an error)
function as_toggleIcon(obj, a_id, expand)
{
    var opener = document.getElementById(a_id);
    var content = getElementsByClass(obj);
	
	if ( expand === undefined ) 
	{
		// assume there is at least one item to expand/collapse
	     expand = (content[0].style.display == "none");
	}
    
    for (i = 0; i < content.length; i++) 
    {
        if (expand) 
        {
            content[i].style.display = '';
        }
        else 
        {
            content[i].style.display = 'none';
        }
    }
	
	// set the icon state
	iconState = opener.firstChild.alt;
	
    if (expand) 
	{
		iconState = iconState.replace("Expand", "");
        opener.firstChild.src = opener.firstChild.src.replace("expand", "collapse");
    	opener.firstChild.alt = 'Collapse' + iconState;	
	}
	else
	{
		iconState = iconState.replace("Collapse", "");
		opener.firstChild.src = opener.firstChild.src.replace("collapse", "expand");
		opener.firstChild.alt = 'Expand' + iconState;
		//opener.focus();  // this generates and error with IE		
	}
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// only tested with groups of radio buttons and single checkbox
// must be set as handler in js, otherwise this will be document context
function as_DynamicQuestionHandler()
{
	as_SetDynamicQuestion(this.name);
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
function as_SetDynamicQuestion(name)
{
	// hide elements with matching class of items which aren't selected
	$('input:[name=' + name + ']not(:checked)').each(function (i) 
	{
		var classname = name + '_' + $(this).val();
		$('.' + classname).hide();
	});
	// show the elements with matching class	
	$('input:[name=' + name + ']:checked').each(function (i) 
	{
		var classname = name + '_' + $(this).val();
		$('.' + classname).show();
	});	
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
// open the calculation details page in a new pop-up
function as_openCalcDetails(target)
{
	//alert(target);
	if(target == 'as_calcdetails'){
    newwindow = window.open('', target, 'width=700,height=600,scrollbars=yes');
	}else{
	newwindow = window.open('', target, 'width=810,height=700,scrollbars=yes');
	}
    if (window.focus) 
    {
        newwindow.focus()
    }
	return true;
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// submit the calculation details form
function as_submitCalcDetails()
{
	document.getElementById('as_calcdetails_form').action = '/cgi-bin/products/deposits/selector/calcdetails.cgi';
	document.getElementById('as_calcdetails_form').target = 'as_calcdetails';
	$('#as_calcdetails_form_button').click();
	return false;
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// submit the calculation details form
function as_submitPrint()
{
	document.getElementById('as_calcdetails_form').action = '/cgi-bin/products/deposits/selector/printversion.cgi';
	document.getElementById('as_calcdetails_form').target = 'as_print';
	$('#as_calcdetails_form_button').click();
	return false;
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
function as_ShowNote(id, show)
{
    show ? $('#' + id).show() : $('#' + id).hide();
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// helper functions for setting step state 
function as_nextStep()
{
	as_relStep(1);
}
function as_prevStep()
{
	as_relStep(-1);
}
function as_refreshStep()
{
	as_relStep(0);
}
function as_relStep(delta)
{
	as_setStep(as_step, as_step + delta);
}
function as_absStep(step)
{
	as_setStep(as_step, step);
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// set wayfinding and buttons according to current step
function as_setStep(current_step, step)
{
    var current = $('input:radio[name=scenario]:checked').val();
    
    var isNoScenario = (current == undefined);
    
    // custom scenario flag	
    var isCustom = (!isNoScenario && current == 'custom');
	
	// keep steps bounded 
    if (step > as_stepNum) 
        step = as_stepNum;
    
    if (step < 1) 
        step = 1;
		
	var wayStep = step;
    
    // if this isn't a custom scenario, then skip to first or last step
    if (!isCustom && current_step > step) 
	{
		step = 1;
		wayStep = 1;
	}
	// next, skip to last step
	else 
		if (!isCustom && current_step < step) 
		{
			step = as_stepNum;
			wayStep = 2;
		}
    
    // show and hide the correct step content
    for (var i = 1; i <= as_stepNum; i++) 
    {
        if (i == step) 
        {
            $('#as_step' + i).show();
        }
        else 
        {
            $('#as_step' + i).hide();
        }
    }
    
	// update the highest step reached 
	as_step_reached =  Math.max(as_step_reached, step);
	
	console.log('  current_step: ' + current_step + ' step: ' + step + ' step_reached: ' + as_step_reached);
    
	// update the top wayfinding
    $('#topwayfinding > ul:visible > li').each(function(i)
    {
    
        // get the anchor around the step label (if it exists)
        var label_a = $(this).find('.topwayfinding-label:first > a');
        
        // get the checked image (if it exists)
        var label_checkimg = $(this).find('.topwayfinding-label:first > img');
        
        if (i + 1 == wayStep) 
        {
            // set class to make step current step
            $(this).attr('class', 'topwayfinding-currentpage');
            
            // remove the link if it exists
            if (label_a.length != 0) 
            {
                $(this).find('.topwayfinding-label:first a').contents().unwrap();
            }
        }
        else 
            if (i < as_step_reached) 
            {
                // clear the class to make it in visited state
                $(this).attr('class', '');
                
                // add a link if it isn't there already
                if (label_a.length == 0) 
                {
                    // <a href="#top" onclick="as_setStep(i);" />
                    $(this).find('.topwayfinding-label:first').wrapInner('<a href="#top" onclick="as_absStep(' + (i + 1) + ');" />');
                }
                
                // add the checkbox
                if (label_checkimg.length == 0) 
                {
                    console.log('step ' + (i + 1) + ' adding img');
					
                    $(this).find('.topwayfinding-label:first').append('<img src="/uos/_assets/images/navigation/leftwayfinding/check.gif" alt="' + as_string_completed + '" class="topwayfinding-check" />');
                    
                }
            }
            else 
            {
                // set class to make step future step
                $(this).attr('class', 'topwayfinding-inactive');
                
                // remove the link if it exists
                if (label_a.length != 0) 
                {
                    $(this).find('.topwayfinding-label:first a').contents().unwrap();
                }
            }
    });
    
	var next_button_id;
	
    // disable or enable the bottom nav button 
    if (isNoScenario) 
    {
        $('#as_stepnav-next').hide();
		next_button_id = "#as_stepnav-next-disabled";
    }
    else 
    {
        $('#as_stepnav-next-disabled').hide();
		next_button_id = "#as_stepnav-next";
    }
    
    // set bottom button states according to scenario type and step		
    switch (step)
    {
        case 1:
            
            $('#as_stepnav-back').hide();
            $('#as_stepnav-cancel').show();
            $(next_button_id).show();
            
            if (isCustom) 
            {
                $('#as_stepnav-next a').text(as_string_next);
            }
            else 
            {
                $('#as_stepnav-next a').text(as_string_recommend);
            }
            break;
            
        case 2:
            
            $('#as_stepnav-back').show();
            $('#as_stepnav-cancel').show();
            $(next_button_id).show();
            
            $('#as_stepnav-next a').text(as_string_next);
            
            break;
            
            
        case 3:
            
            $('#as_stepnav-back').show();
            $('#as_stepnav-cancel').show();
            $(next_button_id).show();
            
            $('#as_stepnav-next a').text(as_string_recommend);
            
            break;
            
        case 4:
            
            $('#as_stepnav-back').show();
            $('#as_stepnav-cancel').show();
			if (!as_debug)
            	$(next_button_id).hide();
            
            // one step 4, we also submit the form
            as_submitform();
            
            break;
            
        default:
			break;
            
    }
    
	// save step	
	as_step = step;
	
		stepcount();
    
}
		
function stepcount(){
	var branchid = as_branch_id;
	var sessionid = as_session_id;
	var stepnumber = as_step;
	var cookiestep = '';
	
	if(getCookie(sessionid+'step')){
		cookiestep = getCookie(sessionid+'step');
		if(stepnumber > cookiestep){
			setCookie(sessionid+'step',stepnumber,30);
var getBranchRequest = createXmlHttpRequest();
var poststring = "sessionid="+sessionid+"&branch="+branchid+"&step="+stepnumber+"&account=";
getBranchRequest.open("POST", "/cgi-bin/products/deposits/selector/post.cgi",true);
getBranchRequest.setRequestHeader("Content-length", poststring.length);
getBranchRequest.onreadystatechange = function() {
	if (getBranchRequest.readyState != 4)  {	
		return; 
	}
};	
getBranchRequest.send(poststring);			
			//holder.src = "/cgi-bin/products/deposits/selector/post.cgi?sessionid="+sessionid+"&branch="+branchid+"&step="+stepnumber+"&account=";
			//alert(stepnumber);
		}
	}else{
		setCookie(sessionid+'step',stepnumber,30);
var getBranchRequest = createXmlHttpRequest();
var poststring = "sessionid="+sessionid+"&branch="+branchid+"&step="+stepnumber+"&account=";
getBranchRequest.open("POST", "/cgi-bin/products/deposits/selector/post.cgi",true);
getBranchRequest.setRequestHeader("Content-length", poststring.length);
getBranchRequest.onreadystatechange = function() {
	if (getBranchRequest.readyState != 4)  {	
		return; 
	}
};	
getBranchRequest.send(poststring);		
		//holder.src = "/cgi-bin/products/deposits/selector/post.cgi?sessionid="+sessionid+"&branch="+branchid+"&step="+stepnumber+"&account=";
		//alert(stepnumber);
	}
}
function setCookie(c_name,value,expireminutes) {
	var exdate=new Date();
	exdate.setMinutes(exdate.getMinutes()+expireminutes);
	document.cookie=c_name+ "=" +escape(value)+((expireminutes==null) ? "" : ";expires="+exdate.toGMTString()) + ';path=/';
}
function getCookie(c_name) {
	if (document.cookie.length>0) {
		c_start=document.cookie.indexOf(c_name + "=");
		if (c_start!=-1) { 
			c_start=c_start + c_name.length+1; 
			c_end=document.cookie.indexOf(";",c_start);
			if (c_end==-1) c_end=document.cookie.length;
			return unescape(document.cookie.substring(c_start,c_end));
		} 
	}
	return "";
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// clear the AS form
function as_clear(step)
{
    // HACK: this is a bit agressive, will remove all check images in top-wayfinding
    $('#topwayfinding img.topwayfinding-check').remove();
	// reset the step tracking variables	
	as_step_reached = 0;
    as_absStep(1);
    
    // clear the form too
	$('#as_form')[0].reset();
	
	if (as_branch) 
	{
		as_setBranchMode();	
	} 
	
	as_refreshStep();
	// clear auto totallers
	for (var i=0; i < as_totallers.length; i++)
	{
		as_totallers[i].total();
	}	
    
	// now, also need to reset scenario group
	as_setScenarios();
	as_scenarioSelected();
	// re-initialize all dynamic questions
	$('input.as_dynamicquestion:checked').each( function ()
	{
		var name = this.name;
		as_SetDynamicQuestion(name);
	});	
	as_SetDynamicQuestion('as_record_book');
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// keep an array of all Totaller objects in the page
var as_totallers = [];
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// set up a new Totaller for the associated form quantities
function as_initialize_autototal(total_id, sum_ids)
{
	// this will be the new totally object for this set of form fields
    var totaller = new as_Totaller(total_id, sum_ids);
    
	// set callbacks for each associated field
    jQuery.each(sum_ids, function()
    {
        var id = this + ",f";
        
        //console.log(id);
		
		// get the ids of the quantity form fielf and its associate frequency
		var field = $('input[name="' + id + '"]');
		var freq_field = $('select[name="' + id + '_f"]');
        
		// IE doesns't call onchange properly, try this work-around
        field.blur(function()
        {
            totaller.total();
        });
        
        freq_field.click(function()
        {
            totaller.total();
        });
		
        freq_field.blur(function()
        {
            totaller.total();
        });		
    });
	
	// save the totaller
	as_totallers.push(totaller);
	
	// run the totaller to initialize
	totaller.total();
    
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// Totaller: constructor
function as_Totaller(totalField, sumFields)
{
    this.totalField = totalField;
    this.sumFields = sumFields;
    
    this.total = as_Totaller_total;
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// Totaller: update total method
function as_Totaller_total()
{
    var total = 0;
    var totalId = '#' + this.totalField;
    
    //console.log(totalId + ' = [' + $(totalId).text() + ']');
    
	// update total from all associated fields
    jQuery.each(this.sumFields, function()
    {
        var id = this + ",f";
        
        var x = $('input[name="' + id + '"]').val();
        var freqid = $('select[name="' + id + '_f"]').val();
        
        //console.log('as_Totaller_total: ' + id + ' = ' + x + ' freqid: ' + freqid);
        
        var freq;
        
		// special handling of form value is not a number
        if (isNaN(x)) 
        {
            $(totalId).html('???');
            return false;
        }
        
		// take the associated frequency into account
        switch (freqid)
        {
			// annual
            case 'y':
                freq = 1 / 12;
                break;
             
			// monthly   
            case 'm':
                freq = 1;
                break;
            
			// weekly    
            case 'w':
                freq = 52.177457 / 12;
                break;
             
			// unrecognized frequency    
            default:
                $(totalId).html('???');
                return false;
        }
        
        total = total + x * freq;
        
    });
    
	// display the total
    $(totalId).html(Math.round(total * 10) / 10 + ' /' + as_string_mth);
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// submit the form contents to the cgi-script using AJAX
function as_submitform()
{
	// set the olb hidden var
    if (as_olb) 
		$('input:hidden[name=as_olb]').val("1");
	
    var ajax_url = document.as_form.action;
    
	// two ways to submit
	
    // post to new window using standard post
    if ($('input[name=as_debug_newwin]').is(':checked')) 
    {
        $("#as_recommended_product").html('debug: results in new page');
        
        document.as_form.target = '_AS_DEBUG';
        
        document.as_form.submit();
    }
    // ajax post with results displayed in div
    else 
    {
  		// first, serialize the form data so that it can be sent to the cgi  
        var mydata = $("#as_form").serialize();
    
		// write for the form contents to the textarea    
        if (as_debug) 
  			as_debug_writeline(mydata);
        
        // show loading panel, clear results					
        $('#as_loading').show();
        $('#as_recommended_product').html('');
        
		// 	contentType: "text/html; charset=utf-8",
        // call the script and return the results
        $.ajax(
        {
            type: "POST",
            url: ajax_url,
            data: mydata,
            cache: false,
            success: function(html)
            {
                $('#as_loading').hide();
                $("#as_recommended_product").html(html);
				
				var test = html.indexOf("id='sessionidID' value='");
				var test2 = html.substr(test+24,20);
				var sessionid = test2.substr(0,test2.indexOf("'"));
				test = html.indexOf("id='acctID' value='");
				test2 = html.substr(test+19,20);
				var accountid = test2.substr(0,test2.indexOf("'"));
				test = html.indexOf("id='branchID' value='");
				test2 = html.substr(test+21,20);
				var branchid = test2.substr(0,test2.indexOf("'"));
				var cookieacct = '';
				
				if(getCookie(sessionid+'account')){
					cookieacct = getCookie(sessionid+'account');
					if(accountid != cookieacct){
						setCookie(sessionid+'account',accountid,30);
var getBranchRequest = createXmlHttpRequest();
var poststring = "sessionid="+sessionid+"&branch="+branchid+"&step=account&account="+accountid;
getBranchRequest.open("POST", "/cgi-bin/products/deposits/selector/post.cgi",true);
getBranchRequest.setRequestHeader("Content-length", poststring.length);
getBranchRequest.onreadystatechange = function() {
	if (getBranchRequest.readyState != 4)  {	
		return; 
	}
};	
getBranchRequest.send(poststring);							
						//holder.src = "/cgi-bin/products/deposits/selector/post.cgi?sessionid="+sessionid+"&branch="+branchid+"&step=account&account="+accountid;
						//alert(branchid);
					}
				}else{
					setCookie(sessionid+'account',accountid,30);
var getBranchRequest = createXmlHttpRequest();
var poststring = "sessionid="+sessionid+"&branch="+branchid+"&step=account&account="+accountid;
getBranchRequest.open("POST", "/cgi-bin/products/deposits/selector/post.cgi",true);
getBranchRequest.setRequestHeader("Content-length", poststring.length);
getBranchRequest.onreadystatechange = function() {
	if (getBranchRequest.readyState != 4)  {	
		return; 
	}
};	
getBranchRequest.send(poststring);					
					//holder.src = "/cgi-bin/products/deposits/selector/post.cgi?sessionid="+sessionid+"&branch="+branchid+"&step=account&account="+accountid;
					//alert(branchid);
				}
            },
            error: function(XMLHttpRequest, textStatus, errorThrown)
            {
				// TODO: if an error is thrown, the message doesn't appear. 
				// if you get an error, try the submit to new window debug option
                $('#as_loading').hide();
                $("#as_recommended_product").html(textStatus + '\n' + errorThrown + '\n' + html);
            }
            
        });
    }
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// for compatibility with IE, create a null function for logging
// you won't see any debug output in the console, but the page 
// won't break either
if (typeof console === "undefined") 
{
    console = 
    {
        log: function()
        {
        }
    };
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// write text to debug textarea
function as_debug_write(text)
{
	if (as_debug) 
	{
		var t = $("#as_debug_msg").val();
		$("#as_debug_msg").val(t + text);
	}	
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// write line of text to debug textarea
function as_debug_writeline(text)
{
	if (as_debug) 
	{
		as_debug_write(text + '\n');
	}
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// stub for in-development functions
function tbd()
{
    alert('TBD: Not yet implemented');
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
