﻿(function () {
    //////////////////////////////////////////////////////////////////////////////////////////////////
    // Switching on Demo Mode allows the password 'demo' to be used and removes Save functionality. //
    // This is probably not what you want.                                                          //
    //////////////////////////////////////////////////////////////////////////////////////////////////
    var isDemoMode = false;
    //////////////////////////////////////////////////////////////////////////////////////////////////

 
    // end of user configurable options.
    // proceed at your own risk.


    function easyedit($) {


        $("head").append($("<link></link>").attr({
            rel: "stylesheet",
            type: "text/css",
            href: $("script[src*=easyedit]").attr("src").replace(".js", ".css")
        }));

        var unsavedChanges = false;
        var origBorder = "";
        var origBackground = "";

        var authPassword = null;
        var elementEdited = null;

        window.onbeforeunload = function () {
            if (unsavedChanges)
                return "You have unsaved changes which will be discarded on exit. Do you wish to close EasyEdit anyway?";
        }

        function beginEditing() {
            unsavedChanges = false;

            elementEdited = $("[easyedit]");
            origBorder = elementEdited.css("border");
            origBackground = elementEdited.css("background");

            elementEdited.attr("contentEditable", "true")
                .css({ border: "2px solid #B30000", padding: "5px", background: "#EEE"   });


            elementEdited.bind("keypress paste", function () { unsavedChanges = true; });

            $("body")
                    .append($("<div></div>").addClass("__easyedit_toolbar")
                    .append($("<div></div>").addClass("__easyedit_inner")

					.append($("<a href='#' title='Save'></a>").click(save).addClass("__easyedit_save"))
                    .append($("<a href='#' title='Close'></a>").click(endEditing).addClass("__easyedit_close"))

                    //.append($("<div></div>").addClass("__easyedit_sep"))

                    .append($("<a href='#' title='Bold'></a>").click(function () { document.execCommand("Bold", false, null); unsavedChanges = true; return false; }).addClass("__easyedit_bold").addClass("__easyedit_icon"))
                    .append($("<a href='#' title='Italic'></a>").click(function () { document.execCommand("Italic", false, null); unsavedChanges = true; return false; }).addClass("__easyedit_italic").addClass("__easyedit_icon"))
                    .append($("<a href='#' title='Underline'></a>").click(function () { document.execCommand("Underline", false, null); unsavedChanges = true; return false; }).addClass("__easyedit_underline").addClass("__easyedit_icon"))
                    .append($("<a href='#' title='Strike Through'></a>").click(function () { document.execCommand("strikeThrough", false, null); unsavedChanges = true; return false; }).addClass("__easyedit_strike").addClass("__easyedit_icon"))
                    .append($("<a href='#' title='Subscript'></a>").click(function () { document.execCommand("subscript", false, null); unsavedChanges = true; return false; }).addClass("__easyedit_sub").addClass("__easyedit_icon"))
                    .append($("<a href='#' title='Superscript'></a>").click(function () { document.execCommand("superscript", false, null); unsavedChanges = true; return false; }).addClass("__easyedit_sup").addClass("__easyedit_icon"))

                    //.append($("<div></div>").addClass("__easyedit_sep"))

                    .append($("<a href='#' title='Justify Left'></a>").click(function () { document.execCommand("justifyLeft", false, null); unsavedChanges = true; return false; }).addClass("__easyedit_left").addClass("__easyedit_icon"))
                    .append($("<a href='#' title='Justify Center'></a>").click(function () { document.execCommand("justifyCenter", false, null); unsavedChanges = true; return false; }).addClass("__easyedit_center").addClass("__easyedit_icon"))
                    .append($("<a href='#' title='Justify Right'></a>").click(function () { document.execCommand("justifyRight", false, null); unsavedChanges = true; return false; }).addClass("__easyedit_right").addClass("__easyedit_icon"))

                    //.append($("<div></div>").addClass("__easyedit_sep"))

                    .append($("<a href='#' title='Insert link'></a>").click(function () {

                        var url = prompt("URL", "http://");
                        if (url) {
                            document.execCommand("CreateLink", false, url);
                            unsavedChanges = true;
                        }

                        return false;
                    }).addClass("__easyedit_link").addClass("__easyedit_icon"))
                    .append($("<a href='#' title='Break Link'></a>").click(function () { document.execCommand("Unlink", false, null); unsavedChanges = true; return false; }).addClass("__easyedit_linkdelete").addClass("__easyedit_icon"))

                    //.append($("<div></div>").addClass("__easyedit_sep"))

                    .append($("<a href='#' title='Insert Image'></a>").click(function () {

                        var url = prompt("Image URL", "http://");
                        if (url) {
                            document.execCommand("insertImage", false, url);
                            unsavedChanges = true;
                        }

                        return false;
                    }).addClass("__easyedit_image").addClass("__easyedit_icon"))

                    .append($("<a href='#' title='Insert Unordered List'></a>").click(function () { document.execCommand("insertUnorderedList", false, null); unsavedChanges = true; return false; }).addClass("__easyedit_ul").addClass("__easyedit_icon"))
                    .append($("<a href='#' title='Insert Ordered List'></a>").click(function () { document.execCommand("insertOrderedList", false, null); unsavedChanges = true; return false; }).addClass("__easyedit_ol").addClass("__easyedit_icon"))
                    .append($("<a href='#' title='Redo Changes'></a>").click(function () { document.execCommand("redo", false, null); unsavedChanges = true; return false; }).addClass("__easyedit_redo").addClass("__easyedit_icon"))

                    //.append($("<div></div>").addClass("__easyedit_sep"))
                    .append($("<a href='#' title='Undo Changes'></a>").click(function () { document.execCommand("undo", false, null); unsavedChanges = true; return false; }).addClass("__easyedit_undo").addClass("__easyedit_icon"))
                    .append($("<a href='#' title='Insert Horizontal Rule'></a>").click(function () { document.execCommand("insertHorizontalRule", false, null); unsavedChanges = true; return false;}).addClass("__easyedit_hr").addClass("__easyedit_icon"))

                    //.append($("<div></div>").addClass("__easyedit_sep"))
                     .append($("<a href='#' title='Font Color'></a>").click(function () {

                        var url = prompt('Enter Color', '');
                        if (url) {
                            document.execCommand('forecolor', false, url);
                            unsavedChanges = true;
                        }

                        return false;
                    }).addClass("__easyedit_fcol").addClass("__easyedit_icon"))


                     .append($("<a href='#' title='Background Color'></a>").click(function () {

                        var url = prompt('Enter background color', '');
                        if (url) {
                            document.execCommand('backcolor', false, url);
                            unsavedChanges = true;
                        }

                        return false;
                    }).addClass("__easyedit_bground_color").addClass("__easyedit_icon"))
                     
                    .append($("<select style='border:1px solid #B7B8BA;background-color:#D6D6D6;width:100px'></select>")
                        .append("<option>--Font Style--</option>")
                        .append("<option style='font-family:Arial';>Arial</option>")
                        .append("<option style='font-family:Comic Sans MS';>Comic Sans MS</option>")
                        .append("<option style='font-family:Times';>Times</option>")
                        .append("<option style='font-family:Verdana';>Verdana</option>")
                        .append("<option style='font-family:Tahoma';>Tahoma</option>")
                        .append("<option style='font-family:Georgia';>Georgia</option>")
                        .append("<option style='font-family:Courier';>Courier</option>")
                        .append("<option style='font-family:Impact';>Impact</option>")
                        .change(function () { document.execCommand("fontname", false, $(this).val()); unsavedChanges = true; })
                    )



                    //.append($("<div></div>").addClass("__easyedit_sep"))

                .append($("<select style='border:1px solid #B7B8BA;background-color:#D6D6D6;width:100px'></select>")
                        .append("<option>--Font Size--</option>")
                        .append("<option>1</option>")
                        .append("<option>2</option>")
                        .append("<option>3</option>")
                        .append("<option>4</option>")
                        .append("<option>5</option>")
						.append("<option>6</option>")
                        .append("<option>7</option>")
                        .append("<option>8</option>")
                        .append("<option>9</option>")
                        .append("<option>10</option>")
						.append("<option>20</option>")

                        .change(function () { document.execCommand("fontsize", false, $(this).val()); unsavedChanges = true; })
                    )
                   .append($("<select style='border:1px solid #B7B8BA;background-color:#D6D6D6;width:100px'></select>")
                        .append("<option>--Headings--</option>")
                        .append("<option>H1</option>")
                        .append("<option>H2</option>")
                        .append("<option>H3</option>")
                        .append("<option>H4</option>")
                        .append("<option>H5</option>")
						.append("<option>H6</option>")

                        .change(function () { document.execCommand("formatblock", false, $(this).val()); unsavedChanges = true; })
                    )
                )
            );
        }


        function endEditing() {
            if (unsavedChanges) {
                if (!confirm("You have unsaved changes which will be discarded on exit. Do you wish to close EasyEdit anyway?"))
                    return;
            }

            elementEdited.removeAttr("contenteditable")
                .animate({ border: origBorder, background: origBackground }, function () { $(this).css({ border: origBorder, background: origBackground }); });

            $(".__easyedit_toolbar").hide(function () { $(this).remove(); });
        }

        function save() {
            if (isDemoMode) {
                alert("Save functionality has been disabled in this demo");
                return;
            }

            $(".__easyedit_save").addClass("__easyedit_saving");

            var fname = location.pathname;
            if ($("script#easyedit_realpath").size() > 0) {
                fname = $("script#easyedit_realpath").text();
            }
            else if (fname[fname.length - 1] == '/') {
                fname = fname + "index.html";
            }

            $.post($("script[src*=easyedit]").attr("src").replace(".js", ".php"), { action: 'save', password: authPassword, file: fname, page: elementEdited.html() }, function (data) {
                if (data.split(":")[0] != "true") {
                    alert("An error occured while saving.");
                }
                else {
                    unsavedChanges = false;
                }
                $(".__easyedit_save").removeClass("__easyedit_saving");
            });
        }

        $(document).ready(function () {
            $("a[href=#__easyedit]").click(function () {

                // fade out document and fade in login form
                var docfade = $("<div>").css({
                    width: "100%",
                    height: "100%",
                    background: "transparent",
                    position: "fixed",
                    left: "0px",
                    top: "0px"
                });

                docfade.fadeOut(function () { $("body").append($(this).fadeTo(300, 0.7)) });

           $("body").append($("<form>").addClass("__easyedit_login")
                    .append($("<span>").text("You need to login to make changes to this webpage."))
                    .append($("<input>").attr({ type: "password" }).focus())
                    .append($("<input>").attr({ type: "submit", value: "Log me in" }).click())
                    .append($("<a>").attr("href", "#").text("Cancel").click(function () {
                        $(".__easyedit_login").fadeOut("fast", function () {
                            $(this).remove();
                            docfade.remove();
                        });
                        return false;
                    }))
                    .submit(function () {
                        var $this = $(this);

                        // do stuff that involves validating auth here
                        var pw = $this.children("input").val();

                        var onAuth = function (data) {
                            if (data == "true" || (isDemoMode && pw == "demo")) {

                                authPassword = pw;

                                $(".__easyedit_login").fadeOut("fast", function () {
                                    $this.remove();
                                    docfade.remove();
                                });

                                beginEditing();

                            } else {

                                // auth failed, shake login box OS X style
                                $this.animate({ marginLeft: "-200px" }, 100, function () {
                                    $this.animate({ marginLeft: "-160px" }, 100, function () {
                                        $this.animate({ marginLeft: "-200px" }, 100, function () {
                                            $this.animate({ marginLeft: "-160px" }, 100, function () {
                                                $this.animate({ marginLeft: "-180px" }, 100);
                                            });
                                        });
                                    });
                                });

                            }
                        };

                        if (isDemoMode) {
                            onAuth("false");
                        }
                        else {
                            $.post($("script[src*=easyedit]").attr("src").replace(".js", ".php"), { action: 'login', password: pw }, onAuth);
                        }

                        return false;
                    })
                    .fadeIn()
                );

                return false;
            });
        });
    }

    if (typeof (jQuery) != "undefined") {
        easyedit(jQuery);
    }
    else {
        var script = document.createElement('script');
        script.type = "text/javascript";
        script.onreadystatechange = function () {
            if (this.readyState == 'complete')
                easyedit(jQuery);
        };
        script.onload = function () { easyedit(jQuery); };
        script.src = 'http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js';
        document.body.appendChild(script);
    }
})();
