//

(function($) {

function debug(obj) {
    if (window.console && window.console.log)
    {
         window.console.log('debug: ' + obj);
    }
}


$.fn.quickoats = function(options) {
    
    if (!($('#logged_in').length)) return;
    
    var opts = $.extend($.fn.quickoats.defaults, options);
    $.fn.quickoats.opts = opts;
   
    $(".quickoats_new_item").hide();
   
    inject_editor(opts.editing_buttons, opts.save_buttons);
    inject_intro_box();
    
    $(".quickoats_new_item a").live('click', handle_new_item_button_click);
   
    $("#editor_buttons a").live('click', handle_editor_clicks);
    $("#save_buttons a").live('click', handle_save_clicks);
    
    $("#quickoats_intro_box a").live('click', handle_intro_box_clicks);
   
    $(".quickoats_delete").live('click', handle_deletes);
   
   
   
    $(window).unload(function() {
        //alert($('.editable').first().hasAttr('contenteditable'));
    
        if ($('.editable').first().attr('contenteditable') && confirm("Do you want to save the changes you've made?")) {//if yes
            $.fn.quickoats.save_changes();
        }
    });
   
   
    $(document).keypress(handle_keypresses);
   
    document.onclick = $.fn.quickoats.close;
    return $(".editable");
};

$.fn.quickoats.opts = null;


function handle_new_item_button_click() {
    
    var button = $(this);
   
    var qo_type = button.attr('quickoats_class');
        
    $.ajax({
        type: "POST",
        url: '/quickoats/get',
        data: { type: qo_type },
        success: function(data) {
            var new_post = $('<div></div>');
            $(new_post).html(data);
         
            var qo_id = $(new_post).find('.quickoats_id').text();
          
            $(new_post).find('.quickoats_id').remove();
            $(new_post[0]).addClass('editable').attr('contenteditable','true').attr('quickoats_id',qo_id);
            debug('yo');
            
            var delete_link = $('<a class="quickoats_delete" href="#">delete this post</a>').attr('quickoats_id',qo_id);
            //$(new_post[0]).after(delete_link);
            debug('yo2');
            var classnames = button.attr('quickoats_class').split(' ');
         
            for (var i in classnames)
            {
                $(new_post[0]).addClass(classnames[i]);
            }
            var x = button.parent().after(delete_link).after(new_post);
            x.next().focus();
        }
    });
   
    return false;
}




function handle_deletes() {
    
    if (!confirm("Are you sure you want to delete this post? This is PERMANENT.")) {
        return;
    }
    
    var button = $(this);
   
    var qo_id = button.attr('quickoats_id');
    
    $.ajax({
        type: "POST",
        url: '/quickoats/delete',
        data: { id: qo_id },
        success: function(data) {
            var selector = '[quickoats_id="' + qo_id + '"]';    
            //var selector2 = 'div[quickoats_id="' + qo_id + '"]';  
            
            $(selector).remove();
        }
    });
   
    return false;
}


function handle_editor_clicks(event) {
        var command_name = $(this).attr('command_name');
        var command_arg = $(this).attr('command_arg');
       
        if (command_name == 'removeBlock') {
            remove_block(command_arg);
        } 
        else if (command_name == 'removeFormatting') {
            remove_all_formatting();
        } else {
            try {
                document.execCommand(command_name, false, command_arg);
            }
            catch(err) {
                debug(err);
            }
        }
       
        var j_start = j = current_editable();
    
        if (j_start != null)
        {
            $(j_start).focus();
        }
        event.preventDefault();
        return false;
    }
    
    
    
function handle_save_clicks(event) {
        func = $(this).first().data('func');
        
        if (func) {
            func();
        }
        event.preventDefault();
        return false;
    }
    
    

function start_editing() {
    $('.editable').attr('contenteditable', 'true');
    $(".quickoats_new_item").show();
    $("#quickoats_intro_box").hide();
    $("#quickoats_editor").show();
    $("#quickoats_upload").load('/quickoats/upload');
    $("#quickoats_htmledit").load('/quickoats/htmledit');
    
    //$('.editable img').live('click', function() { alert('cunt'); });
        
    refresh_image_events();
    
    $('.aToolTip a').live('click', function() { 
         
        debug($.fn.quickoats.current_img[0].tagName);
        $.fn.quickoats.current_img.removeClass();
        $.fn.quickoats.current_img.addClass($(this).attr('image_class')); 
        
        return false; 
   });
   
   $('.editable').each(function() {
   
        var attr = $(this).attr('quickoats_content');
        
        if (!attr) {
            //alert(attr);
            
            var qo_id = $(this).attr('quickoats_id');
            var delete_link = $('<a class="quickoats_delete" href="#">delete this post</a>').attr('quickoats_id',qo_id);
            
            $(this).after(delete_link);
            
        }
        //var qo_id = $(this).attr('quickoats_id');
        
        
        
   });
   
   
   //$().attr('quickoats_id',qo_id);
    //        debug('yo');
            
    
   
    

}




function refresh_image_events() {
    $('.editable img').unbind('click');
    
    $('.editable img').click(function(el) {debug('fuck'); $.fn.quickoats.current_img = $(this); 
    return false; });
    
    $('.editable img').aToolTip({  
        clickIt: true,
        tipContent: '<a href="#" image_class="float_left">leftr</a> <a href="#" image_class="float_center">center</a> <a href="#"image_class="float_right">right</a>'  
    });
    
}




function stop_editing() {
    $('.editable').removeAttr('contenteditable');
    $(".quickoats_new_item").hide();
    $("#quickoats_intro_box").show();
    $("#quickoats_editor").hide();
    $("#quickoats_upload").dialog('close');
    $("#quickoats_htmledit").dialog('close');
    $('.editable img').unbind('click');
    $('.quickoats_delete').remove();
}







function handle_intro_box_clicks(event) {
    if (!$.browser.webkit) {
        alert('You must be using Chrome or Safari to use this editor.');
        return false;
    }
    
    start_editing();
    return false;
}


function handle_keypresses(event) {

    // Handling for Backspace Key
    // this is to prevent backspacing into other contenteditable regions
    if (event.keyCode == '8') {
        if (cursor_at_start_of_field()) {
            event.preventDefault();
            // if range is a selection, we still want to
            // delete the selection on backspace
            range.deleteContents();
        }   
    }
}


function cursor_at_start_of_field() {
    var range = window.getSelection().getRangeAt(0);
    var startoffset = range.startOffset;
     
    if (startoffset > 0) {
        return false;
    }
    
    var j_start = range.startContainer;
    
    while (! $(j_start).hasClass("editable"))
    {
        var old = j_start;
        j_start = j_start.parentNode;
        var c = j_start.firstChild;
        if (c != old) return false;
    }
    return true;
}



function current_editable() {
    
    try {
        var range = window.getSelection().getRangeAt(0);
    } catch (err)
    {
        debug(err);
        return false;
    }
    var j = range.startContainer;
    
    while (j != null && ! $(j).hasClass("editable"))
    {
        j = j.parentNode;
    }
    return j;
}



function remove_block_old(command_arg) {
    if (!current_editable()) return;

    var selected_range = window.getSelection().getRangeAt(0);
   
    //we begin at the start of the selection range...
   
    var current_node = selected_range.startContainer;
    var parent_node = current_node.parentNode;
   
    command_arg = command_arg.toLowerCase();
   
    // move up the tree until we find a tag matching
    // the type of tag we're trying to remove
    while (parent_node.nodeName.toLowerCase() != command_arg)
    {
        debug($(current_node).get(0).tagName);
        current_node = parent_node;
        parent_node = current_node.parentNode;
       
        if (parent_node == null)
            return;
    }
   
    remove_unwanted(parent_node);
    return;
}



function remove_block(command_arg) {
    if (!current_editable()) return;
    debug('found cur_editable');
    var selected_range = window.getSelection().getRangeAt(0);
   
    //we begin at the start of the selection range...
   
    var current_node = selected_range.startContainer;
    var parent_node = current_node.parentNode;
   
    command_arg = command_arg.toLowerCase();
   
    // move up the tree until we find a tag matching
    // the type of tag we're trying to remove
    
    debug(parent_node.nodeName.toLowerCase());
    
    while (parent_node.nodeName.toLowerCase() != command_arg)
    {
        debug($(current_node).get(0).tagName);
        current_node = parent_node;
        parent_node = current_node.parentNode;
       
        if (parent_node == null)
            return;
    }
   
    change_to_div(parent_node);
    return;
}



function change_to_div(dom_node) {

    var grandparent = dom_node.parentNode;
    

    var new_div = $('<div></div>');
    
    new_div.html($(dom_node).html());
    $(dom_node).replaceWith(new_div);
    
    
    return;
    
}








function remove_unwanted(dom_node) {
    // then get the (unwanted) tag's parent
    var grandparent = dom_node.parentNode;
    var blocked_siblings = dom_node.childNodes;
   
    // move the contents of the unwanted node into the parent
    while (blocked_siblings.length > 0)
    {
        grandparent.insertBefore(blocked_siblings[0], dom_node);
    }

    // finally, remove the (now empty) unwanted node
    grandparent.removeChild(dom_node);
}




function remove_all_formatting() {
    if (!current_editable()) return;
    var selected_range = window.getSelection().getRangeAt(0);
   
    //var text = selected_range
   
    //we begin at the start of the selection range...
   
    var current_node = selected_range.startContainer;
    var parent_node = current_node.parentNode;
   
    //var grandparent = dom_node.parentNode;
    
    var c = $(current_node);
    
    while (!c.hasClass('editable'))
    {
        p = c.parent();
        if (p.hasClass('editable'))
        {
            change_to_div(c.get(0));
        }
        else if (c.get(0).tagName) {
            remove_unwanted(c.get(0));
        }
        
        c = p;
    }
    return;

}




function inject_editor(editing_buttons, save_buttons) {
    //debug(left_buttons)
   
    $('#quickoats_editor').remove();
   
   
   
    var div = '<div id="quickoats_editor"></div>';
    var p = $('<p id="editor_buttons"></p>');
    var p2 = $('<p id="save_buttons"></p>');
   
    
    
   
   
    for (var i in editing_buttons) {
        var button_info = editing_buttons[i];
   
        if (button_info.length < 1) continue;
   
        if (button_info.length == 1) {
            p.append(button_info[0]);
        }
        else
        {
           
            var button = $('<a></a>');
            button.attr('href','#');
           
            try {
                button.append(button_info[0]);
                button.attr('command_name',button_info[1]);
               
                if (button_info[2] != null) {
                    button.attr('command_arg', button_info[2]);
                }
               
                if (button_info[3] != null) {
                    button.data('activation_check',button_info[3]);
                }
               
            } catch (err) {
                p.append(button);
                continue;
           
            }
           
            p.append(button);
        }
   
    }
    
    for (var i in save_buttons) {
        var button_info = save_buttons[i];
   
        if (button_info.length < 1) continue;
   
        if (button_info.length == 1) {
            p2.append(button_info[0]);
        }
        else
        {
           
            var button = $('<a></a>');
            button.attr('href','#');
           
            try {
                button.append(button_info[0]);
                button.attr('command_name',button_info[1]);
               
                if (button_info[2] != null) {
                    button.attr('command_arg', button_info[2]);
                }
               
                if (button_info[3] != null) {
                    button.data('func',button_info[3]);
                }
               
            } catch (err) {
                p2.append(button);
                continue;
           
            }
           
            p2.append(button);
        }
   
    }
    
    var toolbar = $(div).append(p);
    var t2 = $(toolbar).append(p2);
   
    $('body').append(t2);
    
};



function inject_intro_box() {
   
    $('#quickoats_intro_box').remove();
   
    var div = '<div id="quickoats_intro_box"></div>';
    var p = $('<p><a href="">start editing</a></p>');
   
    
   
    var toolbar = $(div).append(p);
   
   
    $('body').append(toolbar);
    
    var upload = '<div id="quickoats_upload" class=""></div>';
    $('body').append(upload);
    
    
    $("#quickoats_upload").dialog({ autoOpen: false, title: 'Choose an image, or upload a new one...', 
            height: 520, width: 720, modal: true });
            
    var htmledit = '<div id="quickoats_htmledit" class=""></div>';
    $('body').append(htmledit);
    
    
    $("#quickoats_htmledit").dialog({ autoOpen: false, title: 'Edit the current area\'s HTML directly...', 
            height: 520, width: 720 });
            
            
            
    //$("#quickoats_upload form").live('submit', submit_image_upload);
            
     $("#quickoats_image_browser a.pic_insert").live('click', function() {
        restore_cursor_pos();
     
        if (!current_editable()) {
            $("#quickoats_upload").dialog('close');
            alert('You need to be within an editable area to insert an image.');
            return false;
        }
        
        try {
                
                document.execCommand('insertImage', false, $(this).attr('href'));
            }
            catch(err) {
                debug(err);
            }
            refresh_image_events();
        $("#quickoats_upload").dialog('close');
        return false;
     });
     
     $("#quickoats_image_browser a.pic_delete").live('click', function() {
        if (!confirm("Are you sure you want to delete this picture? If the image is in use on the site it could break content.")) {
            
            return false;
        }
        var h = $(this).attr('href');
        //ajax delete
        $.ajax({
        type: "POST",
        url: '/quickoats/delete_image',
        data: { href: h },
        success: function(data) {
            //alert(data);
            $("#quickoats_upload").load('/quickoats/upload');
            //var selector = '[quickoats_id="' + qo_id + '"]';    
            //var selector2 = 'div[quickoats_id="' + qo_id + '"]';  
            
            //$(selector).remove();
        }
    });
        
        
        //remove the link in question
        
        
        return false;
     });
     
     
     
            
            
    var options = { 
        target:        '#quickoats_upload'
    }; 
 
    // bind to the form's submit event 
    $("#quickoats_upload form").live('submit',function() { 
        // inside event callbacks 'this' is the DOM element so we first 
        // wrap it in a jQuery object and then invoke ajaxSubmit 
        $(this).ajaxSubmit(options); 
 
        // !!! Important !!! 
        // always return false to prevent standard browser submit and page navigation 
        return false; 
    }); 
            
    $("#quickoats_htmledit form").live('submit',function() { 
        // inside event callbacks 'this' is the DOM element so we first 
        // wrap it in a jQuery object and then invoke ajaxSubmit 
        //$(this).ajaxSubmit(options); 
        var new_html = $('#quickoats_htmledit textarea').val();
        
        
        var cur = $.fn.quickoats.current;
        $(cur).html(new_html);
        $("#quickoats_htmledit").dialog('close');
        // !!! Important !!! 
        // always return false to prevent standard browser submit and page navigation 
        return false; 
    });         
            
            
            
            
            
            
    $('input:file').live('change', 
            function(){
                if ($(this).val()) {
                    $('input:submit').attr('disabled',false);
                    // or, as has been pointed out elsewhere:
                    // $('input:submit').removeAttr('disabled'); 
                } 
            }
            );
            
            
            
};




function update_buttons() {
    $('#indicator').show().fadeOut(50);
   
    $('#quickoats_editor').find('a').each(function() {
        
        var check = $(this).data('activation_check');
              
        if (check != null)
        {
            
            if (check()) {
                $(this).addClass('deactivated');
            }
            else {
                $(this).removeClass('deactivated');
            }
        }
    });
};


function update_toolbar() {
   
    if (current_editable() != null)
    {
        //update_buttons();
        //jQuery.quickoats_utils.checkActivations('asdf');
    }
};


$.fn.quickoats.range = null;

function save_cursor_pos() {
    
// Save current selected range
    var sel = window.getSelection();
    var range = sel.getRangeAt(0);
    $.fn.quickoats.range = range;
};

function restore_cursor_pos() {
    var sel = window.getSelection();
    
    sel.removeAllRanges();
    sel.addRange($.fn.quickoats.range);
    
};

$.fn.quickoats.check_button_bold = function() {
    return document.queryCommandState('bold');
};


$.fn.quickoats.save_all = function() {
    debug('save');
    
    var x = this;
    
    $('.editable').each(function() {
        var qo_content = $(this).html().trim();
        var qo_id = $(this).attr('quickoats_id') || '';
        var qo_content_id = $(this).attr('quickoats_content') || '';
        
        debug('qo content: ' + qo_content);
        debug('qo content id: ' + qo_content_id);
        var curr = $(this);
        $.ajax({
            type: "POST",
            url: '/quickoats/set',
            data: { id: qo_id, content_id: qo_content_id, content: qo_content },
            success: function(data) {
                debug('saved');
          }
        });
        
        
    
    });
    
    //$.ajax({
 // url: 'ajax/test.html',
 // success: function(data) {
 //   $('.result').html(data);
 //   alert('Load was performed.');
 // }
//});
    
};



$.fn.quickoats.save_changes = function() {
    
    $.fn.quickoats.save_all();
    $('.editable').fadeTo(0, 0.1);
    $('.editable').fadeTo(3000,1);
};

$.fn.quickoats.save_and_finish = function() {
    debug('save');
    $.fn.quickoats.save_all();
    $('.editable').fadeTo(0, 0.1);
    $('.editable').fadeTo(3000,1);
    stop_editing();
};

$.fn.quickoats.open_image_dialog = function() {

    save_cursor_pos();
    $("#quickoats_upload").load('/quickoats/upload');
    $("#quickoats_upload").dialog('open');
    
};

$.fn.quickoats.open_html_dialog = function() {
    var cur = current_editable();

    if (!cur) {
        
        alert('You need the cursor to be within an editable area to edit its HTML.');
        return;
    
    }
    $.fn.quickoats.current = cur;
    
    var content = $(cur).html().trim();
    $("#quickoats_htmledit").load('/quickoats/htmledit',function() {
        $("#quickoats_htmledit textarea").html(content);
        $("#quickoats_htmledit").dialog('open');
    });
    
    
    
    
    
};

$.fn.quickoats.current = null;

$.fn.quickoats.current_img = null;



$.fn.quickoats.defaults = {
    get_url: '/quickoats/get/',
    set_url: '/quickoats/set/',
    toolbar: 'red',
    editing_buttons:   [
                    ['ordinary text','removeFormatting'],
                    ['big heading','formatBlock','<h3>'],
                    ['medium heading','formatBlock','<h4>'],
                    ['small heading','formatBlock','<h5>'],
                    ['&nbsp;&nbsp;&nbsp;'],
                   
                    ['&raquo; add blockquote', 'formatBlock','<blockquote>'],
                    ['&laquo; remove blockquote', 'removeBlock','blockquote'],
                    ['&nbsp;&nbsp;&nbsp;'],
                   
                    ['bulleted list','insertUnorderedList'],
                    ['&nbsp;&nbsp;&nbsp;'],
                   
                    ['bold','bold', null, $.fn.quickoats.check_button_bold],
                    ['italic','italic', null, null],
                    ['<br/>'],
                    ],
    save_buttons:   [
                    ['insert image','insert_image', null, $.fn.quickoats.open_image_dialog],
                    ['edit raw html (experts only)','edit_html', null, $.fn.quickoats.open_html_dialog],
                    ['save changes','save', null, $.fn.quickoats.save_changes],
                    ['save and finish','save_and_finish', null, $.fn.quickoats.save_and_finish],
                    ]
};


})(jQuery);


