﻿(function($) {
    $.fn.mvc_load = function(url, data, callback) {
        if (typeof (url) == 'undefined' || url == '')
            throw new Error('url cannot be empty.');
        $.mvc_loadUrl = url;
        this.load(url, data, function(response, status) {
            if (status == "error")
                $.mvc_error("Cannot connect to " + url);
            else {
                if (callback)
                    callback(response);
                else
                    return response;
            }
        });
    };
    $.fn.mvc_loadReplace = function(url, data, callback) {
        var self = this;
        $.mvc_get(url, data, 'html', function(response) {
            $(self).empty();
            $(self).replaceWith(response + '');
            if (callback)
                callback(response);
        });
    };
    $.fn.mvc_ajaxForm = function(options) {
        if (options == null)
            options = {};
        $.mvc_loadUrl = $(this).attr('action');
        options.error = function(request) {
            $.mvc_error("Cannot connect to " + $.mvc_loadUrl);
        };
        if (!options.target)
            options.target = this;
        var self = this;
        if (!options.success) {
            options.success = function(data) {
                if (data.validation_failed) {
                    var validator = $(self).mvc_validate();
                    for (var field in data.validation_failed) {
                        $(data.validation_failed[field]).each(function(i) {
                            if (this.success)
                                return;
                            if (field == 'exception') {
                                alert(this.message);
                                return;
                            }
                            var messages = {};
                            messages[field] = this.message;
                            validator.showErrors(messages);
                        });
                    }
                    if (options.notvalid)
                        options.notvalid(data);
                }
                else {
                    if (options.valid)
                        options.valid(data);
                }
                return false;
            };
        }
        return this.ajaxForm(options);
    };
    $.fn.mvc_validate = function(options) {
        if (options == null)
            options = {};
        if (!options.errorPlacement) {
            options.errorPlacement = function(error, element) {
                var error_holder = $('#' + element.attr('id') + '_Error', $(element).parents('form'));
                if (error_holder.length > 0)
                    error.appendTo(error_holder);
                else
                    error.insertAfter(element);
            };
        }
        return this.validate(options);
    };
    $.fn.edit_dialog = function(url, options) {
        var self = this;
        if (options == null)
            options = {};
        options.draggable = false;
        options.resizable = false;
        //options.modal = true;
        if (!options.width)
            options.width = 640;
        if (!options.height)
            options.height = 480;
        this.dialog(options);
        this.removeClass('ui-widget-content ui-dialog-content');
        this.addClass('edit-dialog');
        if (options.fixedsize)
            this.addClass('fixedsize');
        $(this).mvc_load(url, null, function(data) {
            $('.tabs', self).tabs();
            $('.tabs', self).removeClass('ui-widget-content ui-corner-all');
            $('.tabs > ul', self).removeClass('ui-widget-header ui-corner-all');
            $('.tabs .ui-tabs-panel', self).each(function(i) {
                $(this).removeClass('ui-corner-bottom');
                $(this).addClass('ui-corner-all');
            });
            $('.tabs', self).append('<div class="ui-dialog-titlebar-fake"></div>')
            $('.tabs .ui-dialog-titlebar-fake', self).append($('.ui-dialog-titlebar-close', self.parent()));

            $('.ui-dialog-titlebar-close', self).unbind('click');
            $('.ui-dialog-titlebar-close', self).click(function(e) {
                e.preventDefault();
                self.trigger('edit-dialog-close');
            });
            $('> *', self).each(function(i) {
                $(this).width(options.width);
            });
        });
    };
    $.fn.quick_dialog = function(callback1, callback2, options) {
        var self = this;
        if (options == null)
            options = {};
        options.modal = true;
        this.dialog(options);
        $('#button1', this).click(function(e) {
            if (callback1)
                callback1(e);
        });
        $('#button2', this).click(function(e) {
            if (callback2)
                callback2(e);
        });
    };
    $.fn.ckEditor = function(options) {
        if (this.length == 0)
            return;
        if (this.attr('id') == null) {
            if (options == 'close')
                return;
            else
                throw new Error('Cannot create editor on element with no id');
        }
        if (options == 'close') {
            if (typeof (eval('CKEDITOR.instances.' + this.attr('id'))) != 'undefined') {
                CKEDITOR.remove(eval('CKEDITOR.instances.' + this.attr('id')));
            }
        }
        else if (options == 'getInstance') {
            if (typeof (eval('CKEDITOR.instances.' + this.attr('id'))) != 'undefined')
                return eval('CKEDITOR.instances.' + this.attr('id'));
            return null;
        }
        else if (options == 'forceUpdate') {
            var instance = null;
            if (typeof (eval('CKEDITOR.instances.' + this.attr('id'))) != 'undefined')
                instance = eval('CKEDITOR.instances.' + this.attr('id'));
            if (instance == null)
                return;
            instance.updateElement();
            instance.resetDirty();
        }
        else {
            if (typeof (eval('CKEDITOR.instances.' + this.attr('id'))) != 'undefined')
                CKEDITOR.remove(eval('CKEDITOR.instances.' + this.attr('id')));
            CKEDITOR.replace(this.attr('id'));
            eval('CKEDITOR.instances.' + this.attr('id')).resetDirty();
            var self = this;
            if (options.change) {
                this.get(0).pollDirty = function() {
                    if (typeof (eval('CKEDITOR.instances.' + self.attr('id'))) == 'undefined')
                        return;
                    if (eval('CKEDITOR.instances.' + self.attr('id')).checkDirty()) {
                        options.change(true);
                    }
                    setTimeout(function() {
                        self.get(0).pollDirty();
                    }, 2000);
                };
                this.get(0).pollDirty();
            }
        }
    };
    $.fn.progress = function() {
        $('.ui-icon', this).each(function(i) {
            $(this).hide().after('<span class="ui-progress"></span>');
        });
    };
    $.fn.complete = function() {
        $('.ui-progress', this).remove();
        $('.ui-icon', this).show();
    };
    $.fn.mvc_datepicker = function(options) {
        var self = this;
        if (options == null)
            options = {};
        if (!options.dayNamesMin)
            options.dayNamesMin = ['Sö', 'Må', 'Ti', 'On', 'To', 'Fr', 'Lö', 'Sö'];
        if (!options.dayNames)
            options.dayNames = ['Söndag', 'Måndag', 'Tisdag', 'Onsdag', 'Torsdag', 'Fredag', 'Lördag', 'Söndag'];
        if (!options.dayNamesShort)
            options.dayNamesShort = ['Sön', 'Mån', 'Tis', 'Ons', 'Tor', 'Fre', 'Lör', 'Sön'];
        if (!options.firstDay)
            options.firstDay = 1;
        if (!options.dateFormat)
            options.dateFormat = 'yy-mm-dd';
        if (!options.showAnim)
            options.showAnim = 'slideDown';
        if (!options.duration)
            options.duration = 'fast';
        this.datepicker(options);
    };
})(jQuery);

jQuery.extend({
    mvc_get: function(url, data, dataType, callback) {
        if (url == '')
            throw new Error('url cannot be empty.');
        jQuery.mvc_loadUrl = url;
        jQuery.ajax({ url: url, data: data, dataType: dataType, success: function(data) {
            callback(data);
        }, error: function(request, textStatus, errorThrown) {
            jQuery.mvc_error("Cannot load from " + url);
        }
        });
    },

    mvc_getJSON: function(url, data, callback) {
        jQuery.mvc_get(url, data, 'json', callback);
    },

    mvc_error: function(msg) {
        if (msg == null)
            msg = "System error has occured!";
        alert(msg);
        //         if (!jQuery.mvc_errorPage)
        //             jQuery.mvc_errorPage = '/Error';
        //         window.open(jQuery.mvc_errorPage + '?url=' + jQuery.mvc_loadUrl);
    }
});