jQuery(document).ready(function(){
    jQuery('#wghs_add_form').submit(wghs_add_form_submit);
    jQuery('#wghs_search_location').click(wghs_search_location);
    jQuery('#wghs_suggestions .wghs_close').live('click',wghs_hide_suggestions);
    jQuery('#wghs_locations_list a').live('click', wghs_save_suggestion);
    jQuery('#wghs_clear_location').live('click', wghs_clear_location);
});

function wghs_add_form_submit(){
    frm = jQuery('#wghs_add_form');
    if(!frm.find('input[name=wghs_location_id]').val()){
        alert('Please enter the location ID');
        return false;
    }
    return true;
}

function wghs_search_location(){
    jQuery('#wghs_search_location').attr('disabled','disabled');
    data = {
        wghs_ajx_action:'search_location',
        location:jQuery('#wghs_location').val(),
        location_parent:jQuery('#wghs_location_parent').val()
    }
    jQuery.ajax({
        type:'POST',
        url:location.href,
        data:data,
        dataType:'json',
        success:function(resp){
            jQuery('#wghs_suggestions').html(resp.text).slideDown();
            jQuery('#wghs_search_location').removeAttr('disabled');            
        }
    });
}

function wghs_hide_suggestions(){
    jQuery('#wghs_suggestions').slideUp(function(){jQuery(this).html('')});
    return false;
}

function wghs_save_suggestion(){
    jQuery('#wghs_location').unbind('change', wghs_location_change_actions);
    jQuery('#wghs_location').val(jQuery(this).attr('rel'));
    jQuery('#wghs_location_id').val(jQuery(this).attr('href').replace('#',''));
    jQuery('#wghs_location, #wghs_location_parent').attr('readonly','readonly');
    jQuery('#wghs_search_location').hide();
    jQuery('#wghs_clear_location').show();
    
    wghs_hide_suggestions();
    jQuery('#wghs_location').bind('change', wghs_location_change_actions);
}

function wghs_location_change_actions(){
    jQuery('#wghs_location_id').val('');
}

function wghs_clear_location(){
    jQuery('#wghs_clear_location').hide();
    jQuery('#wghs_search_location').show();    
    jQuery('#wghs_location, #wghs_location_parent').removeAttr('readonly');
    jQuery('#wghs_location').val('');
    jQuery('#wghs_location_id').val('');
}