/// <reference path="~/scripts/jquery.js" />
/// <reference path="~/scripts/ww.jquery.js" />
$(document).ready(function() {
    $("#imgEditTitle").click(titleEdit);
    $("#imgEditCode").click(codeEdit);
    $("#imgPostToTwitter").click(twitterClick);
    $("#imgShowLineNumbers").click(showLineNumbers);
    $("#btnEditLanguage").click(langEdit);
    $("#btnSaveComment").click(saveComment);
    $("#btnEditTags").click(editTags);
    $("#btnEditComment").click(editComment);
    $("#btnCopyCode").click(copyToClipboard);
    
    showStatus({ afterTimeoutText: "hide" });
    showStatus("hide");
});

function copyToClipboard(e) {
    $('#CodeDisplay').editable();
    $('#_contenteditor')
     .attr("readonly", "readonly")
     .focus()
     .select()
     .keydown(function(e) {
         // capture Ctl-C, Ctl-X to remove editable
         if (e.which == 27) {
             e.preventDefault();
             e.stopPropagation();
         }
         if (e.which == 67 || e.which == 88 || e.which == 27) {
             // have to delay so text doesn't go away before copy operation
             setTimeout(function() {
                $("#divCopyDialog").hide(); 
                $("#CodeDisplay").editable("cleanup");         
             }, 200);
         }
     });

    // show overlay message
    $("#divCopyDialog")
                .centerInClient({ container: $("#divContainerContent") })
                .css("top", 350)                
                .shadow()
                .closable()
                .draggable()
                .show()
                .fadeIn(1000);
    setTimeout(function() { $("#divCopyDialog").fadeOut(1000); }, 3000);
};

function codeEdit(evt) {
    var id = $("#SnippetId").val();
    var jCode = $("#CodeDisplay");
    ajaxCallMethod(serverVars.callbackHandler, "GetCode", [id],
                   function(code) {
                       jCode.editable(
                            { value: code, saveHandler: function(res) {
                                saveCode.call(this, res);
                                return false; // don't close window
                            }
                            });
                   }, onPageError);
}
function saveCode(res) {
    var jEdit = $(this).css({ opacity: 0.50 });
    res.button.attr("disabled", true);
    var id = $("#SnippetId").val();
    var jCode = $("#CodeDisplay");
   
    ajaxCallMethod(serverVars.callbackHandler, "SaveCode", [id, res.text],
               function(htmlCode) {
                   jCode.html(htmlCode);
                   res.cleanup();
               }, function(error) {
                   showStatus("Unable to update code change: " + error.message,8000);
                   jEdit.css("opacity", 1);
                   res.button.attr("disabled", false);                     
               });
    
}
function titleEdit(evt) {
    var id = $("#SnippetId").val();
    $("#Title").editable(
        { editClass: "tagedit",
            saveHandler: function(res) {
                ajaxCallMethod(serverVars.callbackHandler, "SaveTitle", [id, res.text],
                           function(title) {
                               $("#Title").text(title); 
                               res.cleanup();
                           },
                           onPageError);
            }
        });
}


function langEdit() {
    var jLang = $("#Language");

    // set a flag to disallow double editing
    if (jLang.data("editing"))
        return;
        
    var lang = jLang.text();
    
    // Need a snippet id for Server callbacks
    var id = $("#SnippetId").val();
    
    ajaxCallMethod(serverVars.callbackHandler, "GetCodeLanguages", [], function(langs) {
        var dd = $("<select></select>")
                  .attr("id", "LanguageDropDown")
                  .css("font-size", "8pt");
        jLang.data("editing", true);
        $.each(langs, function() {
            var opt = $("<option></option>").text(this.value).val(this.key);
            if (lang == this.key) {
                opt.get(0).selected = true;
            }
            dd.append(opt);
        });

        // Hook up change handler that saves selection and restores text display
        dd.change(function() {
            var lang = dd.val();
            ajaxCallMethod(serverVars.callbackHandler, "SaveLanguage", [id, lang], 
              function(code) {
                $("#CodeDisplay").html(code).hide().fadeIn("slow");
            }, onPageError);

            jLang.fadeIn("slow")
                 .text(lang)
                 .data("editing",false);
            dd.remove();
        });

        jLang.before(dd).hide();
    });
}
function editTags() {
    var id = $("#SnippetId").val();
    var jTags = $("#Tags");
    var tags = jTags.text();    
    jTags.editable(
        { editClass: "tagedit",
          saveHandler: function(res) {
            ajaxCallMethod(serverVars.callbackHandler, "SaveTags", [id, res.text],
                           function(html) { jTags.html(html); res.cleanup()},
                           onPageError);
        }
        });             
}
function editComment() {
    var id = $("#SnippetId").val();
    var jComment = $("#Comment");
    var comment = jComment.text();
    
    jComment.editable(
        { editClass: "commentedit",
            saveHandler: function(res) {
            ajaxCallMethod(serverVars.callbackHandler, "SaveMainComment", [id, res.text],
                           function(html) { jComment.html(html); res.cleanup() },
                           onPageError);
        }
        });
}
function RemoveSnippet(id) {
    ajaxCallMethod(serverVars.callbackHandler, "RemoveSnippet", [id], function() {
        $("body").fadeOut("slow", function() { window.location = serverVars.baseUrl; });
    }, onPageError);

}
function ReportAbuse() {
    var id = $("#SnippetId").val();
    if (!id)
        return;

    ajaxCallMethod(serverVars.callbackHandler, "ReportAbuse", [id],
                    function(result) {
                        showStatus("Thank you: Abuse for this snippet has been reported.", 8000, true);
                    }, onPageError);    
}

function saveComment() 
{
    ajaxCallMethod(serverVars.callbackHandler, "SaveComment", [$("#txtNewComment").val(), $("#SnippetId").val()],
                   function(result) {
                       var jNew = $(parseTemplate($("#commentTemplate").html(), result)).hide();
                       
                       $("#divNewComment")
                            .before(jNew)
                            .fadeOut(function() {
                               jNew.fadeIn("slow");
                            });
                   }, onPageError);  
}

function showLineNumbers() {
    ajaxCallMethod(serverVars.callbackHandler, "ShowLineNumbers", 
                   [$("#SnippetId").val(), !serverVars.showLineNumbers],
                    function(htmlCode) {
                        serverVars.showLineNumbers = !serverVars.showLineNumbers;
                        $("#CodeDisplay").html(htmlCode);
                    }, onPageError);
}

function twitterClick() {
    var id = $("#SnippetId").val();
    window.open("http://twitter.com/home?status=" + $("#Title").text() + ": http://codepaste.net/" + id + escape(" #") + id,"_blank");    
}
