var IE6 = null;

//  jQuery extension
$.extend({
    refresh: function()
    {
        window.location.reload();
    },
    
    prompt: function(title, content /*, buttons */)
    {
        var dlg = $('#prompt_dialog');
        var buttons = {"OK":function(){ $(this).dialog('close'); }};

        if (arguments.length > 2) buttons = arguments[2];

        if (typeof(content) == "string")
        {
            if (dlg.length == 0)
            {
                var body = $("body");
                body.append("<div id='prompt_dialog'></div>");
                dlg = $('#prompt_dialog');
                dlg.dialog({
                    autoOpen:false,
                    modal:true,
                    width:'auto'
                });
            }

            dlg.html(content);
        }
        else
        {
            dlg = $(content);
            dlg.dialog({
                autoOpen:false,
                modal:true,
                width:'auto'
            });
        }

        dlg.dialog('option', 'title', title);
        dlg.dialog('option', 'buttons', buttons);
        dlg.dialog('option', 'stack', true);
        dlg.fix();
        dlg.dialog('open');
    },

    promptFromUrl: function(title, promptSource, buttons)
    {
        $.ajax({
            url:promptSource,
            async:false,
            dataType:"html",
            success:function(data)
            {
                $.prompt(title, data, buttons);
            }
        });
        
    },

    htmlDialogFromUrl: function(title, promptSource, buttons)
    {
        $.ajax({
            url:promptSource,
            async:false,
            dataType:"html",
            success:function(data)
            {
                $.prompt(title, data, buttons);
            }
        });

    },

    confirm: function(title, message, yes, no)
    {
        var defaultAction = function(){$(this).dialog('close');};
        if (yes == null) yes = defaultAction;
        if (no == null) no = defaultAction;
        $.prompt(title, message, {
            "Yes": yes,
            "No": no
        });
    },

    //  Loads the HTML for the form and displays it in a dialog
    //  box. When user clicks OK the form is submitted and the result
    //  is processed. If the result status code is 200 then the
    //  result HTML is passed to successAction. If the result is 201 then
    //  the form is re-displayed with the updated HTML.
    formDialog: function(
        id,
        title,
        formSource,
        successAction
        )
    {
        var options = (arguments.length > 4) ? arguments[4] : {};
        var success_handler = function(data, textStatus)
            {
                var div = null;
                var form = null;
                var html = "<div id='" + id + "' style='display:none;'>";
                var initForm = function()
                {

                };

                html += data;
                html += "</div>";
                div = $(html);
                div.appendTo("body");

                div.data('initForm', function()
                {
                    form = div.find("form");
                    trace("Form dialog = " + form.length);

                    form.ajaxForm({
                        async:false,
                        beforeSubmit:function(formData)
                        {
                            var validate = form.data('validate');
                            if ((validate == null) || (validate == undefined)) return true;
                            return validate(formData);
                        },
                        complete:function(request/*, textStatus*/)
                        {
                            var status = request.status;
                            var response = request.responseText;

                            if (status == 0)
                            {
                                if (response.charAt(0) == "!")
                                {
                                    status = 201;
                                    response = response.substring(1);
                                }
                                else status = 200;
                            }

                            if (status == 200)
                            {
                                $("#"+id).each(function(){
                                    $(this).dialog('close');
                                    $(this).dialog('destroy');
                                    $(this).remove();
                                });
                                successAction(response);
                            }
                            else if (status == 201)
                            {
                                $("#"+id).html(response);
                                $("#"+id).fix();
                                div.data('initForm')();
                            }
                            else
                            {
                                trace("Request failed!");
                            }

                        }
                    });
                });

                div.data('initForm')();

                $.prompt(title, $("#"+id)[0], {
                    "Cancel":function()
                    {
                        $(this).dialog('close');
                        $(this).dialog('destroy');
                        $(this).remove();
                    },
                    "OK":function()
                    {
                        form.submit();
                    }
                })
            };

        if (('mode' in options) && (options.mode == 'html'))
        {
            success_handler(formSource, 'success');
        }
        else
        {
            $.ajax({
                url:formSource,
                async:false,
                dataType:"html",
                cache:false,
                error:function(request, textStatus, errorThrown)
                {
                    trace("Failed to get form from " + formSource);
                },
                success:success_handler
            });

        }

    },

    popup: function(target, url_or_html, options)
    {
        var div = $("#popup");

        if (options == null) options = {};

        if (div.length == 0)
        {
            var ie6 = (IE6 != null);
            var html = '';

            if (ie6)
            {
                html = "<div id='popup' class='popup_ie6' style='display:none;'>";
            }
            else
            {
                html = "<div id='popup' class='popup' style='display:none;'>";
                html += "<div class='popup-tl'></div>";
                html += "<div class='popup-tr'></div>";
                html += "<div class='popup-bl'></div>";
                html += "<div class='popup-br'></div>";
                html += "<div class='popup-t'></div>";
                html += "<div class='popup-l'></div>";
                html += "<div class='popup-r'></div>";
                html += "<div class='popup-b'></div>";
                html += "<img class='popup-callout' src='/images/popup_callout.png'></img>";
            }
            html += "<div class='popup-content'></div>";
            html += "</div>"
            $("body").prepend(html);
            div = $("#popup");
            div.data('content', div.children(".popup-content"));

            div.data('show', function(popup_target, html)
            {
                var offset = $(popup_target).offset();
                var width = $(popup_target).outerWidth();
                div.data('content').html(html);

                div.css({
                    left: offset.left + width,
                    top: offset.top
                });
                div.show();
            });
        }

        var content = div.data('content');

        content.attr('class', 'popup-content');
        if ('userClass' in options)
        {
            content.addClass(options.userClass);
        }

        if (!('type' in options) || (options.type == 'url'))
        {
            $.get(
                url_or_html,
                null,
                function(responseText, textStatus)
                {
                    div.data('show')(target, responseText);
                }
            );
        }
        else if (options.type == 'html')
        {
            div.data('show')(target, url_or_html);
        }
        else
        {
            assert(false, "Invalid popup content type: " + options.type);
        }
    },

    hidePopup: function()
    {
        $("#popup").hide();
    }
});

$.fn.extend({

    formDialog: function(
        title,
        contentUrl,
        formUrl,
        editButton
    )
    {
        var div = this;
        var div_id = this[0].id;
        var edit = $(editButton);

        edit.click(function() {
            $.formDialog(
                div_id + "_dialogForm",
                title,
                formUrl,
                function(data)
                {
                    div.html(data);
                }
            );
        });

        div.load(contentUrl);
    },

    formInline: function(
        formUrl,
        successHandler
    )
    {
        var div = this;
        var loaded = function() {
            div.fix();
            div.find("form").ajaxForm({
                complete:function(request, textStatus)
                {
                    if (request.status == 200)
                    {
                        if (successHandler != null)
                        {
                            successHandler(request.responseText);
                        }
                        else
                        {
                            div.html(request.responseText);
                        }
                    }
                    else if (request.status == 201)
                    {
                        div.html(request.responseText);
                        loaded();
                    }
                    div.fix();
                }
            });
        };

        if (formUrl == null)
            loaded();
        else
            div.load(formUrl, null, loaded);
    },

    formSection:function(
        param,
        args
    )
    {
        var data = null;

        if (typeof(param) == 'string')
        {
            data = this.data('formSection');

            if (typeof(data) != 'undefined')
            {
                if (param == 'edit')
                {
                    if (data.editing == false)
                    {
                        data.edit.click();
                    }
                }
                else if (param == 'readonly')
                {
                    if (data.editing == false)
                    {
                        data.edit.toggle(param == false);
                    }
                }
            }
        }
        else // create
        {
            data = {
              save: $(param.saveButton),
              edit: $(param.editButton),
              cancel: $(param.cancelButton),
              editing: false,
              div: this
            };

            data.div.data('formSection', data);

            data.initForm = function()
            {
                data.form = data.div.find('form');
                data.form.ajaxForm({
                    async:false,
                    complete:function(request, textStatus)
                    {
                        if (request.status == 200)
                        {
                            data.div.html(request.responseText);
                            data.save.hide();
                            data.cancel.hide();
                            data.edit.show();
                            data.editing = false;
                        }
                        else if (request.status == 201)
                        {
                            data.div.html(request.responseText);
                            data.initForm();
                        }
                    }
                });
            };

            data.edit.click(function(){
                data.div.load(
                    param.editUrl,
                    null,
                    function(text, status, request)
                    {
                        if (request.status == 200)
                        {
                            data.edit.hide();
                            data.save.show();
                            data.cancel.show();
                            data.div.fix();
                            data.initForm();
                            data.editing = true;
                        }
                    }
                );
                return false;
            });
            data.save.click(function(){
                data.form.submit();
                return false;
            });
            data.cancel.click(function(){
                data.div.load(param.showUrl);
                data.save.hide();
                data.cancel.hide();
                data.edit.show();
                data.editing = false;
                return false;
            });

            data.save.hide();
            data.cancel.hide();
            data.edit.show();

            $.get(param.showUrl, null, function(response)
            {
                if (data.editing == false) data.div.html(response);
            });
        }
    },

    closeParentDialog: function()
    {
        $(this).closest(".ui-dialog-content").dialog("close");
    },

    reloadCurrentTab: function()
    {
        var the_tabs = $(this).closest(".ui-tabs");
        the_tabs.tabs('load', the_tabs.tabs('option', 'selected'));
    },

    fix: function()
    {
        if (IE6 != null) IE6.fix(this);
    }
})

// Time helper class
var Time = {
  'to_min': function(val)
  {
      if (typeof(val) == 'string') val = parseInt(val);
      return (Math.floor(val / 100) * 60) + (val % 100);
  },
  'to_int': function(val)
  {
      if (typeof(val) == 'string') val = parseInt(val);
      return (Math.floor(val / 60) * 100) + (val % 60);
  },
  'add': function(val, delta)
  {
      return Time.to_int(Time.to_min(val) + delta);
  },
  'minutes_to_hours_str': function(val)
  {
      var i = (typeof(val) == 'string') ? parseInt(val) : val;
      var s = (i % 60).toString();
      if (s.length == 1) s = '0' + s;
      s = Math.floor(i / 60).toString() + ':' + s;
      return s;
  },
  'seconds_to_minutes_str': function(val)
  {
      return Time.minutes_to_hours_str(val);
  },
  'to_time_str': function(val)
  {
    var hh = Math.floor(val / 100);
    var h12 = hh % 12;
    var mm = val % 100;
    var str = '';

    str += (hh == 0) ? '12' : h12.toString();
    str += ':';
    if (mm < 10) str += '0';
    str += mm.toString();
    str += ' ';
    str += (hh >= 12) ? 'PM' : 'AM';

    return str;
  }  
};

