/*
 * Copyright (c) 2006 by ePublishing
 *   All rights reserved.
 *
 * Author: Robert James Kaes <rkaes@ePublishing.com>
 *
 * Implement the required UI for the physical_location HTML
 *
 */

var url = '/m_geography/xml';

$(document).ready(function(){

    // Set up the ajax notification
    $("#geography-selection-loading")
        .ajaxStart(function(){ $(this).show(); })
        .ajaxStop(function(){ $(this).hide(); });


    // Set up the onchange events for the various select inputs
    // $("select[@name=country_id]").change(function(){
    $("select[@name=country]").change(function(){
        // Now, try to load up the state information
        var country_id = this.options[this.selectedIndex].value;
		if (country_id) {
        	$.get(url + '/country/' + country_id + '/states',
           	 state_has_loaded);
		}
    });


    $("select[@name=state]").change(function(){
        // Load up the city information
        var state_id = this.options[this.selectedIndex].value;
		if (state_id) {
        	$.get(url + '/state/' + state_id + '/cities',
                city_has_loaded);
		}
    });

/*
    $("select[@name=cities]").change(function(){
        $("select[@name=neighborhood_id]").hide();
        var city_id = this.options[this.selectedIndex].value;
        $.get(url + '/city/' + city_id + '/neighborhoods',
                neighborhood_has_loaded);
    });
*/

    // Fire the change on the country to start the process
    $("select[@name=country]").change();
});


function state_has_loaded(xml) {
    populate_select_with_xml('state', xml);

    var select = $('select[@name=state]')[0];
    
    if (select.length > 1) {
        preset_select_element(select, 'state');
        $(select)
            .siblings().show().end()
            .show().change();
    }
    else {
        // No staes, so populate the city list from the country id.
        var country_id = $("select[@name=country]").val();
        $.get(url + '/country/' + country_id + '/cities',
                city_has_loaded);

        // Also hide the "Add States" item
        $(select).siblings().hide();
    }
}


function city_has_loaded(xml) {
    populate_select_with_xml('city', xml);

    var select = $('select[@name=city]')[0];

    if (!select.length) {
        // Hide the Add neighborhood link
        $("select[@name=neighborhood_id]").siblings().hide();
        return;
    }

    $("select[@name=neighborhood_id]").siblings().show();
    preset_select_element(select, 'city');
    $(select).change().show();

}


function neighborhood_has_loaded(xml) {
    populate_select_with_xml('neighborhood', xml);

    var select = $('select[@name=neighborhood_id]')[0];
    
    // Prepend an empty option to the beginning of the select list
    $(select).prepend(new Option("", ""));
    select.selectedIndex = -1; // deselect

    preset_select_element(select, 'neighborhood_id');
    $(select).show();
}


/*
 * Examine the hidden elements prepared by the controller for the view to find
 * out what the loaded state, city, and neighborhood values should be.
 *
 * @param select => DOM object representing the select to update
 * @param name => full field name of the hidden input element
 */
function preset_select_element(select, name) { 
    // Check for an existing value for the state in the hidden input
    // fields
    var input = $("input[@name=" + name + "]");
    if (input && input.val()) {
        $(select).find("option[@value=" + input.val() + "]")
            .each(function(){ this.selected = true; })
        .end();

    }

    // Remove the input so it's not rechecked or sent to the server
    input.remove();
}


/*
 * Take the XML response from the /admin/geography/xml query and populate the
 * requested select input.
 */
function populate_select_with_xml(name, xml)
{
    var select = $('select[@name=' + name + ']');
    var field = $("question/field", xml).text();

    select.empty(); // clear the select to begin with

	if (name == 'state') {
        var option = new Option('State/Province');

    	var city_select = $('select[@name=city]');
    	city_select.empty(); 
        var city_option = new Option('City');
    	city_option.value = '';
    	city_select.append(city_option);
	}
	if (name == 'city') {
        var option = new Option('City');
	}
    option.value = '';

    select.append(option);

    $('answer/' + field, xml).each(function(){
        var id = $(this).attr('id');
        var text = $(this).text();

        var option = new Option(text);
        option.value = id;

        select.append(option);
    });
}

