var BACK_1_CAPT = 'Back to Step 1 (Change Details Above)';
var CONT_1_CAPT = 'Continue (All Details Above are Correct)';
var BACK_2_CAPT = 'Back to Step 2 (Change Redeemable Loans)';
//var CONT_2_CAPT = 'Continue (All Redeemable Loans OK)';
var scc_msg = '\nAlso ensure Gross and Net Salary or any Redeemable Deduction are in correct format';
var frm_prefix = 'init_calc_';
var cust_details_final = false, redeem_values_final = true, ok_submit = false;

var untouchable_ratio, loan_max = 0;
var loan_min, pay_mth_min, pay_mth_max, age_min, age_max;
var ruleset = 0, mth_step = 6, redeem_lines = 12;
var init_redeem_lines = 0;
var birth_y, birth_m, birth_d, apply_y, apply_m, apply_d;
var E_show = Element.show, f_show = s_show, E_hide = Element.hide;
var force_recalc = true, l_slider = null;

//if (typeof dojo != 'undefined') {
//    dwid = dojo.widget.byId;
//}

//function hi_callback(type, data, evt)
//  {
//    if (type == 'error')
//      alert('Error when retrieving data from the server!');
//    else
//      alert(data);
//  }

//function E_hide (x) {
//try {
//    Element.hide(x);
//    } catch (e) { alert('RJS error:\n\n' + e.toString()); throw e }
//}

function c_hide () {
    E_hide("combine_div");
    E_show("redeem_summary");

}

function c_show () {
    E_show("combine_div");
    E_hide("redeem_summary");
}

function show_deduct_info () {
	E_hide("take_home");
        disp_workings();
	E_show("deduct_info");
}

function hide_deduct_info () {
	E_hide("deduct_info");
	E_show("take_home");
}

function lock_state_1 () {
	d_hide();
	s_hide("loan_constraint_id");
	s_hide("borrower_classification_id");
	f_hide('gross_income');
	f_hide('dcl_net');
	f_hide('undcl_deduct');
	f_hide('net_income');
	s_hide('itype');
	E_hide('reset_step1');
	$('btn_cont1').value = BACK_1_CAPT;
	if (ruleset != 2) 
	    E_show('step_2');
}

function lock_state_2 () {
    var i;
    //c_hide();
    for (i = 1; i <= redeem_lines; i++) {
	s_hide('fi_name' + i);
	f_hide('m_redeem' + i);
	f_hide('outstanding' + i);
	f_hide('acct_no' + i);
    }
    f_hide('monthly_redeem');
    f_hide('redeemable_loans');
    $('btn_back2').value = BACK_2_CAPT;
}

function unlock_state_2 () {
    var i;
    for (i = 1; i <= redeem_lines; i++) {
	s_show('fi_name' + i);
	f_show('m_redeem' + i);
	f_show('outstanding' + i);
	f_show('acct_no' + i);
    }
    f_show('monthly_redeem');
    f_show('redeemable_loans');
}

function lock_state_3 () {
    f_hide('calc_loan');
    f_hide('c_installment');
    f_hide('c_period');
    f_hide('amt_apply_for');
    f_hide('repay_period');
    f_hide('monthly_repay');
}

function unlock_state_3 () {
    s_show('calc_loan');
    s_show('c_installment');
    s_show('c_period');
    s_show('amt_apply_for');
    s_show('repay_period');
    s_show('monthly_repay');
    //E_show('div_submit');
}

function set_upper (w) {
    var s = frm_prefix + w;
    try {
	$(s).value = loan_max;	// dojo.widget.byId(s).flags.max;
    }
    catch(e) { alert('upper: ' + w);  }
}

function clean_redeem () {
    var i, invar_1 = frm_prefix + 'fi_name',
	invar_2 = frm_prefix + 'm_redeem',
	invar_4 = frm_prefix + 'acct_no',
	invar_3 = frm_prefix + 'outstanding', invar_0 = '0.00';
    for (i = 1; i <= redeem_lines; i++) {
	//$(invar_1 + i).selectedIndex = 0;
	if (parseFloat($F(invar_2 + i)) <= 0)
	    $(invar_2 + i).value = invar_0;
	if (parseFloat($F(invar_3 + i)) <= 0)
	    $(invar_3 + i).value = invar_0;
	//$(invar_4 + i).value = '-';
    }
    //$(frm_prefix + 'redeemable_loans').value = 0;
    // param in becomes dummy :)
    comp_m_redeem_total($(frm_prefix + 'monthly_redeem'));
    comp_outstanding_total($(frm_prefix + 'redeemable_loans'));
    redeem_values_final = true;
}

function reset_step_3 () {
    E_hide("step_3");
    E_hide('div_submit');
    ok_submit = false;
    loan_max = 0;
}

function get_selectval (o) {
    return $A(o.getElementsByTagName('option'))[$(o).selectedIndex].innerHTML;
}

//function get_selected (o) {
//    return $A(o.getElementsByTagName('option'))[$(o).selectedIndex].value;
//}

function age_months () {
    var ad_mths = get_selectval(apply_y) * 12 + $(apply_m).selectedIndex + 1;
    return ad_mths - get_selectval(birth_y) * 12 - $(birth_m).selectedIndex - 1;
}

function age_desc (age_m) {
    var s, y = Div(age_m, 12),
	m = Mod(age_m, 12);
    if (y > 0)
	s = y + ' year';
    else
	s = '';
    if (y > 1)
	s += 's';
    if (m > 0) 
	s += ' ' + m + ' month';
    if (m > 1)
	s += 's';
    return s;
}

function continue_1 () {
    cust_details_final = !cust_details_final;
    if (cust_details_final) {
	var g = parseFloat($F('init_calc_gross_income'));
	var n = parseFloat($F('init_calc_net_income'));
	if (age_months() + pay_mth_min > age_max) {
	    alert(age_desc(age_months() + pay_mth_min - age_max) +
		  ' too old for ' + get_selectval($(frm_prefix + "loan_constraint_id")));
	    cust_details_final = false;
	    return;
	}
	if (age_months() < age_min) {
	    alert(age_desc(age_min - age_months()) + ' too young for ' +
		  get_selectval($(frm_prefix + "loan_constraint_id")));
	    cust_details_final = false;
	    return;
	}
	if (g < n) {
	    alert('Net Income cannot be more than Gross Salary!');
	    cust_details_final = false;
	    return;
	}
	lock_state_1();
	clean_redeem();
	
	if (ruleset != 2)
	    state_2();
	else
	    state_3();
    }
    else {
        // when force recall not true -> we have gone through calc already
        // this will not popup when we have done only step 2, but not step 3  
        if (!force_recalc)
        {
            if (!confirm('If you go back to Step 1, Loan values will be Recalculate'))
            {
                cust_details_final = true;  // still true
                return; // cancel Redo
            }
            force_recalc = true;    // allow recalc to take place
        }
	E_hide("step_2");
	reset_step_3();
	d_show();
	s_show("borrower_classification_id");
	s_show("loan_constraint_id");
	
	s_show('gross_income');
	s_show('dcl_net');
	s_show('net_income');
	s_show('undcl_deduct');
	s_show('itype');
	E_show('reset_step1');
	$('btn_cont1').value = CONT_1_CAPT;
    }
}

function state_2 () {
	redeem_values_final = !redeem_values_final;
	if (redeem_values_final) {
		lock_state_2();
		state_3();
		//clean_redeem();
	}
	else {
	//E_hide("div_submit");
	reset_step_3();
	unlock_state_2();
	c_show();
	}
}
    
function state_3 () {
	if (ruleset == 2) 
	    clean_redeem();
	$('tmpnote').innerHTML = '<br>';
    	E_show('step_3');
        if (force_recalc)
        {
            show_ranges();
            preload_month_repay();
            force_recalc = false;
        }
        else // do a redeem ad
        {
            //show_ranges();
        }
	E_show("div_submit");
	ok_submit = true;
}    

function max2 (a, b) {
    if (a > b) {
	return a;
    }
    return b;
}

function good_scale (lo, hi) {
    var iv = hi - lo;
    if (iv > 99999)
        return 2000;
   return 1000;
   /* if (iv < 100)
	return 1;
    else
	iv /= 100;
    var scale = [2, 5, 10, 20, 50, 100, 200, 500, 1000, 2000];
    rv = scale.find(function(v) { return v >= iv; });
    if (rv == null)
	return 5000;
    return rv; */
}

function Div(X, Y) {
    return (X / Y) | 0;
}

function Mod(X, Y) {
    return X - ((X / Y) | 0) * Y;
}

function trunc1k (x) {
	return Div(x, 1000) * 1000;
}

function calc_monthly_payment ()
{
    var x = $('tmpnote');
    x.innerHTML = 'Slider moved, reminder to Press Calculate Monthly Payment';
    new Effect.Highlight(x, {startcolor:'#ff99ff', endcolor:'#ffff99', restorecolor: '#ffffff' });
    //setTimeout("$('calc_installment').onclick();", 100);
}

function aux_max_loan () {
    loan_max = trunc1k(loan_max);
    if (loan_max >= loan_min) {
	$('loan_range_div').innerHTML = 'Max: ' + loan_max + ' (nearest thousand RM)';
	set_bounds('amt_apply_for', loan_min, loan_max, 0);
	var amt = frm_prefix + 'amt_apply_for';
	l_slider = new Control.Slider('slider_loan', 'track2', {
		range: $R(loan_min, loan_max),
		sliderValue: loan_max, 
		values: range_arr(loan_min, loan_max, good_scale(loan_min, loan_max)),
		onSlide: function(v) { $(amt).value = v; },
		onChange: function(v) { calc_monthly_payment(); }
	});
    }
    else {
	$('loan_range_div').innerHTML = 'LOAN UNACCEPTABLE (Unable to repay Min. Loan of ' + loan_min + ')';
	set_bounds('amt_apply_for', 0, 0, 0);
    }
}
    
// Flag to one set per step 3
// Make sure reset it before leaving step 3
function set_loan_max (v) {
    if (loan_max != v) { // loan_max == 0 before oct 07
	loan_max = v;
    }
}

function synch_calc_loan (i) {
    //set_bounds('monthly_repay', 0, i, 2);
    $(frm_prefix + 'calc_loan').onclick();
    loan_max = $F(frm_prefix + 'amt_apply_for');
    aux_max_loan();
    set_upper('amt_apply_for');	//, loan_max);
    $(frm_prefix + 'c_installment').onclick();
				   // this made the monthly payment adjust correctly
}

function preload_month_repay () {
    var gross = $F(frm_prefix + 'gross_income');
    var ub = (1.0 - untouchable_ratio) * gross;
    var lb = parseFloat($F(frm_prefix + 'net_income')) + parseFloat($F(frm_prefix + 'monthly_redeem'));
    if (gross * untouchable_ratio < 500) {
	ub = gross - 500;
    }	
    
    lb = lb - max2(500, gross * untouchable_ratio);
    
    if (lb > ub)
    {
	lb = ub;
    }
    //$('loan_range_div').innerHTML = "LOAN NOT POSSIBLE!";
    if (lb < 0) {
	$('mth_repay_range_div').innerHTML = 'LOAN UNACCEPTABLE (Cannot pay > RM 0 per month)';
    }
    else {
	$('mth_repay_range_div').innerHTML = lb + ' MAX';
    set_bounds('monthly_repay', 0, lb, 2);
    setTimeout('synch_calc_loan(' + lb + ');', 100);
    }
}

function set_bounds (id, lb, ub, set) {
    var s = frm_prefix + id;
        if (set < 0 && set > 2)
	alert(id + set);
//    try {
//	var f = dojo.widget.byId(s).flags;
//	if (lb > ub)
//	{
//	    var t = ub;
//	    ub = lb;
//	    lb = t;
//	}
//	f.min = lb;
//	f.max = ub;
//    }
//    catch(e) { alert('bound ' + s);  }
    if (set == 2)
	$(s).value = ub;
    else if (set == 1)
	$(s).value = lb;
}

function range_arr (b, e, s) {
    var i, a = new Array();
    
    for (i = b; i <= e; i += s) {
	a.push(i);
    }
    if (i - e < s)
	a.push(e);
    return a;
}

function set_amt_and_period_limits (l_min, p_min, p_max, a_min, a_max, rs) {
    $('loan_range_div').innerHTML = "(Valid range NOT computed yet)";
    set_bounds('amt_apply_for', l_min, l_min, 1);
 
    loan_min = l_min;
    //loan_max set by server
    //note conversion to months from server
    age_min = a_min; age_max = a_max;
    ruleset = rs;
    pay_mth_min = p_min;
    
    var mod = '',  max_shown,
	new_p = age_max - age_months(); // remaining months to borrow
    
    if (new_p <= p_max) {	 // critical age gap
	p_max = Div(new_p, mth_step) * mth_step;
	mod = ' (adjusted for age)';
	max_shown  = p_max - mth_step;
    }
    else
	max_shown = p_max;
    pay_mth_max = p_max;
    
    set_bounds('repay_period', p_min, max_shown, 2);
    $('repay_period_range_div').innerHTML = '(' + p_min + ' - ' + max_shown  + ' only)' + mod;
	
    var mth = frm_prefix + 'repay_period';
    new Control.Slider('slider_mth', 'track1', {
	    range: $R(p_min, p_max),
	    sliderValue: max_shown, 
	    values: range_arr(p_min, p_max, mth_step),
	    onSlide: function(v) { $(mth).value = v; },
	    onChange: function(v) { calc_monthly_payment(); }
    });
}

function show_age () {
    $('age_div').innerHTML = 'Age: ' + age_desc(age_months());
}

function show_ranges () {
    var	lid = $F('init_calc_loan_constraint_id');
	new Ajax.Updater('repay_period_range_div',
'/init_calcs/show_amt_and_period/' + lid, {asynchronous:false, evalScripts: true});
}

function set_with_hold () {
    var bc_id = $F('init_calc_borrower_classification_id');
    new Ajax.Updater('with_hold_div',
		     '/borrower_classifications/get_percent/' + bc_id, {asynchronous:false, evalScripts: true});
}

function d_hide () {
    var o = 'option';
    var m = birth_m;
    E_hide(birth_d); E_hide(m); E_hide(birth_y);
    E_hide(apply_d); E_hide(apply_m); E_hide(apply_y);
    var mth = $A(m.getElementsByTagName(o));
    $('dob_h').innerHTML = get_selectval(birth_d) + ' ' +
    mth[$(m).selectedIndex].innerHTML + ' ' + get_selectval(birth_y);
    
    m = apply_m;
    mth = $A(m.getElementsByTagName(o));
    $('apply_h').innerHTML = get_selectval(apply_d) + ' ' +
    mth[$(m).selectedIndex].innerHTML + ' ' + get_selectval(apply_y);
}

function d_show () {
    E_show(birth_d); E_show(birth_m); E_show(birth_y);
    E_show(apply_d); E_show(apply_m); E_show(apply_y);
    $('dob_h').innerHTML = '';
    $('apply_h').innerHTML = '';
}

function f_hide (id) {
    var s = frm_prefix + id;
    E_hide(s);
    $(id + '_h').innerHTML = $F(s);
}

function s_hide (id) {
    var s = frm_prefix + id;
    E_hide(s);
    var nodes = $A($(s).getElementsByTagName('option'));
    $(id + '_h').innerHTML = nodes[$(s).selectedIndex].innerHTML;
}

function w_hide (id) {
    var s = frm_prefix + id;
    dojo.widget.byId(s).hide();
    $(id + '_h').innerHTML = $F(s);
}

function s_show (id) {
    var s = frm_prefix + id;
    $(id + '_h').innerHTML = '';
    E_show(s);
}

function w_show (id) {
    var s = frm_prefix + id;
    $(id + '_h').innerHTML = '';
    try {
	dojo.widget.byId(s).show();
    }
    catch(e) { alert(s); }
}

function to_nat (o) {
    o.value = parseInt(o.value);
}

// roundup to highest 10 cent
function roundup_10 (v) {
	v *= 100.0;
	return Math.ceil(Math.floor(v) / 10.0) / 10.0;
}
	
function to_ringgit (o) {
	//o.value = parseFloat(o.value).toFixed(2);
	o.value = roundup_10(parseFloat(o.value)).toFixed(2)	// display 2 trailing decimal at all times
}

function comp_net_income (o) {
    o.value = parseFloat(o.value).toFixed(2);
    $(frm_prefix + 'net_income').value = (parseFloat($F(frm_prefix + 'dcl_net'))
    - parseFloat($F(frm_prefix + 'undcl_deduct'))).toFixed(2);
}

function comp_m_redeem_total(o) {
    aux_comp_total('m_redeem', 'monthly_redeem', o);
}

function comp_outstanding_total(o) {
    aux_comp_total('outstanding', 'redeemable_loans', o);
}

function aux_comp_total (line, total, o) {
    var i, t = 0,
	invariant = frm_prefix + line;
    o.value = parseFloat(o.value).toFixed(2);
    for (i = 1; i <= redeem_lines; i++) {
	t +=  parseFloat($F(invariant + i));
    }
    $(frm_prefix + total).value = t.toFixed(2);
}

function trap_enter () {
    if (ok_submit)
    {
        if (confirm('Are you sure you want to save Loan details now?')) {
        $(frm_prefix + 'c_loan_range').value = $('loan_range_div').innerHTML; 
         $(frm_prefix + 'c_mth_repay').value = $('mth_repay_range_div').innerHTML; 
         $(frm_prefix + 'c_rp_range').value = $('repay_period_range_div').innerHTML;
            return true;
        }
        return false;
    }
    else
    {
	alert("You cannot submit this form at the moment");
	return false;
    }
}

function disp_workings () {
    var i = 'insurance', a = 'advance_payment',
    ii = 'interim_interest', t = 'take_home_amt';
 
    $(frm_prefix + i).value = parseFloat($F(frm_prefix + i)).toFixed(2);
    $(frm_prefix + a).value = parseFloat($F(frm_prefix + a)).toFixed(2);
    $(frm_prefix + ii).value = parseFloat($F(frm_prefix + ii)).toFixed(2);
    $(frm_prefix + t).value = parseFloat($F(frm_prefix + t)).toFixed(2);
    f_hide(i);  f_hide(a);
    f_hide(ii); f_hide(t);
    
    // More details added for 2007
    var cp = '_copy',
        ni = 'net_income', ni_cp = ni + cp,
        mr = 'monthly_redeem', mr_cp = mr + cp,
        rmi = 'redeemed_month_income',
        mp = 'monthly_repay', mp_cp = mp + cp,
        fmi = 'final_month_income', comp_fmi;
    
    $(ni_cp).innerHTML = $F(frm_prefix + ni);
    $(mr_cp).innerHTML = $F(frm_prefix + mr);
    $(rmi).innerHTML = parseFloat($F(frm_prefix + ni)) + parseFloat($F(frm_prefix + mr));
    $(mp_cp).innerHTML = $F(frm_prefix + mp);
    
    comp_fmi = parseFloat($(rmi).innerHTML) - parseFloat($F(frm_prefix + mp));
    $('pcent_fmi').innerHTML = '(' + ((comp_fmi * 100) /
                                parseFloat($F(frm_prefix + 'gross_income'))).toFixed(4)
                                + '% of Gross Salary)';                               
    $(frm_prefix + fmi).value = comp_fmi.toFixed(2);
    f_hide(fmi);
    if (l_slider != null)
        l_slider.setValue($F(frm_prefix + 'amt_apply_for'));
}

function calc_common_init () {
    var doc = document;

    set_with_hold();
 
    birth_y = doc.getElementsByName('init_calc[dob(1i)]')[0];
    birth_y.onchange = show_age;
    birth_m = doc.getElementsByName('init_calc[dob(2i)]')[0];
    birth_m.onchange = show_age;
    birth_d = doc.getElementsByName('init_calc[dob(3i)]')[0];
    apply_y = doc.getElementsByName('init_calc[created_at(1i)]')[0];
    apply_y.onchange = show_age;
    apply_m = doc.getElementsByName('init_calc[created_at(2i)]')[0];
    apply_m.onchange = show_age;
    apply_d = doc.getElementsByName('init_calc[created_at(3i)]')[0];
    show_age();
        
    lock_state_2();   // always when edit loaded
    $('loan_range_div').innerHTML = $F(frm_prefix + 'c_loan_range');
    $('mth_repay_range_div').innerHTML = $F(frm_prefix + 'c_mth_repay');
    $('repay_period_range_div').innerHTML = $F(frm_prefix + 'c_rp_range');
    disp_workings();
    ok_submit = false;
}

function calc_add_init () {
    // only call when a new calc
    $('btn_cont1').value = CONT_1_CAPT;
    //set_bounds("gross_income", 501, 99999, 1);
    //set_bounds("net_income", 500, 99999, 1);
    calc_common_init();
    show_ranges();
}

function show_redeem_lines () {
    for (i = 1; i <= redeem_lines; i++) {
        if (i > init_redeem_lines)
            $('rd_line' + i).style.display = 'none';
        else
            $('rd_line' + i).style.display = '';
    }
}

function add_redeem_line () {
    var i = ++init_redeem_lines;
    if (i > redeem_lines)
        --init_redeem_lines;
    else {
        show_redeem_lines();
    }
}

function rem_redeem_line () {
    var i = init_redeem_lines--;
    if (i < 1)
        init_redeem_lines = 0;
    else {
        var m = frm_prefix + 'm_redeem' + i;
        var o = frm_prefix + 'outstanding' + i;
        $(m).value = '0.00';
        comp_m_redeem_total($(m));
        $(o).value = '0.00';
        comp_outstanding_total($(o));
        $(frm_prefix + 'fi_name' + i).value = 1;
        $(frm_prefix + 'acct_no' + i).value = '';
        show_redeem_lines();
    }
}

function clear_redeem_lines () {
    for (i = 1; i <= redeem_lines; i++) {
        $('rd_line' + i).style.display = 'none';
        var m = frm_prefix + 'm_redeem' + i;
        var o = frm_prefix + 'outstanding' + i;
        $(m).value = '0.00';
        $(o).value = '0.00';
        $(frm_prefix + 'fi_name' + i).value = 1;
        $(frm_prefix + 'acct_no' + i).value = '';
    }
    $(frm_prefix + 'monthly_redeem').value = '0.00';
    $(frm_prefix + 'redeemable_loans').value = '0.00';
}  

function reset_step_1 () {
    $(frm_prefix + 'gross_income').value = 0.0;
    $(frm_prefix + 'dcl_net').value = 0.0;
    $(frm_prefix + 'undcl_deduct').value = 0.0;
    $(frm_prefix + 'net_income').value = 0.0;
}

function do_print () {
    $(frm_prefix + 'c_installment').onclick();
	// this prevent cheating before printing by editing figures but not doing recalc
    c_show();
    E_show("redeem_summary");
    lock_state_3();
      var disp_setting="toolbar=no,location=no,directories=no,menubar=no,"; 
      disp_setting+="scrollbars=yes,width=750,height=550,left=0,top=0"; 
  var content_vlue = document.getElementById("calc_contents").innerHTML; 
  
  var dpr=window.open("","",disp_setting); 
   dpr.document.open(); 
   dpr.document.write('<html><title>SCC Calculator</title>'
	+ '<style type="text/css">'
	+ 'div.dont_print {display:none;} '
	+ 'body {background: white; font-size:12px;font-family:Arial, Helvetica, sans-serif;} '
	+ 'div {font-size:12px;} '
	+ 'label {font-size:12px;} '
	+ 'td {font-size:12px;} '
	+ '.dont_print input {display:none;} '
	+ 'div.currency_box {background: lightgreen;}'
	+ '</style><body onLoad="self.print()">'); 
   dpr.document.write(content_vlue);          
   dpr.document.write('</body></html>'); 
   dpr.document.close(); 
   dpr.focus();
   unlock_state_3();
    c_hide();
	
   	
}

var myCodeVer = 705270930;
