var content;

$('.submitter')
    .live('click', function() {
        $("#output").html("<img src=\"../App_Themes/images/ajax-loader.gif\" />");
        $.ajax({
            type: "POST",
            url: "/requestministrychanges.aspx/ViewProfileItem",
            data: "{'col':'" + $(".ddprofheaders:first").val() + "', 'ein':'" + $(".ddministries:first").val() + "'}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(msg) {
                if (msg.d != '' && msg.d != null) {
                    $("#output").html("<h3>Below is the current website information for the topic: " + 
                    $(".ddprofheaders:first option:selected").text() + "</h3>" + msg.d +
                    "<h3>Request to change this information in the form below. Proposed changes made in \"" + $(".ddprofheaders:first option:selected").text() + "\"" +
                    " for " + $(".ddministries:first option:selected").text() + ".</h3>");
                }
                else {
                    $("#output").html("<p><i>" + $(".ddministries:first option:selected").text() + " has no profile data under \"" +
                    $(".ddprofheaders:first option:selected").text() + "\"</i></p>" + 
                    "<h3>Request to change this information in the form below. Proposed changes made in \"" + $(".ddprofheaders:first option:selected").text() + "\"" +
                    " for " + $(".ddministries:first option:selected").text() + ".</h3>");
                }
            },
            error: function(msg) {
                alert("Error: " + msg.d);
            }
        });
    });


//$('.submit')
//    .live('click', function() {
//        //alert("submitting");
//        //var css_id = $(this).parents('div:eq(0)').attr('id');
//        var notes = $("#RequestedChange").html();
//        alert(notes);
//        //var notes = "poooooo";
//        //notes = notes.replace(/(['|\\])/g, "\\$1");
//        //$(this).html("<img src=\"../App_Themes/images/ajax-loader.gif\" />")
//        $.ajax({
//            type: "POST",
//            url: "../MinistryWatch.asmx/RequestMinChange",
//            data: "{'change':'" + notes + "'}",
//            contentType: "application/json; charset=utf-8",
//            dataType: "json",
//            success: function(msg) {
//                $("#output").html(msg.d);
//            },
//            error: function(msg) {
//                alert(msg.d);
//            }
//        });
//    });

/*
 * jQuery RTE plugin 0.3 - create a rich text form for Mozilla, Opera, and Internet Explorer
 *
 * Copyright (c) 2007 Batiste Bieler
 * Distributed under the GPL (GPL-LICENSE.txt) licenses.
 */

// define the rte light plugin
    jQuery.fn.rte = function(css_url, media_url) {

        if (document.designMode || document.contentEditable) {
            $(this).each(function() {
                var textarea = $(this);
                enableDesignMode(textarea);
            });
        }

        function formatText(iframe, command, option) {
            iframe.contentWindow.focus();
            //try {
            iframe.contentWindow.document.execCommand(command, false, option);
            //} catch (e) { console.log(e) }
            iframe.contentWindow.focus();
        }

        function tryEnableDesignMode(iframe, doc, callback) {
            try {
                iframe.contentWindow.document.open();
                iframe.contentWindow.document.write(doc);
                iframe.contentWindow.document.close();
            } catch (error) {
                console.log(error)
            }
            if (document.contentEditable) {
                iframe.contentWindow.document.designMode = "On";
                callback();
                return true;
            }
            else if (document.designMode != null) {
                try {
                    iframe.contentWindow.document.designMode = "on";
                    callback();
                    return true;
                } catch (error) {
                    console.log(error)
                }
            }
            setTimeout(function() { tryEnableDesignMode(iframe, doc, callback) }, 250);
            return false;
        }

        function enableDesignMode(textarea) {
            // need to be created this way
            var iframe = document.createElement("iframe");
            iframe.frameBorder = 0;
            iframe.frameMargin = 0;
            iframe.framePadding = 0;
            iframe.height = 400; //200
            if (textarea.attr('class'))
                iframe.className = textarea.attr('class');
            if (textarea.attr('id'))
                iframe.id = textarea.attr('id');
            if (textarea.attr('name'))
                iframe.title = textarea.attr('name');
            textarea.after(iframe);
            var css = "";
            if (css_url && css_url != "")
                var css = "<link type='text/css' rel='stylesheet' href='" + css_url + "' />"
            var content = textarea.val();
            // Mozilla need this to display caret
            if ($.trim(content) == '')
                content = '<br>';
            var doc = "<html><head>" + css + "</head><body class='frameBody'>" + content + "</body></html>";
            tryEnableDesignMode(iframe, doc, function() {
                $("#toolbar-" + iframe.title).remove();
                $(iframe).before(toolbar(iframe));
                textarea.remove();
            });
        }

        function disableDesignMode(iframe, submit) {
            var submitNonDesign = false;
            try {
                //var content = $(iframe).contents().find("body").html().replace(/'/gi, "&apos;").replace(/\\/gi, "\\\\");
                //content = $(iframe).contents().find("body").html().replace(/'/gi, "&apos;").replace(/\\/gi, "\\\\").replace(/&nbsp;/g, ' ').replace(/\s+/g, ' ');
                content = $(iframe).contents().find("body").html().replace(/'/gi, "&apos;").replace(/\\/gi, "\\\\");
            }
            catch (err) {
                //var content = $("textarea:first").val();
                content = $("textarea#RequestedChange").val();
                if (content == null) {
                    return;
                }
                else if (submit == true)
                    submitNonDesign = true;
            }

            content = HouseKeeping(content);

            if (submit == true)
                var textarea = $('<input type="hidden" />');
            else
                var textarea = $('<textarea cols="40" rows="10"></textarea>');
            textarea.val(content);
            t = textarea.get(0);
            if (iframe.className)
                t.className = iframe.className;
            if (iframe.id)
                t.id = iframe.id;
            if (iframe.title)
                t.name = iframe.title;
            if (submitNonDesign != true)
                $(iframe).before(textarea);
            if (submit != true)
                $(iframe).remove();
            else
                SendData(content, $("#wordocpaste").is(':checked'));
            return textarea;
        }

        function toolbar(iframe) {
            //                    <option value='h3'>Title</option>\
            //<a href='#' class='image'><img src='"+media_url+"image.png' alt='image' /></a>\
            var tb = $("<div class='rte-toolbar' id='toolbar-" + iframe.title + "'><div>\
            <p>\
                <select>\
                    <option value=''>Bloc style</option>\
                    <option value='p'>Paragraph</option>\
                </select>\
            </p>\
            <p>\
                <a href='#' class='bold'><img src='" + media_url + "edit-bold.png' alt='bold' /></a>\
                <a href='#' class='italic'><img src='" + media_url + "edit-italic.png' alt='italic' /></a>\
                <a href='#' class='underline'><img src='" + media_url + "edit-underline.png' alt='underline' /></a>\
                <a href='#' class='strikethrough'><img src='" + media_url + "edit-strike.png' alt='strikethrough' /></a>\
            </p>\
            <p>\
                <a href='#' class='unorderedlist'><img src='" + media_url + "edit-list.png' alt='unordered list' /></a>\
                <a href='#' class='insertorderedlist'><img src='" + media_url + "edit-list-order.png' alt='ordered list' /></a>\
                <a href='#' class='link'><img src='" + media_url + "ui-label-link.png' alt='link' /></a>\
                <a href='#' class='disable'>HTML</a>\
            </p></div></div>");

            $('select', tb).change(function() {
                var index = this.selectedIndex;
                if (index != 0) {
                    var selected = this.options[index].value;
                    formatText(iframe, "formatblock", '<' + selected + '>');
                }
            });
            $('.bold', tb).click(function() { formatText(iframe, 'bold'); return false; });
            $('.italic', tb).click(function() { formatText(iframe, 'italic'); return false; });
            $('.underline', tb).click(function() { formatText(iframe, 'underline'); return false; });
            $('.unorderedlist', tb).click(function() { formatText(iframe, 'insertunorderedlist'); return false; });
            $('.insertorderedlist', tb).click(function() { formatText(iframe, 'insertorderedlist'); return false; });
            $('.strikethrough', tb).click(function() { formatText(iframe, 'strikethrough'); return false; });
            $('.link', tb).click(function() {

                //var txt = prompt("Link title");

                //                var range = document.selection.createRange(); // as IHTMLTxtRange;
                //                range.pasteHTML("<a href=\"" + p + "\">" + txt + "</a>");
                //                range.collapse(false);
                //                range.select();

                //url = unescape("<a href=\"" + p + "\">" + txt + "</a>");

                //                var txt = '';
                //                var foundIn = '';
                if (iframe.contentWindow.document.getSelection) {
                    if (iframe.contentWindow.document.getSelection() == '') {
                        alert("Select some text in order to make it a hyperlink")
                    }
                    else {
                        var p = prompt("URL:", "http://");
                        if (p)
                            formatText(iframe, 'CreateLink', p);
                    }
                }
                else {
                    alert("Select some text in order to make it a hyperlink");
                }

                //                alert(txt);

                //                if (window.getSelection) {
                //                    alert("selected");
                //                }
                //                else {
                //                    alert("not selected");
                //                }

                return false;
            });
            $('.image', tb).click(function() {
                var p = prompt("image URL:");
                if (p)
                    formatText(iframe, 'InsertImage', p);
                return false;
            });
            $('.disable', tb).click(function() {
                var txt = disableDesignMode(iframe);
                var edm = $('<a href="#">Enable design mode</a>');
                tb.empty().append(edm);
                edm.click(function() {
                    enableDesignMode(txt);
                    return false;
                });
                return false;
            });
            //            $(iframe).parents('form').submit(function() {
            //                disableDesignMode(iframe, true);
            //            });
            $(".submit").click(function() {
                disableDesignMode(iframe, true);
            });
            var iframeDoc = $(iframe.contentWindow.document);

            var select = $('select', tb)[0];
            iframeDoc.mouseup(function() {
                setSelectedType(getSelectionElement(iframe), select);
                return true;
            });
            iframeDoc.keyup(function() {
                setSelectedType(getSelectionElement(iframe), select);
                var body = $('body', iframeDoc);
                if (body.scrollTop() > 0)
                    iframe.height = Math.min(350, parseInt(iframe.height) + body.scrollTop());
                return true;
            });

            return tb;
        }

        function setSelectedType(node, select) {
            while (node.parentNode) {
                var nName = node.nodeName.toLowerCase();
                for (var i = 0; i < select.options.length; i++) {
                    if (nName == select.options[i].value) {
                        select.selectedIndex = i;
                        return true;
                    }
                }
                node = node.parentNode;
            }
            select.selectedIndex = 0;
            return true;
        }

        function getSelectionElement(iframe) {
            if (iframe.contentWindow.document.selection) {
                // IE selections
                selection = iframe.contentWindow.document.selection;
                range = selection.createRange();
                try {
                    node = range.parentElement();
                }
                catch (e) {
                    return false;
                }
            } else {
                // Mozilla selections
                try {
                    selection = iframe.contentWindow.getSelection();
                    range = selection.getRangeAt(0);
                }
                catch (e) {
                    return false;
                }
                node = range.commonAncestorContainer;
            }
            return node;
        }

        function HouseKeeping(input) {
            //cleanup of extraneous html and make breaks xhtml compliant
            if (input != null) {
                if (input.substring(input.length - 4, input.length) == "<br>")
                    input = input.replace(/\<br\>$/, "");
                input = input.replace(/\<br\>/gi, "<br />");
                input = input.replace(/\<p\>\<br \/\>\<\/p\>/gi, "");
                //input = input.replace(/\<\/li\>\<li\>/gi, "</li>\r\n<li>");
            }
            return input;
        }

        function SendData(data, wordoc) { //$("#Comments").val()
            $("#output").html("<img src=\"../App_Themes/images/ajax-loader.gif\" />");
            $.ajax({
                type: "POST",
                url: "../MinistryWatch.asmx/RequestMinChange",
                data: "{'col':'" + $(".ddprofheaders:first").val() + "', 'ein':'" + $(".ddministries:first").val() + "', 'comments':'" + $("#Comments").val().replace(/'/gi, "&apos;").replace(/\\/gi, "\\\\") + "', " +
                    "'name':'" + $(".ddministries:first option:selected").text() + "', 'change':'" + data + "', 'msWordFormat':'" + wordoc + "'}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function(msg) {
                    if (msg.d == "") {
                        $("#output").html("");
                        alert("Error: an error occured while parsing the text.");
                    }
                    else {
                        $("#changearea").html("<p style=\"color:#117e11; \">Thank you for your help.  Your request to change the " +
                    $(".ddprofheaders:first option:selected").text() + " section for " +
                    $(".ddministries:first option:selected").text() + " has been successfully submitted. We will review this request and make edits based upon this request. " +
                    "Below is your proposed change.  If you have another requested change, <a href=\"requestministrychanges.aspx\">click here to request another profile change</a></p><hr />" + msg.d);
                    }
                    //$("#output").html(msg.d);
                },
                error: function(msg) {
                    $("#output").html("");
                    alert("Error: the text is in an unrecognizeable format.");
                }
            });
        }
    }