$.fn.extend({
    inPlaceCKEditor: function (options) {
        defaults = {
            textCancel: "Annuleren",
            textSave: "Opslaan",
            buttonsPlaceholder: '',
            preInit: function () { },
            postInit: function () { },
            save: function () { },
            cancel: function () { }
        };        
        
        $.extend(defaults, options);
        var options = defaults;
        
        var instances = $(this);
        for (i = 0; i < instances.length; i++)
        {
            initialize($(instances[i]), options);
        }
        
        function uniqid(string_length) {
            var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
            var randomstring = '';
            for (var i=0; i<string_length; i++) {
                var rnum = Math.floor(Math.random() * chars.length);
                randomstring += chars.substring(rnum,rnum+1);
            }
            
            return randomstring;
        }
        
        function initialize(self, options) {
            if (self.attr('id')) { var id = self.attr('id'); }
            else { var id = uniqid(10); self.attr('id', id); }
            
            var ckeId = "cke_" + id;
            var buttonsId = id + 'Buttons';
            
            self.click(function () {
                options.preInit(self);
                
                self.data('oldValue', self.html());

                self.ckeditor(function () {
                    addButtons();
                    options.postInit(self);
                });
            });
            
            function addButtons() {      
                $("#" + ckeId).after("<div id='" + buttonsId + "' class='cke_buttons'><input type='submit' value='" + options.textCancel + "' class='cancel' /> <input type='submit' value='" + options.textSave + "' class='save' /></div>");

                $("#" + buttonsId + " .save").click(function () {
                    destroyInstance(id, buttonsId);
                    return options.save();
                });

                $("#" + buttonsId + " .cancel").click(function () {
                    destroyInstance(id, buttonsId);
                    $("#" + id).html(self.data('oldValue'));
                   return options.cancel(); 
                });
            }

            function destroyInstance(id, buttonsId) {
                $("#" + id).ckeditorGet().destroy();
                $("#" + buttonsId).remove();
            }            
        }
    }    
});
