/**
 * Onload function for the HTML version of the produc selector.
 * Populates the DOB Year dropdown and calls the update_reasons() function to ensure form is up to date.
 * 
 */
function product_selector_html_onload()
{

    // Get current Year
    var d = new Date();
    var dYear = d.getFullYear();

    for( var i = (dYear - 17); i > (dYear - 100); i-- )
    {
        add_select_option("postBYear", i, i);
    }

    update_reasons();

}


/**
 * Update the 'Reasons for taking HBF cover' based on the supplied cover recipients
 */
var reason_value;
function updateReasons()
{

    // Get the current value of postReason
    // This way we can reset it when the dropdown is re-populated.
    reason_value = $(":input#postCover").val();
    
    /*
     * Build a list of possible reasons to display
     */

    var reason_array = [];
    reason_array['dental'] 	= 'Need dental/optical cover';
    reason_array['safe'] 	= 'To be on the safe side';
    reason_array['health'] 	= 'Particular health condition';
    reason_array['tax'] 	= 'Pay less tax';
    reason_array['family'] 	= 'Planning a family';
    reason_array['extras'] 	= 'To help pay the extra bills';
    reason_array['kids'] 	= 'Planning more kids';
    reason_array['age'] 	= 'Feeling my age';
    reason_array['unsure'] 	= 'Unsure';

    /*
     * Assign the correct reasons to the right age/recipient categories
     */

    var category_reason_array = [];

    // For example, the possible 'Young Single' reasons are reason_array['cover'], ['safe'], ['health'], ['tax'], and ['unsure']
    // 'unsure' is an option for all categories, so leave it out
    category_reason_array['young_single'] = [];
    category_reason_array['young_single'].push("dental");
    category_reason_array['young_single'].push("safe");
    category_reason_array['young_single'].push("health");
    category_reason_array['young_single'].push("tax");
    category_reason_array['young_single'].push("unsure");

    category_reason_array['young_couple'] = [];
    category_reason_array['young_couple'].push("family");
    category_reason_array['young_couple'].push("dental");
    category_reason_array['young_couple'].push("safe");
    category_reason_array['young_couple'].push("health");
    category_reason_array['young_couple'].push("tax");
    category_reason_array['young_couple'].push("unsure");

    // All Family categories share the same reason sets
    category_reason_array['family'] = [];
    category_reason_array['family'].push("extras");
    category_reason_array['family'].push("kids");
    category_reason_array['family'].push("safe");
    category_reason_array['family'].push("health");
    category_reason_array['family'].push("tax");
    category_reason_array['family'].push("unsure");

    // Middle/Mature Single categories share the same reason sets
    category_reason_array['middle_mature_single'] = [];
    category_reason_array['middle_mature_single'].push("tax");
    category_reason_array['middle_mature_single'].push("safe");
    category_reason_array['middle_mature_single'].push("health");
    category_reason_array['middle_mature_single'].push("dental");
    category_reason_array['middle_mature_single'].push("unsure");

    // Middle/Mature Family categories share the same reason sets
    category_reason_array['middle_mature_family'] = [];
    category_reason_array['middle_mature_family'].push("extras");
    category_reason_array['middle_mature_family'].push("kids");
    category_reason_array['middle_mature_family'].push("safe");
    category_reason_array['middle_mature_family'].push("health");
    category_reason_array['middle_mature_family'].push("tax");
    category_reason_array['middle_mature_family'].push("unsure");
		
    // Both Empty Nester categories share the same reason sets
    category_reason_array['empty_nester'] = [];
    category_reason_array['empty_nester'].push("age");
    category_reason_array['empty_nester'].push("health");
    category_reason_array['empty_nester'].push("extras");
    category_reason_array['empty_nester'].push("safe");
    category_reason_array['empty_nester'].push("tax");
    category_reason_array['empty_nester'].push("unsure");

    // Retiree
    category_reason_array['retiree'] = [];
    category_reason_array['retiree'].push("age");
    category_reason_array['retiree'].push("health");
    category_reason_array['retiree'].push("extras");
    category_reason_array['retiree'].push("tax");
    category_reason_array['retiree'].push("unsure");

    /*
     * Determine which category the user fits into, to know which reasons to display
     */


	 var dob = $(":input#dob").val();

	 var dobParts = dob.split("-");
	 var dobYear = dobParts[0];
	 var dobMonth = dobParts[1];
	 var dobDay = dobParts[2];

	 
    // Determine the user's age and family status
    var user_age = get_age_in_years(parseInt(dobYear,10), parseInt(dobMonth,10), parseInt(dobDay,10));
    
	if(!user_age)
    {
        remove_select_options("postReason");
        return;
    }

    var user_cover = document.getElementById('postCover').value;

    // Which category does their age and family status place them in?
    // User is in the 'young' category
    if (user_age >= 17 && user_age <= 24)
    {
        switch(user_cover)
        {
            case 'single':
                user_category = 'young_single';
                break;
            case 'couple':
                user_category = 'young_couple';
                break;
            case 'family':
            case 'singleParent':
                user_category = 'family';
                break;
            default:
                remove_select_options("postReason");
                return;
        }
    }
    else if (user_age >= 25 && user_age <= 44)
    {
        switch (user_cover)
        {
            case 'single':
                user_category = 'middle_mature_single';
                break;
            case 'couple':
                user_category = 'young_couple';
                break;
            case 'family':
            case 'singleParent':
                user_category = 'family';
                break;
            default:
                remove_select_options("postReason");
                return;
        }
    }
    else if (user_age >= 45 && user_age <= 64)
    {
        switch(user_cover)
        {
            case 'single':
                user_category = 'middle_mature_single';
                break;
            case 'couple':
                user_category = 'empty_nester';
                break;
            case 'family':
            case 'singleParent':
                user_category = 'family';
				break;
            default:
                remove_select_options("postReason");
                return;
        }
    }
    else
    {
        user_category = 'retiree';
    }

    /*
     * Generate the HTML for the new Reasons select box and replace the existing one on the page
     */

    // Remove all options from the select
    remove_select_options("postReason");

    // Add all elements in array to select
    for (reason in category_reason_array[user_category])
    {

        // Determine reason code
        reason_code = category_reason_array[user_category][reason];
        
        // Add option to select
        add_select_option("postReason", reason_array[reason_code], reason_code);

    }

    // If reason_value is set, then attempt to set the value of the newly populated dropdown.
    document.getElementById("postReason").value = reason_value;


    // An invalid resoen was set --> set to the default one
    // eg. A reson is not available anymore because of a diffenet cover type
    if ( null == $(":input#postReason").val() )
    {
	     $(":input#postReason").val('');
    }


}

/**
 * Empty the Reasons select box
 */
function remove_select_options(id)
{

    // Get Select Object
    var selectBox = document.getElementById(id);
    var i;

    for( i=selectBox.options.length-1; i>=0 ; i-- )
    {

        selectBox.remove(i);
    }

	// Add empty option to select
    add_select_option("postReason", "My main intention is", "");

}

/**
 * Calculates a person's current age, in years, from provided year, month, and day.
 *
 * @param int year
 * @param int month
 * @param int day
 */
function get_age_in_years(year, month, day)
{
    // If year, month or day are not set, do not return a value
    if(!year || !month || !day)
    {
        return null;
    }

    // Determine the current date
    var current_date = new Date();
    var current_day = current_date.getDate();
    var current_month = 1 + current_date.getMonth();
    var current_year = current_date.getUTCFullYear();

    // Work out how many years of age
    user_years = current_year - year;

    // Is the current month the same or less than the DOB month?
    if (current_month <= month)
    {
            // Is the DOB month the same as current month?
            if (current_month == month)
            {
                    // Yes.
                    // Is the DOB day greater than the current day?
                    if (day > current_day)
                    {
                            // Yes. So subtract a year from what was calculated because
                            // mathematically this full year has not eventuated yet
                            user_years--;
                    }
            }
            else
            {
                    // No. So subtract a year from what was calculated because mathematically this
                    // full year has not eventuated yet
                    user_years--;
            }
    }

    // Return the number of years of age
    return user_years;
}



/**
 * Generic function to add a new option to a select on the page
 *
 * @param <select>	Object of select to add option to
 * @param String	Option text
 * @param String	Option Value
 */
function add_select_option(select_id, option_text, option_value)
{

    // Get postReason Object
    var selectBox = document.getElementById(select_id);

    // Create option element
    var optn = document.createElement("option");

    // Create Text Value
    optn.text = option_text;

    // Create Value 
    optn.value = option_value;

    // Add option to select
    selectBox.options.add(optn);

}

/**
 * ------------------------------------
 * Sets the value of a submit button in a form for HTML Product Selector.
 * It also sets a timeout to clear the value after 5 seconds.
 * ------------------------------------
 *
 */
function setPSSubmitValue(value)
{
	$(":input#postButton").val(value);

 setTimeout("clearPSSubmitValue", 5000);

}

function clearPSSubmitValue()
{
	 $(":input#postButton").val("");
}
