(function (window) {
    var currentOverlay;
    var popupseed = 0;
	
	this._setPosition = null;
	this._closePopup = null;
	
	this._show = function(){
		if(this.beforeShow) this.beforeShow();
	
		$("#shadow").css("visibility", "visible");
		$("#mdropopup_1").css("visibility", "visible");
	};
	
   
    function popover(options) {
        var url = options.url,
            html = options.html,
            width = options.width || 350,
            height = options.height,
            scroll = options.scroll === undefined ? !height : options.scroll,
            back = options.back === undefined ? !height : options.back,
            onclose = options.onclose,
            onload = options.onload;
		
		if(options.beforeShow)
			this.beforeShow = options.beforeShow;
		
        if (!html == !url) alert("html or url shoud be supplied but not both.");
        popupseed++;
        var _shadow = $("<div id='shadow' style='visibility: hidden; position:fixed; left: 0; top: 0; background: #666; background: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVQI12NIS0ubCQAENAHMsbKjNwAAAABJRU5ErkJggg==); width: 100%; height: 100%; z-index:10'></div>");
        var _container = $("<div style='visibility: hidden;width: 860px; margin:auto; z-index: 11; position: relative;' id='mdropopup_" + popupseed + "' class='close-handler'></div>");
        var _content = $("<div style='display:none; position:fixed; background: #ccc; width: 650px; border: solid 8px #ccc; margin-left: -8px; border-radius: 10px; -moz-border-radius: 10px; -webkit-border-radius: 10px;-moz-box-shadow: 0 0 20px rgba(0,0,0,0.7); -webkit-box-shadow: 0 0 20px rgba(0,0,0,0.7); box-shadow: 0 0 20px rgba(0,0,0,0.7);'></div>");
        var _titleContent = $("<div style='background: #eee; padding: 6px 10px 4px; border-bottom: solid 1px #e5e5e5; border-radius: 4px 4px 0 0; -moz-border-radius: 4px 4px 0 0; -webkit-border-radius: 4px 4px 0 0'></div>");
        var _backButton = $("<br/><a href='javascript://' class='popup-close' style='text-decoration:none;line-height:1.5em'>&#0171; <u>Back</u></a>");
        var _innerContent = $("<div class='scroll-async-reset' style='padding: 10px 10px; margin: 0 0 1px; border-radius: 0 0 4px 4px; -moz-border-radius: 0 0 4px 4px; -webkit-border-radius: 0 0 4px 4px; position: relative; background: #fff'></div>");
        var _closeBox = $("<div class='popup-close' style='position: absolute; right: 3px; top: 6px; z-index: 20; cursor:pointer; background: url(/images/fancy_closebox.png) no-repeat right center; padding: 0 32px 4px 0; line-height: 24px; font-family:Century Gothic,Trebuchet MS,Helvetica,Arial,Geneva,sans-serif; font-size: 18px; color: #777; text-shadow: 0 1px 1px #fff'><span style='border-bottom: dotted 1px #999'>Close</span></div>");

        _content.appendTo(_container);
        _titleContent.appendTo(_content);
        if (back) {
            _backButton.appendTo(_titleContent);
        }
        _innerContent.appendTo(_content);
        _closeBox.appendTo(_content);

        var request;

        // prevent mousewheel
        _shadow.mousewheel(function (e) { e.preventDefault(); });
        _content.mousewheel(function (e, delta) {
            if (delta > 0 && _innerContent.scrollTop() == 0 || delta < 0 &&
                    _innerContent[0].scrollHeight - _innerContent.outerHeight() <= _innerContent.scrollTop() + 2) {
                e.preventDefault();
            }
        });

        this._setPosition = function(w, h) {
			var localHeight= h ? h:height;
			localHeight = localHeight + 10 * 2 + 3 * 2 + 20 + 46> $(window).height() - 10 ? null : localHeight; 
			var localWidth = w ? w:width;
            if (!localHeight) {
                var goodHeightPercent = 95;
                var minHeightPercent = 95;
                var minHeightAfter = 600;

                var totalHeight = $(window).height() - 10;
                var goodHeight = totalHeight * goodHeightPercent / 100;

                if (goodHeight < minHeightAfter) {
                    localHeight = totalHeight * minHeightPercent / 100;
                } else {
                    localHeight = goodHeight;
                }

                // fix padding and border
                localHeight -= 10 * 2 + 3 * 2 + 20 + 46;

                currentTop = (totalHeight - height) / 2 * 0.5;
                _content.css("top", currentTop);
            }
			
			else localHeight += 10 * 2 + 3 * 2 + 20;

			

            if (scroll) {
                // hidden thing required for IE7
                _innerContent.css({ "overflow-y": "scroll", "overflow-x": "hidden" });
                _innerContent.css("height", localHeight);
            } else {
                _innerContent.css("min-height", localHeight);
            }

            // calculate left, top
            var left = ($(window).width() - localWidth) / 2;
            var top = ($(window).height() - localHeight) / 2 - 40;
            _content.width(localWidth).css({ left: left, top: top });
        }
        this._setPosition();

        $(window).resize(this._setPosition);
		
		this._closePopup = function() {
            // display confirmation box is there's something dirty inside popup
            if (!confirmUnsavedForm(_content)) return false;

            $(window).unbind("resize", this._setPosition);
            if (request) request.abort();
            _shadow.remove();
            _container.remove();
            if (onclose) onclose();
            currentOverlay = null;
            return false;
        }

        $("#" + _container.attr('id') + " .popup-close").live('click', this._closePopup);
        _container[0].close = this._closePopup;

        function showHtml(el) {
            var _el = $(el);
            
			_titleContent.prepend("<span id='iframeTitle' style='font-size:18px;'><a style='font-family:Century Gothic,Trebuchet MS,Helvetica,Arial,Geneva,sans-serif' href='#'>Go to sponsor website</a></span>");

            _el.appendTo(_innerContent);
            _content.fadeIn("fast");
         //   defaultifyForms(_content);
        }

        function showRootElements() {
            $("body").prepend(_container);
            $("body").prepend(_shadow);
        }

        showRootElements();

        if (html) {
            showHtml(html);
        } else {
            // add racing with timer
           showHtml("<iframe height='auto' id='popup' width='100%' src='"+ url +"'/>");
        }
        currentOverlay = this;
        this.close = this._closePopup;
    }

    function closeContainer(innerElement) {
        log("closeContainer", innerElement);
        $(innerElement).closest('.close-handler')[0].close();
    }

    //---------------------------------------------------------------------------------------------------
    // private functions
    function confirmUnsavedForm(element) {
        var hasDirtyForms = $("form.dirty", element).length;
        return !hasDirtyForms || confirm("The form contains unsaved data.\n\nClose it anyway?");
    }

    // export
    window.popup = { 
        popover: popover,
        closeContainer: closeContainer,
		show: this._show
    };

})(window);
