AJS.$(function ($) {
    K15T.isInit = true;
    K15T.Popup = function(config) {
        var that = this;

        if(config) {
            this.height = (config.height || 200);
            this.width = (config.width || 200);
            this.url = (config.url || 200);
            this.title = (config.title || "Application Title");
            this.applicationName = (config.applicationName || "Application Name");
            this.applicationLink = (config.applicationLink || "http://www.k15t.com");
            this.applicationVersion = (config.applicationVersion || "0.0");
            this.afterInit = (config.afterInit || function() {});
        }

        if(AJS.Dialog) {
            this.container = new AJS.Dialog(this.width, this.height);
            this.element = this.container.popup.element;
        } else {
            // TODO implement solution for pre-3.0 here
            alert("ERROR: AJS.Dialog not defined.");
//            $("body").append("<div id='com-k15t-confluence-scroll-office-popup' class='popup dialog' style='background-color: white;'></div>");
//            this.container = $(".com-k15t-confluence-scroll-office-popup");
//            this.container.css("width", width + "px").css("height", height + "px");
//            this.container.hide();
//            this.element = $("#com-k15t-confluence-scroll-office-popup");
        }

        // === The HTML code for the popup =======
        this.element.html("<div class='com-k15t-popup'>" +
            "<div class='title' style='background-image: url(" + CONTEXT_PATH + "/download/resources/com.k15t.scroll.scroll-office:ui-required/images/title_bg.png)'>" +
            "  <h2>" + that.title + "<span style='float: right;'><a href='#' class='com-k15t-scroll-close' style='text-decoration: none; color: #666666;' title='Close'>" +
            "<img src='" + CONTEXT_PATH + "/download/resources/com.k15t.scroll.scroll-office:ui-required/images/title_btn_close.png' title='Close' /></a></span>" + 
            "  </h2>" +
            "</div>" +
            "<div class='content settings' style='height: " + (that.height - 120) + "px;'>Please wait...</div>" +
            "<div class='content loading' style='text-align: center; height: " + (that.height - 120) + "px; display: none;'>" +
            "  <div class='animation'><img src='" + CONTEXT_PATH + "/download/resources/com.k15t.scroll.scroll-office:ui-required/images/ani.gif' " + "title='Edit Export Settings'/><br/><br/>Please wait a second or two.</div>" + 
            "</div>" +
            "<div class='poweredby' style='background-image:url(" + CONTEXT_PATH + "/download/resources/com.k15t.scroll.scroll-office:ui-required/images/footer_bg.png)'>" +
            "  <span class='logo' style='background-image: url(" + CONTEXT_PATH + "/download/resources/com.k15t.scroll.scroll-office:ui-required/images/footer_scrolllogo.png)'></span>" +
            "  <span class='footertext'><a href='" + that.applicationLink + "' target='_new'>" + that.applicationName + " " + that.applicationVersion + "</a>," +
            "    Collaborative Office Documents &nbsp;|&nbsp; " +
            "    <a href='http://support.k15t.com/' target='_new'>Get Support</a>" +
            "  </span>" +
            "</div>" + 
            "</div>");

        // === Setup live event handler for close links =======
        this.element.find(".com-k15t-scroll-close").unbind("click").bind("click", function(event) {
            event.preventDefault();
            that.close();
        });

        $.ajax({
            type : 'GET'
            ,url :  that.url
            ,beforeSend : function(xmlHttpRequest) {
                that.show();
            }
            ,success : function(data, textStatus, XMLHttpRequest) {
                that.show(data);
                that.afterInit.call(this, data, textStatus, XMLHttpRequest);
            }
            ,error: function(XMLHttpRequest, textStatus, errorThrown) {
                that.show(XMLHttpRequest.responseText);
            }
            ,dataType: 'html'
        });
    }

    K15T.Popup.prototype.show = function(html) {
        var that = this;
        
        if(html) {
            this.element.find(".settings").show();
            this.element.find(".settings").html(html);
            this.element.find(".loading").hide();

            this.element.find(".com-k15t-scroll-close").unbind("click").bind("click", function(event) {
                event.preventDefault();
                that.close();
            });

            $("a.com-k15t-scroll-ajaxified").unbind("click").bind("click", function(event) {
                event.preventDefault();  // do not submit the form
                event.stopPropagation(); // handle settings event here

                $.ajax({
                    type : 'GET'
                    ,url : $(this).attr("href")
                    ,beforeSend : function(xmlHttpRequest) {
                        that.show();
                    }
                    ,error: function(XMLHttpRequest, textStatus, errorThrown) {
                        that.show(XMLHttpRequest.responseText);
                    }
                    ,success : function(data, textStatus, xmlHttpRequest) {
                        that.show(data);
                        timeout = that.element.find("form.autosubmit input[name=timeout]").attr("value");
                        downloadLink = that.element.find("form.autosubmit input[name=downloadLink]").attr("value");
                        if(timeout && (timeout >= 0) && downloadLink) {
                            window.setTimeout("window.location.href = downloadLink", timeout);
                        }
                        // init feedback messages link
                        $("#com-k15t-scroll-export-feedback-link").click(function() {
                            $("#com-k15t-scroll-export-feedback").slideToggle(200);
                        });
                    }
                    ,dataType: 'html'
                });
            });

            $("form.com-k15t-scroll-ajaxified").unbind("submit").bind("submit", function(event) {
                event.preventDefault();  // do not submit the form
                event.stopPropagation(); // handle settings event here

                $.ajax({
                    type : 'GET'
                    ,url : $(this).attr("action")
                    ,data : $(this).serialize()
                    ,beforeSend : function(xmlHttpRequest) {
                        that.show();
                    }
                    ,error: function(XMLHttpRequest, textStatus, errorThrown) {
                        that.show(XMLHttpRequest.responseText);
                    }
                    ,success : function(data, textStatus, xmlHttpRequest) {
                        that.show(data);
                        timeout = that.element.find("form.autosubmit input[name=timeout]").attr("value");
                        downloadLink = that.element.find("#com-k15t-scroll-downloadlink").attr("href");
                        if(downloadLink) {
                            window.setTimeout("window.location.href = downloadLink", 500);
                        }
                        // init feedback messages link
                        $("#com-k15t-scroll-export-feedback-link").click(function() {
                            $("#com-k15t-scroll-export-feedback").slideToggle(200);
                        });
                    }
                    ,dataType: 'html'
                });
            });

            this.container.show();
        } else {
            this.element.find(".settings").hide();
            this.element.find(".loading").show();
            this.container.show();
        }

    }

    K15T.Popup.prototype.hide = function(html) {
        this.container.hide();
    }

    K15T.Popup.prototype.close = function(html) {
        this.element.find(".settings").html("");
        this.container.hide();
    }

});

K15T = function() {};

SCROLL_VERSION = "2.0.2";

AJS.$(function ($) {
    $(document).ready(function() {
        CONTEXT_PATH = ($("#confluence-context-path").attr("content") || "");
        var webItemLink = $("#com-k15t-confluence-scroll-office-word-link");

        // init only, if the scroll office link is available
        if(webItemLink) {

            // === Initialize One-click Export Link =======
            webItemLink.find("span").append("<img id='com-k15t-confluence-scroll-office-word-quick-link' src='" +
                    CONTEXT_PATH + "/download/resources/com.k15t.scroll.scroll-office:ui-required/images/page_go.png' " +
                    "title='One-click Export' style='float:right; position:relative; z-index:1000; padding: 0 2px' />");
            $("#com-k15t-confluence-scroll-office-word-quick-link").click(function(event) {
                event.preventDefault();  // do not follow the link
                event.stopPropagation(); // handle settings event here

                var exportDialog = new K15T.Popup({
                    width : 620
                    ,height : 480
                    ,url : webItemLink.attr("href").replace(/settings.action/, "export.action")
                    ,title : "Export to Word"
                    ,applicationName : "Scroll Office"
                    ,applicationLink : "http://www.k15t.com/display/web/Scroll+Office"
                    ,applicationVersion : SCROLL_VERSION
                    ,afterInit : function(data, textStatus, xmlHttpRequest) {
                        downloadLink = $("#com-k15t-scroll-downloadlink").attr("href");
                        if(downloadLink) {
                            window.setTimeout("window.location.href = downloadLink", 500);
                        }
                        // init feedback messages link
                        $("#com-k15t-scroll-export-feedback-link").click(function() {
                            $("#com-k15t-scroll-export-feedback").slideToggle(200);
                        });
                    }
                });
            });

            // === Initialize Export Config Link =======
            webItemLink.click(function(event) {
                event.preventDefault();  // do not follow the link
                event.stopPropagation(); // handle settings event here

                var settingsDialog = new K15T.Popup({
                    width : 620
                    ,height : 480
                    ,url : webItemLink.attr("href")
                    ,title : "Export to Word"
                    ,applicationName : "Scroll&trade; Office"
                    ,applicationLink : "http://www.k15t.com/display/web/Scroll+Office"
                    ,applicationVersion : SCROLL_VERSION
                    ,afterInit : function(data) {
                        $("#includeLabelList").unbind("click").bind("click", function() {
                            $("#includePageWithLabels").attr("checked", "checked");
                        });
                    }
                });
            });
        }
    });
});

