document.lib = {};
var lib = document.lib;
document.lib.form_refresh = function() {
    $('div.require .control span.require').remove();
    $('div.require .control').append('<span class="require">*</span>');
}
$(document).ready(function()
{
    if ($('table.grid').size() > 0)
    {
        $('table.grid input:button').click(function() {
            $('tr', $(this).parent().parent().parent()).click();
        });
        $('table.grid input:checkbox').click(function() {
            this.checked = !this.checked;
            return true;
        });
        $('table.grid tr').click(function() {
            var state = 0;
            $('input:checkbox', $(this)).each(function() {
                this.checked = !this.checked;
                state = this.checked;
            });
            if (state) $(this).addClass('selected');
            else $(this).removeClass('selected');
        });
        $('table.grid').each(function() {
            this.get_selected = function()
            {
                return $.makeArray($('input:checked', $(this)).map(function() { return this.value;}));
            }
        });
        $('table.grid tr')
        .mouseover(function() {
            $(this).addClass('hover');
        })
        .mouseout(function() {
            $(this).removeClass('hover');
        });
    }
    $('a.help').popup({
        centerBrowser: 1,
        resizable: 1,
        scrollbars: 1,
        width: 500,
        height: 500
    });

    var dialog = document.getElementById('dialog');

    dialog.show = function(title, content, ok, cancel, width, height) {

        var params = {
            title: title,
            position: 'center'
        };

        if (width) params.width = width;
        if (height) params.height = height;

        if (ok || cancel)
        {
            params.buttons = {};
        }

        if (ok)
        {
            params.buttons["Ok"] = function() { ok(); $(this).dialog('close'); }
        }
        if (cancel)
        {
            params.buttons["Cancel"] = function() { cancel(); $(this).dialog('close'); }
        }

        $('#dialog').html(content).dialog(params);
        document.lib.form_refresh();
    }
    dialog.display = function(content, ok, cancel, width, height) {
        $('#dialog').dialog('close');
        dialog.show('Simple Savings', content, ok, cancel, width, height);
    }
    dialog.remove = function() {
        $('#dialog').dialog('close');
    }
    dialog.widget = function(name, vars, loading) {
        if (loading == undefined) loading = 'Loading...';
        dialog.display(loading);
        $.get('/widget/'+name+'/', vars, function(res) {
            dialog.redisplay(res.html, dialog.on_ok, dialog.on_cancel, res.width, res.height);
        }, 'json');
    }
    dialog.redisplay = function(html, ok, cancel, width, height) {
        dialog.display(html, ok, cancel, width, height);
    }
    dialog.content = function(html) {
        $('#dialog').html(html);
    }
    dialog.page = function(url, ok, cancel, width, height) {
        dialog.display('<iframe src="'+url+'" frameborder="0" marginheight="0" marginwidth="0"'
            +' width="'+(width-40)+'" height="'+(height-55)+'" scrolling="auto"></iframe>',
            ok, cancel, width, height);
    }
    document.dialog = dialog;

    document.lib.form_refresh();

    if ($('form span.error').size())
    {
        dialog.show('Form Problems', ' <p style="text-align: center;">Please look for the <span style="color: red;">'
            +'red error messages</span>, correct any problems, then try submitting the form again. Thanks!</p>');
    }
    if ($('#messages div').size())
    {
        // some agents (android, at least) seem to run body onload before .html() works, so fire
        // the messages popup after a short delay. yeah, shonky...
        setTimeout("document.dialog.show('Messages', $('#messages').html());", 300);
        setTimeout('document.dialog.remove()', 4000);
    }
    if ($.fn.inFieldLabels)
        $('form.general label').inFieldLabels();

    // turns out there is no sane way to only display the editor for workable browsers, as some mobile browsers
    // cheerfully say they support contentEditable, when they just don't. so, go off user agent...
    if (($.browser.msie || $.browser.mozilla || $.browser.webkit)
        && !navigator.userAgent.match(/(ipod|iphone|ipad|android|symbian)/i))
    {
        document.editor_callback_image = function(path) {
            $('textarea.editor').tinymce().execCommand('mceInsertRawHTML', false, '<img src="'+path+'" />');
        }
        $('textarea.editor').tinymce({
            script_url : '/js/tiny_mce/tiny_mce.js',
            gecko_spellcheck : true,
            plugins: 'paste',
            paste_use_dialog : false,
            paste_auto_cleanup_on_paste : true,
            paste_retain_style_properties: "",
            paste_strip_class_attributes : "all",
            paste_remove_spans : true,
            paste_remove_styles : true,
            paste_preprocess: function(pl, o) {
                o.content = o.content.replace(/<font.*?>/i, '').replace(/<\/font>/i, '');
            },
            theme : 'advanced',
            theme_advanced_buttons1: 'bold,italic,underline,strikethrough,link,undo,redo,numlist,bullist,ssimages',
            theme_advanced_buttons2: '',
            theme_advanced_buttons3: '',
            theme_advanced_buttons4: '',
            theme_advanced_toolbar_location: 'top',
            theme_advanced_toolbar_align : 'center',
            theme_advanced_statusbar_location : 'none',
            theme_advanced_path : false,
            font_size_style_values : "8pt,10pt,12pt,14pt,18pt,24pt,36pt",
            convert_fonts_to_spans : true,
            relative_urls : false,
            content_css: '/css/richedit.css',
            setup: function(ed) {
                ed.addButton('ssimages', {
                    title: 'Images',
                    image: '/images/icon/toolbar/image.png',
                    onclick: function() {
                        document.dialog.widget('filebrowser', { 'callback': 'document.editor_callback_image' });
                    }
                });
            }
        });
        $('textarea.editor').after('<input type="hidden" name="editor_ok" />');
    }

    // disable submit buttons after first click, for the dedicated i-must-double-click-eveything crowd
    // note: cannot be a proper html disabled=true, as that removes the submit button from the POST vars
    $('form input:submit').click(function(e) {
        if (this.clicked) return false;
        this.clicked = true;
    });
});

$.toJSON = JSON.stringify;

