Toggle() needs to be clicked twice the first time
<p>I have a form that use this collapse.js to show/hide fieldsets with toggle(). Those who are familiar with Django will recognize this function because its exactly the one used in django admin. Now, I use localStorage to make the form remember the toggle state (show/hide) when reloaded.</p>

<p>I have managed to make it works. However, I still have a little bug that I cant fix yet. When the localStorage is true, the fieldset is displayed on reload. That is the expected behaviour. The bug is that the user must click two-times on "Hide" to make the fieldset toggled again. After the double-click, the user have to click only one time on "Hide" or "Show" to toggle the fieldset.</p>

<p>Do you have any clue about that?</p>

<p>jsFiddle: <a href="http://jsfiddle.net/sfF99/5/" rel="nofollow">jsfiddle.net/sfF99/5/</a></p>

<p>collapse.js</p>

<pre><code>(function($) {
$(document).ready(function() {
    // Add anchor tag for Show/Hide link
    $("fieldset.collapse").each(function(i, elem) {
        // Don't hide if fields in this fieldset have errors
        key = 'fieldsetcollapser'+i;
        if(typeof(window.localStorage) != 'undefined'){ 
            if(window.localStorage.getItem (key)){
                $(elem).find("h2").first().append(' (&lt;a id='+ key +' " class="collapse-toggle" href="#"&gt;' + gettext("Hide") + '&lt;/a&gt;)');
            }   else {
                $(elem).addClass("collapsed").find("h2").first().append(' (&lt;a id='+ key +' " class="collapse-toggle" href="#"&gt;' + gettext("Show") + '&lt;/a&gt;)');
            }   
        } 
        else{ 
            throw "window.localStorage, not defined"; 
    }

    });
    // Add toggle to anchor tag
    $("fieldset.collapse a.collapse-toggle").toggle(
        function() { // Show
            $(this).text(gettext("Hide")).closest("fieldset").removeClass("collapsed").trigger("show.fieldset", [$(this).attr("id")]);
            window.localStorage.setItem($(this).attr("id"),true)
            return false;
        },
        function() { // Hide
            $(this).text(gettext("Show")).closest("fieldset").addClass("collapsed").trigger("hide.fieldset", [$(this).attr("id")]);
            window.localStorage.removeItem($(this).attr("id"))
            return false;
        }
    );
});
})(django.jQuery);
</code></pre>
