var update_location = function(){
    
    if ($("#id_location").val() != ''){
        $.ajax({
          url: '/api/location/update/',
          data: 'where=' + $("#id_location").val(), 
          success: function(data) {
            if(data.success == true){
                location_toggle()
                $("#current_location_text").html($("#id_location").val());
            }
          }
        });
    }else{
        location_toggle();
    }
}

var location_toggle = function(){
    $("#location-change-box").toggle('slide', {direction: 'up'}, 600);
}

$(document).ready(function() {
    
    /* Initialize InField labels */
    $('#search_form label').inFieldLabels();
    $('#search_form input').attr('autocomplete', 'off');
    
    /* Focus search on load */
    $('#search_form #id_q').focus(); 
    
    /* Search Autocomplete */

    $('#id_q').autocomplete('/api/search/', {
        dataType: 'json',
        parse: function(data) {
            return $.map(data, function(row) {
                return { data:row, value:row[1], result:row[0] };
            });
        }
        }).result(
            function(e, data, value) {
                $("#id_q_pk").val(value);
            }
        );

    $("#change_location_button").click(location_toggle);
    $("#change_location_submit").click(update_location);
    
    $("#id_location").focus( function() {
        $(this).val("");
    });
    $("#id_location").blur( function() {
        
        if( $(this).val() != '' && $(this).val() != $(this).attr('title')) {
            update_location();
        }else{
            $(this).val( $(this).attr('title') );
            location_toggle();
        }
        
    });
    
    /* Search Focus/Blur */
    $("#id_q").focus( function(){
        $("#search_input").addClass("focused");
    });
    $("#id_q").blur( function(){
        $("#search_input").removeClass("focused");
    });


    $(".phone-toggle").toggle(
        function(){
            $(".phone-text", this).hide();
            $(".phone", this).fadeIn();
        },
        function(){
            $(".phone-text", this).fadeIn();
            $(".phone", this).hide();
        }
    );

});