// STATUS CHANGE FUNCTIONS

function deleteArticle(articlekey, affectedDiv) {
    
    $.confirm({
        'title' : 'Delete Confirmation',
        'message' : 'You are about to delete this item. Continue?',
        'buttons' : {
            'Yes' : {
                'class'	: 'blue',
                'action': function(){
                         
                    var action="/article/delete";
                    var data = { articlekey: articlekey };
                    
                    var success_callback = function(data) {             
                        affectedDiv.fadeOut();
                    }
                    
                    var error_callback = function(data) {
                        alert("Error: " + data.response_text);
                    }
                    
                    post_ajax(data, action, success_callback, error_callback);

                }
            },
            'No'	: {
                'class'	: 'gray',
                'action': function(){}	// Nothing to do in this case. You can as well omit the action property.
            }
        }
    });    
};

function unassignArticle(articlekey, affectedDiv) {
    var action = "/article/unassign";
    var data = { articlekey: articlekey };
    
    var success_callback = function(data) {
        affectedDiv.find("select").hide();
        $("li").removeClass("focus");
        $("#lonelyLog ul").prepend(affectedDiv.addClass("focus").clone());
        affectedDiv.fadeOut();
    }
    
    var error_callback = function(data) {
        alert("Error: " + data.response_text);
    }
    
    post_ajax(data, action, success_callback, error_callback);
}

function unpublishArticle(articlekey, affectedDiv) {
    var action = "/article/unpublish";
    var data = { articlekey: articlekey };
    
    var success_callback = function(data) {
        affectedDiv.find("select").hide();
        $("li").removeClass("focus");
        $("#submittedLog ul").prepend(affectedDiv.addClass("focus").clone());
        affectedDiv.fadeOut();
    }
    
    var error_callback = function(data) {
        alert("Error: " + data.response_text);
    }
    
    post_ajax(data, action, success_callback, error_callback);
}

function rejectArticle(articlekey, affectedDiv) {
    var action = "/article/reject";
    var data = { articlekey: articlekey };
    
    var success_callback = function(data) {
        affectedDiv.find("select").hide();
        $("li").removeClass("focus");            
        $("#assignedLog ul").prepend(affectedDiv.addClass("focus").clone());
        affectedDiv.fadeOut();
    }
    
    var error_callback = function(data) {
        alert("Error: " + data.response_text);
    }
    
    post_ajax(data, action, success_callback, error_callback);
}    


function init_form(photo) {
    $(".form input, .form select, .form textarea").not(':button, :submit, :reset, :hidden').focus(function() {$(this).parent("li").addClass("focused");}).blur(function() {$(this).parent("li").removeClass("focused");});
    $(".form li").not(".buttonset").click(function() {$(".form li").not(this).removeClass("focused");$(this).addClass("focused");});

    $(".form .focused").find("input, select, textarea").focus();
    if (photo) {
        $("#photo-form").init_photoForm();   
    }
    
    init_tinymce();
}

function init_tinymce() {
    tinyMCE.init({
        // General options
        mode : "textareas",
        theme : "advanced",

        theme_advanced_buttons1 : "mylistbox,mysplitbutton,bold,italic,underline,separator,bullist,numlist,outdent,indent,undo,redo,link,unlink",
        theme_advanced_buttons2 : "",
        theme_advanced_buttons3 : "",
        theme_advanced_toolbar_location : "top",
        theme_advanced_toolbar_align : "left",
        theme_advanced_statusbar_location : "",
        setup: function(ed) {
            var text = "";
            var wordcount = false;
            ed.onKeyUp.add(function(ed, e) {
                if (!wordcount) {
                    wordcount = addWordCount();
                }
                text = ed.getContent().replace(/(< ([^>]+)<)/g,"").replace(/\s+/g," ");
                text = $.trim(text);
                $('#' + tinyMCE.activeEditor.id + '_wordcount').html("<span>" + text.split(' ').length + "</span> words");
            });
        }                
    });
    
    function addWordCount() {
        $('span.mceEditor').after('<div id="' + tinyMCE.activeEditor.id + '_wordcount" class="wordcount">0 words</div>');
        return true;
    }          
}

function post_ajax(data, action, success_callback, error_callback, fail_callback) {
    show_processing();
    $.ajax( {
        type: 'post',
        data: data,
        dataType: "json",
        url:  action,
        success: function( data ) {
            if (data.response=="success") { success_callback(data); }
            else { error_callback(data); }
            close_processing();
            return true;
        },
        error: function() {
            alert("Sorry, something went wrong. Please try again.");
            close_processing();
            if (fail_callback) fail_callback()
        }
    });    
}


function show_processing(callback) {
    $("#processing-overlay").show();
    window.scrollTo(0,0);
    if (callback)
        callback();    
}

function close_processing(callback) {
    $("#processing-overlay").hide();
    if (callback)
        callback();       
}

$.fn.reset_form = function() {
    $(':input',this).not(':button, :submit, :reset, :hidden').val('').removeAttr('checked').removeAttr('selected');
    var my_editor_id = $('textarea').attr("id");
    tinymce.get(my_editor_id).setContent(''); 

    $("#new-thumbnail").attr("src","/static/img/no-profile-image.jpg")
}

$.fn.error = function(msg) {
	$(this).hide().removeClass("error").removeClass("success");
	$(this).html(msg).addClass("error").fadeIn();
	return;
}

$.fn.success = function(msg) {
	$(this).hide().removeClass("error").removeClass("success");
	$(this).html(msg).addClass("success").fadeIn();
	return;
}


$.fn.init_photo_upload_form = function() {
    var form = $(this);
    var input_file = $(this).find("input:file");
    var input_url = $(this).find("#upload-photo-url");
    
    var new_photo_iframe = $(this).find("#new-photo-iframe");
    
    input_file.click(function() {
        $(this).blur();
        $(this).focus();
    });
    
    input_file.change(function() {
	    $("input#photo-url").val("");
        form.submit();
    });

    input_url.click(function() {
    	input_file.val("");
    	form.submit();
    });


    //photo saved, now preview it
    new_photo_iframe.load(function() {
        //serve the blob in the parent document after it finishes loading
        var photokey = "";
        try {
            if (window.frames['photo-key'].document.getElementById('photo-key').value != null) {
                form.find("#uploaderror").hide();
                photokey = window.frames['photo-key'].document.getElementById('photo-key').value;

                var new_img_src = "/thumbnail/" + photokey;
                form.find("#new-thumbnail").attr({"src": new_img_src});
                form.find("#form_photokey").val(photokey);
            }
            
        }catch(e){}
        return;
    });  
}



$.fn.init_photoForm = function() {
    var form = $(this);
    var input_file = $(this).find("input:file");
    
    var new_photo_iframe = $(this).find("#new-photo-iframe");
    
    input_file.click(function() {
        $(this).blur();
        $(this).focus();
    });
    
    input_file.change(function() {
	    $("input#photo-url").val("");
        form.submit();
    });


    //photo saved, now preview it
    new_photo_iframe.load(function() {
        //serve the blob in the parent document after it finishes loading
        var photokey = "";
        try {
            if (window.frames['photo-key'].document.getElementById('photo-key').value != null) {
                form.find("#uploaderror").hide();
                photokey = window.frames['photo-key'].document.getElementById('photo-key').value;
                photourl = window.frames['photo-key'].document.getElementById('photo-url').value;

                //var new_img_src = "/serve/" + photokey;
                form.find("#new-thumbnail").attr({"src": photourl});
                //form.find("#new-thumbnail").html()
                form.find("#form_photokey").val(photokey);
            }
            
        }catch(e){}
        return;
    });  
}



