(function($) {
    $.fn.bitPopup = function(options) {
        var defaults = {
            MessageBit: ".message-bit-popup",
            PictureBit: ".picture-bit-popup",
            CollageBit: ".collage-bit-popup",
            VideoBit: ".video-bit-popup",
            LinkBit: ".link-bit-popup",
            VideoLinkBit: ".videolink-bit-popup",
            Memory: ".memory-popup",
            SmsBit: ".sms-bit-popup"
        };

        var opts = $.extend(defaults, options);

        var templates = this;

        var toggleListener = null;

        var currentPopup = null;

        var hidden_fullsize_links = $("body").find("a.hidden-fullsize-link")
        hidden_fullsize_links.fancybox({
            "hideOnContentClick": true
        });

        function showPopup(item) {
            var content = item.closest(".memo-lane-content");
            $.metadata.setType("attr", "data");
            var bit_data = content.metadata().bit_data;
            var doc_type = bit_data.doc_type;

            var popup_selector = opts[doc_type];
            var popup = $(popup_selector, templates).clone();

            var popupimg;
            var popupvideo;

            popup.find(".vis").addClass(bit_data.visibility);

            var handler = popupHandlers[bit_data.doc_type];
            if (handler) {
                handler(popup, bit_data);
            }

            if (currentPopup) {
                currentPopup.remove();
            }

            popup.appendTo("body");
            var popup_x = parseInt(content.offset().left) - ((popup.width() - content.width()) / 2);
            var popup_y = parseInt(content.offset().top) - ((popup.height() - content.height()) / 2);

            // FIXME: this is an ugly hack - swfobject seems to need the containing element to be part of the DOM tree
            // ideally this code should be in the VideoBit handler elsewhere in this file
            if (doc_type == "VideoBit") {
                var flashvars = {
                    file: bit_data.popup_video_url,
                    image: bit_data.popup_image_url,
                    width: 320,
                    height: 240
                };
                if (typeof bit_data.popup_video_autoplay != "undefined")
                {
                    flashvars["autostart"] = bit_data.popup_video_autoplay;
                }
                flashvars["logo.hide"] = true;
                var params = {
                    allowFullScreen: "true"
                };

                var vidcontainer = $(".memo-lane-vidcontainer", popup);
                var vidid = "video_" + bit_data.id;
                vidcontainer.attr("id", vidid);
                swfobject.embedSWF("/swf/jwflv/player.swf", vidid, "320", "240", "9.0.0", false, flashvars, params);
            }

            popup.show();
            popup.css("left", popup_x);
            popup.css("top", popup_y);
            bindPopupEvents(content, popup);

            var h_padding = 16;
            var v_padding = 32;

            if (popup.offset().left < $(window).scrollLeft() + h_padding) {
                popup.css("left", $(window).scrollLeft() + h_padding);
            }

            if (popup.offset().top < $(window).scrollTop() + v_padding) {
                popup.css("top", $(window).scrollTop() + v_padding);
            }

            if (popup.offset().left + popup.width() > ($(window).scrollLeft() + $(window).width()) - h_padding) {
                var new_left = (($(window).scrollLeft() + $(window).width()) - popup.width()) - h_padding;
                popup.css("left", new_left);
            }

            if (popup.offset().top + popup.height() > ($(window).scrollTop() + $(window).height()) - v_padding) {
                var new_top = (($(window).scrollTop() + $(window).height()) - popup.height()) - v_padding;
                popup.css("top", new_top);
            }

            popup.css("z-index", "200");
            currentPopup = popup;
            
            if (bit_data.remove == "True"){
                popup.find("a.remove-link").click(function(){
                    $.ajax({
                        url: bit_data.remove_url,
                        dataType: "json",
                        success: $.handleJSON
                    });
                });
            } else {
                popup.find("a.remove-link").remove();
            }

            if (bit_data.edit == "True"){
                popup.find("a.edit-link").attr("href", bit_data.edit_url);
            } else {
                popup.find("a.edit-link").remove();
            }

            if (bit_data.showmore == "True") {
                popup.find("a.showmore-link").attr("href", bit_data.showmore_url);
            } else {
                popup.find("a.showmore-link").remove();
            }
        }

        function hidePopup(item) {
            item.closest(".memo-lane-popup").remove();
            currentPopup = null;
        }

        function bindPopupEvents(item, popup) {
            popup.find(".close-link").click(function() {
                hidePopup(popup);
                return false;
            });
            popup.find(".add").click(function() {
                if (toggleListener) {
                    toggleListener(item);
                }

                hidePopup(popup);
                //toggleItem($(this));
                return false;
            });
        }

        function pictureCollageHandler(popup, bit) {
        	var min_title_width = 200;
            var title = popup.find("p.title");
            var description = popup.find("p.description");
            title.html(unescape(bit.title));
            description.html(unescape(bit.description));
            var popupimg = popup.find("img.memo-lane-big-pic");
            popupimg.attr("src", bit.popup_image_url);
            var max_width = 320; // from max-width css attribute for .link-bit-popup img, .picture-bit-popup img, .collage-bit-popup img
            var max_height = 320; // from max-height css attribute for .link-bit-popup img, .picture-bit-popup img, .collage-bit-popup img
            var img_width;
            var img_height;
            if (bit.original_dims && bit.original_dims.width && bit.original_dims.height) {
                img_width = bit.original_dims.width;
                img_height = bit.original_dims.height;
                var aspect_ratio = img_width / img_height;
                if (img_width > max_width || img_height > max_height) {
                    w_ratio = max_width / img_width;
                    h_ratio = max_height / img_height;
                    if (w_ratio < h_ratio) { // constrain to max width
                        img_width = max_width;
                        img_height = Math.floor(img_width / aspect_ratio);
                    } else { // constrain to max height
                        img_height = max_height;
                        img_width = Math.floor(img_height * aspect_ratio);
                    }
                }
            } else {
                // old images won't have been saved with dimensions
                var aspect_ratio = 4 / 3;
                img_width = max_width;
                img_height = Math.floor(img_width / aspect_ratio);
            }
            popupimg.attr("width", img_width);
            popupimg.attr("height", img_height);
            if (img_width < min_title_width){
                var diff = min_title_width - img_width;
                popupimg.css({"margin-left":diff/2+"px"});
                title.width(min_title_width);
            } else {
                title.width(img_width);
            }
            description.width(img_width);
            popup.find("a.fullsize-link").attr("href", bit.original_image_url);
            popup.find("a.fullsize-link").attr("title", unescape(bit.title));

            popup.find("a.fullsize-link").click(function() {
                popup.hide();
                var hidden_fullsize_link = $("body").find("a.hidden-fullsize-link#hidden-fullsize-link-" + bit.id);
                hidden_fullsize_link.trigger("click");
                return false;
            });
        }

        var popupHandlers = {
            MessageBit: function(popup, bit) {
                    popup.find("p.content").html(unescape(bit.body));
                    popup.find("p.sender").html(unescape(bit.sender));
                },
            PictureBit: pictureCollageHandler,
            CollageBit: pictureCollageHandler,
            VideoBit: function(popup, bit) {
                    popup.find("p.title").html(unescape(bit.title));
                    popup.find("p.description").html(unescape(bit.description));
                    var vidcontainer = popup.find("div.memo-lane-vidcontainer");
                    vidcontainer.css("width", 320);
                    vidcontainer.css("height", 240);
                },
            LinkBit: function(popup, bit) {
                    popup.find("p.title").html(unescape(bit.title));
                    popup.find("p.description").html(unescape(bit.description));
                    popup.find("span.source").html(bit.domain);
                    var popupimg = popup.find("img.memo-lane-big-pic");
                    popupimg.attr("src", bit.image_url);
                    popup.find("a.open-link").attr("href", bit.link);
                },
            VideoLinkBit: function(popup, bit) {
                    popup.find("p.title").html(unescape(bit.title));
                    popup.find("p.description").html(unescape(bit.description));
                    popup.find("span.source").html(bit.domain);
                    var popupvideo = popup.find("div.video");
                    popupvideo.replaceWith(unescape(bit.video_player));
                },
            Memory: function(popup, bit) {
                    popup.find("p.title").html(unescape(bit.name));
                    popup.find("p.description").html(unescape(bit.description));
                    var popupimg = popup.find("img.memo-lane-big-pic");
                    popupimg.attr("src", bit.popup_url);
                },
            SmsBit: function(popup, bit) { }
        };

        return {
            show: function(item) {
                showPopup(item);
            },

            hide: function(item) {
                hidePopup(item);
            },

            currentPopup: function() {
                return currentPopup;
            },

            toggleListener: function(listener) {
                toggleListener = listener;
            }
        }
    };

    $("div.memo-lane-popup").mousedown(function(e) {
        e.stopPropagation();
    });

    $(document).mousedown(function(e) {
        var et = $(e.target);
        if (!et.hasClass("memo-lane-popup") && et.parents('div.memo-lane-popup').length == 0) {
            $("body").children("div.memo-lane-popup").remove(); // the popup is the direct child of body (unlike the templates)
        }
    });

})(jQuery);

