/*global jQuery*/
(function($) {

    // -------------------------------------------------------------------------
    // 	Remove Box
    // -------------------------------------------------------------------------
    function removeBox(e) {
        function removeElement() {
            target.parentNode.removeChild(target);
            NOOVO.util._equalHeight();
            return false;
        }

        function confirm(e) {
            if (e.target.className !== "undorm") {
                $.ajax({
                    url: "/services/rest/?method=people.removeWidget&widget_id=" + target.id.slice(7),
                    success: removeElement,
                    error: function () {
                                alert(gettext("Couldn't remove widget"));
                           }
                });
            } else {
                $("p.confirmtxt", target).remove();
                $(".noshow", target).removeClass("noshow");
            }
            return false;
        }

        var anim;
        var target = e.target;

        while (target.tagName.toLowerCase() != "div") {
            target = target.parentNode;
        }

        $(target).addClass("rmwidget")
                .children().each(function () {
                    if (this.tagName.toLowerCase() !== "h3") {
                        $(this).fadeOut(400, function () {
                            $(this).addClass("noshow").fadeIn("fast");
                        });
                    }
                });

        window.setTimeout(function () {
            $('<p class="confirmtxt">'
                    + gettext("Are you sure you want to remove this widget from your Profile? <a href='#' class='#'>Remove</a> or <a href='undorm'>Cancel</a>.")
                    + '</p>')
                .appendTo(target)
                .click(confirm);
        }, 500);

        return false;
    }

    // -------------------------------------------------------------------------
    //	Edit Box
    // -------------------------------------------------------------------------
    function editBox(e) {
        function flashBox(tweenFunction) {
            $(target).fadeOut()
                     .queue(function () {
                         tweenFunction();
                         $(this).dequeue();
                     })
                     .queue(function () {
                         $(target).fadeIn();
                         $(this).dequeue();
                     });
        }

        function cancelForm(e) {
            var savecancel = target.getElementsByTagName("button")[0];
            var em;

            // Remove hide from nonempty
            $(".hide", target).each(function () {
                if ($("input", this).val() || $("textarea", this).val()) {
                    if (!$(this).hasClass("keep_hidden")) {
                        $(this).removeClass("hide");
                    }
                }
            });

            // Expose hidden values (.noshow) and hide those with .hide (but don't step on your toes)
            $(".noshow", target).addClass("hide2").removeClass("noshow");
            $(".hide", target).addClass("noshow").removeClass("hide");
            $(".hide2", target).addClass("hide").removeClass("hide2");

            $("input", target).each(function (i) {
                if ($(this).attr("type") === "password") {
                    em = $('<em class="value password" id="' + this.id.slice(4) + '">'
                            + this.oldValue
                            + '</em>')[0];
                } else if ($(this).attr("type") === "checkbox") {
                    em = $('<em class="value checkbox" id="' + this.id.slice(4) + '">'
                            + this.oldValue
                            + '</em>')[0];
                } else {
                    em = $('<em class="value" id="' + this.id.slice(4) + '">'
                            + this.oldValue
                            + '</em>')[0];
                }
                this.parentNode.replaceChild(em, this);
            });
            $("textarea", target).each(function (i) {
                em = $('<em class="value textarea" id="'+this.id.slice(4)+'">'+this.oldValue+'</em>')[0];
                this.parentNode.replaceChild(em, this);
            })

            savecancel.parentNode.parentNode.removeChild(savecancel.parentNode);
            target.openEdit = false;

            // XXX: Override behaviour for nooads
            $("div:has(#nooads_publisher)", target).addClass("noshow");
        }

        function saveForm(e) {

            // 'Serialize' form
            var url = "/services/rest/?method=people.setWidgetProperties&widget_id="+target.id.slice(7);
            $("input", target).each(function (i) {
                if ($(this).attr("type") === "checkbox") {
                    url += "&"+this.id.slice(4).split("_")[1] +"=";

                    if ($(this).attr("id") == "inp_nooads_adtype") {
                        // XXX: temporary fix for tooboads. remove this crap asap!
                        if (this.checked == true) {
                            url += "large";
                            this.oldValue = "true";
                        } else {
                            url += "small";
                            this.oldValue = "false";
                        }
                    } else {
                        if (this.checked == true) {
                            url += "true";
                            this.oldValue = "true";
                        } else {
                            url += "false";
                            this.oldValue = "false";
                        }
                    }
                } else {
                    url += "&" + this.id.slice(4).split("_")[1] + "=" + encodeURIComponent(this.value);
                    this.oldValue = this.value;
                }
            });

            $("textarea", target).each(function (i) {
                url += "&" + this.id.slice(4).split("_")[1] + "=" + encodeURIComponent(this.value);
                this.oldValue = this.value;
            });

            // Save form
            $.ajax({
                type: "GET",
                url: url,
                success: function () { window.location.reload(); }, // XXX: Temporary fix - #1471
                failure: function () { alert (gettext("Couldn't save changes. I'm so ashamed.")); }
            });

            // Reinitialize form
            cancelForm(e);
        }

        function showForm(e) {
            var inp, btn, div, i;

            // Expose hidden values (.noshow) and hide those with .hide (but don't step on your toes)
            $(".noshow", target).addClass("hide2").removeClass("noshow");
            $(".hide", target).addClass("noshow").removeClass("hide");
            $(".hide2", target).addClass("hide").removeClass("hide2");

            var ems = $("em", target);
            var ul = ems[0].parentNode.parentNode;
            var buttons = [gettext("Save"), gettext("Cancel")];
            var btnAction = [saveForm, cancelForm];

            ems.each(function (i) {
                if($(this).hasClass("password")) {
                    inp = $('<input type="password" class="value" id="inp_' + this.id + '" />')[0];
                } else if($(this).hasClass("textarea")) {
                    inp = $('<textarea class="value" rows="4" wrap="soft" id="inp_' + this.id + '">')[0];
                } else if($(this).hasClass("checkbox")) {
                    inp = $('<input type="checkbox" class="value" id="inp_' + this.id + '" />')[0];
                } else {
                    inp = $('<input type="text" class="value" id="inp_' + this.id + '" />')[0];
                }
                // noshow is removed from each element small (or the discovery tags don't work well)
                $(ems[i]).find("small").attr("class","noshow");
                inp.oldValue = ems[i].innerHTML;
                $(ems[i]).find("small").text("").attr("style","");

                // strip html tags
                //inp.value = ems[i].innerHTML.replace(/(<([^>]+)>)/ig,"");
                if ($(inp).attr("type") === "checkbox") {
                    if ($(this).text() === "true") {
                        inp.checked = true;
                    } else {
                        inp.checked = false;
                    }
                    inp.style.width = "5%";
                } else {
                    inp.value = $(ems[i]).text();
                    inp.style.width = "70%";
                }
                this.parentNode.replaceChild(inp, this);
            });

            div = document.createElement("li");
            for (i = 0; i < 2; i++) {
                btn = document.createElement("button");
                btn.innerHTML = buttons[i];
                btn.style.marginTop = "5px";
                btn.onclick = function () {
                    flashBox(saveForm);
                };
                div.appendChild(btn);
            }
            div.lastChild.onclick = function () {flashBox(cancelForm);};
            ul.appendChild(div);
        }

        (e.preventDefault) ? e.preventDefault() : e.returnValue = false;

        var target = this;
        while (target.tagName.toLowerCase() != "div") {
            target = target.parentNode;
        }

        if (target.openEdit == true) {
            return;
        }

        target.openEdit = true;

        if (!$("em", target).length) {
            // Hide edit option
            $("a.editsave", target).each(function (i) {
                $(this).empty()
            });
            return false;
        }

        flashBox(showForm);
        return false;
    }

    // -------------------------------------------------------------------------
    // 	Widget plugin
    // -------------------------------------------------------------------------
    $.fn.widgetToolbar = function(params) {
        params = $.extend({ }, params);

        return this.each(function() {
            var widget = $(this);

            // -----------------------------------------------------------------
            //	Initialize
            // -----------------------------------------------------------------
            $("a.editsave", widget).each(function (i) {
                var target = this;

                while (target.tagName.toLowerCase() !== "div") {
                    target = target.parentNode;
                }

                if (!$("em", target).length) {
                    // Hide edit option
                    $(this).empty();
                }
            }).bind("click", editBox);

            $("a.remove", widget).bind("click", removeBox);
        });
    };
})(jQuery);
