/*
 * Misc. jquery utilities that are too small to justify their own file
 */

/*
 * Vertically center align things easily
 * $('#foo').vertCenter();
 */
(function ($) {
    $.fn.vertCenter = function() {
        return this.each(function(i){
            var mh = ($(this).parent().height() - $(this).height()) / 2;
            $(this).css('margin-top', mh);
        });
    };
})(jQuery);

/*
 * CharLimit - jQuery plugin for counting and limiting characters for input and textarea fields
 *
 * $Version: 10.11.2008
 * michal.podhradsky@gmail.com
 *
 * Modified by Don Laursen to save/restore textarea contents instead of just
 * cancelling keydown events.
 */
(function($){
    $.fn.charLimit = function(options){
        var defaults = {
            limit: 30,
            speed: "normal",
            counter: ".chars_used"
        }
        var o = $.extend(defaults,options);

        return this.each(function(i) {
            var obj = $(this);
            obj.after('<div class="max_chars"><span class="chars_used'+ i +'">0</span> characters used (max. ' + o.limit + ')</div>');
            function countChars(){
                $(o.counter+i).text(obj.val().length);
            }
            countChars();
            obj.previous_value = obj.val();
            obj.keydown(function(e){
                if(obj.val().length <= o.limit){
                    obj.previous_value = obj.val();
                }
            }).keyup(function(e){
                if(obj.val().length > o.limit){
                    obj.val(obj.previous_value)
                }
                countChars();
            })
        });
    }
})(jQuery);

/*
 * Make a bookmark page link
 * $(document).makeBookmark();
 */
(function ($) {
    $.fn.makeBookmarkLink = function(options) {
        var defaults = {
            bookmarkUrl: document.location,
            bookmarkTitle: document.title
        }
        var o = $.extend(defaults, options);

        /* Firefox */
        if (window.sidebar) {
            this.click(function(e) {
                e.preventDefault();
                window.sidebar.addPanel(o.bookmarkTitle, o.bookmarkUrl, "");
                return false;
            });

        /* Internet Explorer */
        } else if (window.external || document.all) {
            this.click(function(e) {
                e.preventDefault();
                // Note: IE8 seems to have disabled this
                window.external.AddFavorite(o.bookmarkUrl, o.bookmarkTitle);
                return false;
            });

        /* Opera */
        } else if (window.opera) {
            this.attr("href", o.bookmarkUrl);
            this.attr("title", o.bookmarkTitle);
            this.attr("rel", "sidebar");

        /* Other browsers do nothing */
        } else {
            this.click(function(e) {
                e.preventDefault();
                return false;
            });
        }
    }
})(jQuery);

