/*
# CKEDITOR Edit-In Place jQuery Plugin.
# Created By Dave Earley.
# www.Dave-Earley.com
*/

$j.fn.ckeip = function (options, callback) {

    var original_html = $j(this);
    var defaults = {
        e_height: '10',
        data: {}, 
		e_url: '',
        e_hover_color: '#eeeeee',
        ckeditor_config: '',
        e_width: '50'
    };
    var settings = $j.extend({}, defaults, options);	

    return this.each(function () {
        var eip_html = $j(this).html();
        var u_id = Math.floor(Math.random() * 99999999);

//      $j(this).before("<div id='ckeip_" + u_id + "'  style='display:none;'><textarea id ='ckeip_e_" + u_id + "' cols='" + settings.e_width + "' rows='" + settings.e_height + "'  >" + eip_html + "</textarea>  <br /><a href='#' id='save_ckeip_" + u_id + "'>Save</a> <a href='#' id='cancel_ckeip_" + u_id + "'>Canel </a></div>");
        $j(this).before("<div id='ckeip_" + u_id + "'  style='display:none;'><textarea id ='ckeip_e_" + u_id + "' cols='" + settings.e_width + "' rows='" + settings.e_height + "'  >" + eip_html + "</textarea>  <br /><input type='button' id='save_ckeip_" + u_id + "' value='Save'> <input type='button' id='cancel_ckeip_" + u_id + "' value='Cancel'> </div>");

        $j('#ckeip_e_' + u_id + '').ckeditor(settings.ckeditor_config);
				
				var editor = $j('#ckeip_e_' + u_id + '').ckeditorGet();
				
				CKFinder.setupCKEditor(editor, '/ckfinder/');

        $j(this).bind("click", function () {

            $j(this).hide();
            $j('#ckeip_' + u_id + '').show();

        });

        $j(this).hover(function () {
            $j(this).css({
                backgroundColor: settings.e_hover_color
            });
        }, function () {
            $j(this).css({
                backgroundColor: ''
            });
        });


        $j("#cancel_ckeip_" + u_id + "").click(function () {
            $j('#ckeip_' + u_id + '').hide();
            $j(original_html).fadeIn();
            return false;
        });

        $j("#save_ckeip_" + u_id + "").click(function () {
            var ckeip_html = $j('#ckeip_e_' + u_id + '').val();
            $j.post(settings.e_url, {
                content: ckeip_html,
                data: settings.data
            }, function (response) {
                if (typeof callback == "function") callback(response);

                $j(original_html).html(ckeip_html);
                $j('#ckeip_' + u_id + '').hide();
                $j(original_html).fadeIn();

            });;
            return false;

        });

    });
};
