// cookie functions http://www.quirksmode.org/js/cookies.html
        function createCookie(name,value,days)
        {
                var expires = '';
                if (days)
                {
                        var date = new Date();
                        date.setTime(date.getTime()+(days*24*60*60*1000));
                        expires = "; expires="+date.toGMTString();
                }
                document.cookie = name+"="+value+expires+"; path=/";
        }

$(document).ready(function(){
	
//livesearch

        var timeout = undefined;
        $('.search form').append('<div id="search_results"></div>');
        $('.search input[type=text]').focus(function() {
                if (this.value.length > 0) {
                    $("#search_results").show();
                }
        }).click(function() {
                if (this.value.length > 0) {
                    $("#search_results").show();
                }
        }).keyup(function() {
                if (this.value != this.lastVal && this.value.length > 0) {
                        if (timeout !== undefined) {
                                clearTimeout(timeout);
                        }

                var $this = this;

                timeout = setTimeout(function() {
                        timeout = undefined;
                        $("#search_results")
                                .slideDown('fast')
                                .load('/search/dsearch/'+ encodeURI($this.value));
                }, 200);
        }

        this.lastVal = this.value;

        }).blur(function() { $("#search_results").fadeOut('fast'); });

	if ($.support.leadingWhitespace) {
      		$('#search_results').css('opacity','.98').css('-moz-border-radius','1em').css('-webkit-border-radius','.6em');
	}

        // Escape key closes search
        $(document).keydown(function(e) { if (e.which == 27) { $("#search_results").fadeOut('fast'); } });

//preferences

    $('#settings').toggle( 
        function(){
            $(this).html('Hide Settings').attr('title','Hide the bar');
            $('.controls').show("slide", {direction: "up" }, 500);
            $('.controls-rightside').fadeIn(500); // sliding would be nice, but layout jumps around
            createCookie('show_settings_bar', '1', 365);
        },
        function(){
            $(this).html('Settings').attr('title','Tweak preferences');
            $('.controls').hide("slide", {direction: "up" }, 500);
            $('.controls-rightside').fadeOut(500);
            createCookie('show_settings_bar', '0', 365);
        }
	);

// other session settings
        
        $(".controls :input[name=platform]").change(function() {
            $(this).parents('form').submit();
        });

        $(".controls :input[name=certified_software]").click(function() {
            $(this).parents('form').submit();
        });
        
        
        // IE sometimes calls this function twice, not sure why
        var change_name_last_val;
        var change_name = function() {
            var $input = $(this);
            var val = $.trim($input.val());
            
            var back = function() {
                $('<span id="profile_name"></span>').replaceAll($input).text(val);
                $("#edit_name").show(); // the link
            };
            
            if (val == change_name_last_val) {
                return;
            }
            change_name_last_val = val;
            
            if (val == $input.data('original_value')) {
                back();
                return;
            }
            
            if (val === '') {
                val = $input.data('original_value');
                back();
                return;
            }
            
            $.ajax({
                type: 'POST',
                url: '/accounts/settings/name',
                data: {name: val},
                error: function(xhr, textStatus, errorThrown) {
                    var msg = textStatus + ': ' + xhr.statusText;
                    if (xhr.responseText.length > 1 && xhr.responseText.length < 100) {
                        msg = xhr.responseText;
                    }
                    show_message($input, "Error changing name.<br/>" + msg);
                },
                success: function(data, textStatus) {
                    $input.data('original_value', val);
                    back();
                }
            });
        };
        
        $("#edit_name").click(function() {
            var $link = $(this);
            $("#profile_name").replaceWith('<input type="text" id="profile_name_edit" value="' + $("#profile_name").text() + '"/>');
            $("#profile_name_edit")
                .data('original_value', $("#profile_name_edit").val())
                .focus()
                .select()
                .bind('change blur',change_name)
                .keypress(function(e) {
                    // in IE, an 'enter' keypress doesn't trigger change(), so we do it
                    if (e.keyCode == 13) {
                        $(this).blur();
                    }
                });
            $link.hide();
            return false;
        });

    $('a#feedback').click(function() {
        var $link = $(this);
        if ($('#feedback_box').length === 0) {
            $('#ft').after('<div id="feedback_box">'+
                '<a href="#" id="feedback_close" style="float:right">X</a>'+
                '<h2><a href="http://groups.google.com/group/fossforus">Discuss Fossfor.us on an email list</a></h2>'+
                '<h2>Or, send a short note to the developers:</h2>'+
                '<form method="POST" action="/send_note">'+
                '<textarea name="message"></textarea>'+
                '<br/>'+
                '<label for="asdf">Email (optional): <input name="asdf" value=""/></label>'+
                '<br/>'+
                '<label for="email">Email: <input name="email" value="enter your email address"/></label>'+
                '<input type="submit" value="Send" class="submit"/>'+
                '</form>'+
            '</div>');
            $('#feedback_box label[for=email]').hide();
            $('a#feedback_close').click(function() {
                $('#feedback_box').hide();
                return false;
            });
            $('#feedback_box').css({
                position: 'absolute',
                top: Math.round($link.offset().top) - $('#feedback_box')[0].offsetHeight - 10,
                left: Math.round($link.offset().left) - $('#feedback_box')[0].offsetWidth + 90,
                zIndex: 1
            });
        }
        return false;
    });

});

