// site specific javascript stuff

$(document).ready( function(){
    $('#contact-compose-form').each( contact_init );
});

function contact_init(){
    //console.log('contact_init()');
   
    // by default, hide the location pulldown until a department is chosen
    $('#edit-location-wrapper').hide(); 
    $('#edit-department').change( cb_dept_change );
    // if errors are showing, trigger the change event to get the location list
    $('div.messages.error').each( function(){ 
        $('#edit-department').trigger('change');
    });

    //console.log('contact_init() done');
}

function cb_dept_change(evt){
    //console.log('cb_dept_change()');
    // get the selected options value, which is the dept id we want
    var dept_tid = $(this).val(); 
    //console.log('  - dept tid: ', dept_tid );
    if( dept_tid ){
        // get the json data for all valid locations that have this dept
        $.getJSON('http://www.jordans.ca/ajax/contact_email.php', 
            { dept_tid:dept_tid }, cb_load_locations );
    }else{
        $('#edit-location-wrapper').hide(); 
    } 
}

// ajax function to get location data for a given dept_id
function cb_load_locations( locations ){
    // locations is a json array of tid:names
    // delete any locations except 'please choose'
    $('#edit-location option[value!=""]').remove(); 
    // append the new option to the select list 
    $.each( locations, function(k,v){
        var el = "<option value='"+k+"'>"+v+"</option>";
        $('select#edit-location').append(el);
    });
    // if the choice was "General Enquiry", pre-select Vancouver and don't show
    if( $('select#edit-department option[value=92]').attr('selected') ){
        $('#edit-location option[value=""]').remove();
    }else{
        // show the locations pulldown
        $('#edit-location-wrapper').show(300);
    }
}


