var retry_update_time = 10000;

function updateCounties(districts_id, counties_id, action, format, countytext) {
    
    if(districts_id == null)
        districts_id = 'districts';
    
    if(counties_id == null)
        counties_id = 'counties';
    
    if(action == null)
        action = 'getCounties';
    
    if(format == null)
        format = ['cou_id', 'cou_name'];

    if(countytext == null)
    	countytext = 'Concelho';
    
    if($F(districts_id) == 0) {
        emptySelect($(counties_id));
        updateSelect($(counties_id), 
                 [], 
                 format, 
                 countytext);
        $(counties_id).disabled = true;
        return false;
    }
        
    
    updateSelect($(counties_id), 
                 [], 
                 format, 
                 'A actualizar...');
    
    $(districts_id).disabled = true;
    $(counties_id).disabled = true;
    
    new Ajax.Request('/ajax/'+action+'/'+$F(districts_id), 
                    {method: 'get',
                          onSuccess: function(transport) {
                              
                                         $(counties_id).disabled = false;
                                         $(districts_id).disabled = false;
                              
                                         emptySelect($(counties_id));
                                         updateSelect($(counties_id), 
                                                      transport.responseJSON, 
                                                      format, 
                                                      countytext);
                                     },
                          onFailure: function(transport) {
                              
                                         updateSelect($(counties_id), 
                                                      [],
                                                      format, 
                                                      'Erro a carregar concelhos..');
                                         
                                         //setTimeout('updateCounties('+$F(districts_id)+')', retry_update_time);
                                     }
                            });
    return false;
}
