﻿function ezModalAdd(anchor, options) {
    var defaultOptions = {
        width: 720,
        height: 480,
        sizeToContent: false,
        appendToUrl: ""
    };
    options = $.extend({}, defaultOptions, options);
    if (options.sizeToContent) options.height = 2000; // we set this high so it will be sized down to the eventual height;
    
    var url = anchor.href + options.appendToUrl;
    //ezModalOptions = options; ezModalReadyFired = false;
    var modal = $("<div id='ezmodal' style='position:absolute; left: " + (-options.width - 1000) + "px; top: " + (-options.height - 1000) + "px'><div class='modal-header'></div><iframe frameborder='0' style='width: " + options.width + "px; height: " + options.height + "px;' src='" + url + "'></iframe></div>").appendTo('body');
    var iframe = $("#ezmodal iframe")
    iframe.load(function() { ezModalShow(options) });
    //iframe.attr("src", url);
    anchor.blur();
    return false;
}

function ezModalShow(options) {
    activeModal = $("#ezmodal");
    var iframe = $("#ezmodal iframe");
    var framecontents = iframe.contents();
    var frameheader = framecontents.find("h2");
    var header = $("#ezmodal .modal-header");
    // replace header with the h2 in the iframe
    if (frameheader.length > 0) {
        header.html(frameheader.html());
        frameheader.eq(0).css("display", "none");
    }
    // take measurements before we hide the frame
    var dynamicHeight
    if (options.sizeToContent) {
        dynamicHeight = framecontents.find("body")[0].offsetHeight;
        if (dynamicHeight > $(window).height() * .9) {
            dynamicHeight = $(window).height() * .9
        } else {
            iframe.attr("scrolling", "no");
        }
        iframe.css("height", dynamicHeight + "px");
    }
    else
        dynamicHeight = options.height;
    var headerHeight = header.outerHeight();
    var framecontentheight = framecontents.find("body")[0].offsetHeight;
    activeModal.css("left","").css("top","").css("position","");
    //show the modal with dynamic measuring of the height
    if (activeModal.length > 0) {
        $.modal(activeModal, {
            containerCss: {
                height: dynamicHeight + headerHeight,
                width: options.width
            },
            onClose: ezModalClose
        });
    }
}

function ezModalClose() {
    $.modal.close();
    $("#ezmodal").remove();
}

/*var ezModalOptions, ezModalReadyFired;
function ezModalFrameReady() {
    if (!ezModalReadyFired) {
        ezModalShow(ezModalOptions);
        ezModalReadyFired = true;
    }
}*/
