﻿var kp = {};

kp.log = function(message) {
    if (window.console && window.console.log)
        console.log(message);
};
/* jQuery extensions */
(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;
            }
        });
        return this;
    };
    $.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);
        });
        return this;
    };
    $.fn.mvc_ajaxForm = function(options) {
        if (options == null)
            options = {};
        $.mvc_loadUrl = $(this).attr('action');
        options.error = function(request, status, error) {
            kp.log({ request: request, status: status, error: error });
            $.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.runScript('jquery.form.js').ajaxForm(options);
    };
    $.fn.mvc_validate = function(options) {
        if (options == null)
            options = {};
        if (!options.errorPlacement) {
            options.errorPlacement = function(error, element) {
                var error_holder = $($.jq_escape('#' + element.attr('id') + '_Error'), $(element).parents('form'));
                if (error_holder.length > 0)
                    error.appendTo(error_holder);
                else
                    error.insertAfter(element);
            };
        }
        return this.runScript('jquery.validate.min.js').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 = 490;
        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);
            });
        });
        return this;
    };
    $.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);
        });
        return this;
    };
    $.fn.mvc_confirm = function(text, callbackYes, callbackNo) {
        $('.ui-confirm', self).remove();
        var self = this;
        $(kp.templateConfirm).appendTo(self).effect('drop', { direction: 'up', mode: 'show' }, 250);
        $('.ui-confirm .message', self).html(text);
        $('.ui-confirm .yes', self).click(function(e) {
            $('.ui-confirm', self).remove();
            if (callbackYes)
                callbackYes(e);
        });
        $('.ui-confirm .no', self).click(function(e) {
            $('.ui-confirm', self).remove();
            if (callbackNo)
                callbackNo(e);
        });
        $('.ui-confirm .close', self).click(function(e) {
            $('.ui-confirm', self).remove();
        });
        return this;
    };
    $.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();
            }
        }
        return this;
    };
    $.fn.progress = function() {
        $('.ui-icon', this).each(function(i) {
            $(this).hide().after('<span class="ui-progress"></span>');
        });
        return this;
    };
    $.fn.complete = function() {
        $('.ui-progress', this).remove();
        $('.ui-icon', this).show();
        return this;
    };
    $.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';
        return this.datepicker(options);
    };
    $.fn.clickOutside = function(e) {
        this.bind('clickOutside', e);
        return this;
    };
})(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 (window.console && window.console.log) {
            kp.log('jQuery error happened!');
            kp.log('Last used url: ' + jQuery.mvc_loadUrl);
            if (!jQuery.mvc_errorPage)
                jQuery.mvc_errorPage = '/Error';
            window.open(jQuery.mvc_errorPage);
        }
        if (msg)
            alert(msg);
        else
            alert('Unknown error!');
    },

    jq_escape: function(jq) {
        return jq.replace(/([:\.\[\]])/g, '\\$1');
    }
});
/* special events */
jQuery.event.special.clickOutside = {
    setup: function(data, namespaces) {
        if (!kp.clickOutsideListeners)
            kp.clickOutsideListeners = [];
        kp.clickOutsideListeners.push(this);
        jQuery(document).bind('click', jQuery.event.special.clickOutside.handler);
    },

    teardown: function(namespaces) {
        jQuery(document).unbind('click', jQuery.event.special.clickOutside.handler);
        kp.clickOutsideListeners = null;
    },

    handler: function(event) {
        event.type = 'clickOutside';
        jQuery(kp.clickOutsideListeners).each(function(i) {
            var listener = this;
            if (event.target == listener)
                return;
            var inside = false;
            jQuery(event.target).parents().each(function() {
                if (this == listener) {
                    inside = true;
                    return false;
                }
            });
            if (inside)
                return;
            jQuery(this).trigger(event);
        });
    }
};

/* document ready defaults */
$(function() {
    $('.ui-hover').live('mouseover', function() {
        var ctx = this;
        if ($(ctx).hasClass('ui-state-default') || $(ctx).hasClass('ui-link'))
            ctx = $(ctx).parent();
        $('.ui-state-default', ctx).each(function(i) {
            if (!$(this).hasClass('ui-state-disabled'))
                $(this).addClass('ui-state-hover');
        });
        $('.ui-link', ctx).each(function(i) {
            $(this).addClass('ui-link-hover');
        });
    });
    $('.ui-hover').live('mouseout', function() {
        var ctx = this;
        if ($(ctx).hasClass('ui-state-default') || $(ctx).hasClass('ui-link'))
            ctx = $(ctx).parent();
        $('.ui-state-default', ctx).each(function(i) {
            if (!$(this).hasClass('ui-state-disabled'))
                $(this).removeClass('ui-state-hover');
        });
        $('.ui-link', ctx).each(function(i) {
            $(this).removeClass('ui-link-hover');
        });
    });
});

kp.AjaxUpload = function(button, options) {
    $.kp_loadScript('ajaxupload.3.6.js');
    return new AjaxUpload(button, options);
};

/* misc legacy methods */
function ConfirmDelete(url, msg) {
    if (confirm(msg))
        document.location = url;
}

