$(document).ready(function($){

    var debug = false;
    var focus = false;

    $("#search").submit(function() {
        return doSubmit(this);
    }).find("input[type=text]").focus(function () {
        focus = true;
        $(this).css({
            "background-image" : "none"
        });
    }).blur(function () {
        focus = false;
        input = this;
        // wait a little to prevent blink when sending empty value
        window.setTimeout(function() {
            bg(input)
        }, 50);
    }).each(function () {
        bg(this);
    });

    function bg(input) {
        // do not trim unless the result is empty
        if(focus || jQuery.trim($(input).attr("value")) != "")
            return;
        $(input).attr("value","").css({
            "background-image":"url('graphics/google.png')",
            "background-repeat" : "no-repeat",
            "background-position" : '0.4em 0.3em'
        });
    }
    
    function doSubmit(form) {
        var input = $("input[type=text]",form);
        // trim
        input.attr("value",jQuery.trim(input.attr("value")));
        // validate
        if(input.attr("value") == "") {
            input.focus().css({ "border" : "2px solid red" });
            return false;
        }
        // log
        if(typeof _gaq == "object") {
            _gaq.push(["_trackEvent", "search", "Google", input.attr("value"), 1]);
            if(debug)
                document.title = "GA OK";
        } else if(debug) {
            document.title = "GA N/A & debug";
        }
        // return
        if(debug)
            return false;
        return true;
    }

});
