function update_region_field(src, dest, clear) {
    $.getJSON('/countries/ajax/region-codes/'+$(src).val()+'/', function(json) {
       var parent = $(dest).parent();
       var value = $(dest).val()
       var name = $(dest).attr('name');
       var attributes = $(dest)[0].attributes;
       var stored = new Array(attributes.length);
       for (var index in attributes) {
	 var attribute = attributes[index];
	 if (attribute.nodeName == 'type') {
	      continue;
	 }
	 if (index == 'length') {
	      break; //weird bug?
	 }
	 var arr = new Array(2);
	 arr[0] = attribute.nodeName;
	 arr[1] = attribute.nodeValue;
	 stored[index] = arr;
       }
       var child_text = '';
       if (json.type == 'text') {
	 child_text = '<input type="text" id="'+dest.substring(1)+'" name="'+name+'"/>';
       } else {
	 child_text = '<select id="'+dest.substring(1)+'" name="'+name+'">'+json.html+'</select>';
       }
       parent.html(child_text);
       ndest = parent.children();
       for (var index in stored) {
	 var attribute = stored[index];
	 ndest.attr(attribute[0], attribute[1]);
       }
       if (!clear) {
	 ndest.val(value);
       }
    });
}


/* 
    This function will encapsulate the functionlity needed to do a country/state select
    so that it will work appropriately with a django filled form, where the change of the country
    will update a list of available regions for that country via ajax

    //Django Usage:
    form_region_manager('#id_country','#id_state',
                        '{{ form.initial.country }}','{{ form.initial.state }}',
                        '{{ form.country.data}}','{{form.state.data}}');
*/
function form_region_manager(country_id,state_id,init_country,init_state,country_data,state_data){
    var update_state=function(){  update_region_field(country_id, state_id, true) };
    $(country_id).click(update_state);
    var state_val=(init_state.length)?init_state:state_data;
    var country_val=(init_country.length)?init_country:country_data;
    // prime the select 
    $(state_id).html('<option value="'+state_val+'"></option>');
    $(state_id).val(state_val);
    $(country_id).val(country_val);
    update_region_field(country_id,state_id,false);
}


