/// <reference path="jquery-1.2.6.js" />
/// <reference path="inPractice-utilities.js" />

$(document).ready(function() {
    inPractice = new inPracticeRoot();
    InPractice = inPractice; // for legacy purposes
});


function inPracticeRoot() {
    function getMeta(name) {
        return $("head").find("meta[name=" + name + "]").attr("content");
    }
    this.contentId = getMeta("guid");
    this.contentTitle = getMeta("title");
    this.contentPageType = getMeta("pagetype");
    this.contentPageName = getMeta("pageName");
    //var showInterstitial = $("#txtShowInterstitial");
    //var interstitial = $("#txtInterstitial");
    //if (showInterstitial.val() && showInterstitial.val()=="true")
    //    this.interstitials = new ccoInterstitials(this.contentId, showInterstitial.val(), interstitial.val());
    
    inPracticeSupport();
    this.search = new inPracticeSearch("/inPractice");
    this.poc = new inPracticePoc(this);
    inPracticeToolTips();
    inPracticeKeywords();
    this.suggestedCme = new inPracticeSuggestedCme(this.contentId);
    inPracticeBookshelf(this.contentId);
    this.cmeManager = new inPracticeCmeManager();
    this.cme = new inPracticeCme(this.contentId);
    this.share = new inPracticeShare(this);

    $('#modalDialogContent').height($(window).height() - 225);

    if ($(".chapterAbstract").length > 0) {
        $(".chapterAbstract").truncate();
    }
}

function inPracticeSupport() {
    if($("#modalDialog").length > 0) {
        $('#modalDialog')
        .jqm({ modal: true, onHide: function(hash) {
            hash.w.hide();
            hash.o.remove();
            if (typeof(jqmHideFunc) !== 'undefined' && jqmHideFunc) { jqmHideFunc(hash); }
        } })
        .jqDrag("#modalDialogHeader")
        .jqmAddClose("#modalDialogCloseBtn a");
    
        $(".popAsset").click(function(e) {
            var link = $(e.target);
            var href = link.attr("href");
            var extras = link.find("input:hidden").val();
            CCOWindowOpen(href, ("asset" + new Date().getTime()), extras, true);
            return false;
        });
    }

    if ($(".supporter_slideshow").length > 0) {
        $(".supporter_slideshow").cycle();
        $(".supporter_slideshow").css({ visibility: "visible" });
    }
}

function inPracticeSuggestedCme(pageId) {
    var replace = function() {
        this.spinner.show();
        content.replacePartial("GetEditSuggestedCmeControl", pageId, function(html) {
            this.content.html(html);
            this.spinner.hide();
        });
    }

    $(".GetEditSuggestedCme").modalDialogOpener(function(el, content, title, spinner) {
        title.html("Edit Suggested CME");
        this.content = content;
        this.spinner = spinner;
        replace();
    });

    this.addCme = function(pageToAdd) {
        $.inpAjax({
            methodName: "AddSuggestedCme",
            data: { pageId: pageId, url: $(pageToAdd).val() },
            success: replace
        });
        return false;
    }

    this.deleteCme = function(form) {
        var pages = [];
        $(form).find("input:checked").each(function() { 
            pages.push($(this).val());
        });
        if (pages.length == 0)
        {
            alert("You must check at least one page to submit");
        }
        else 
        {
            $.inpAjax({
                methodName: "RemoveSuggestedCme",
                data: { pageId: pageId, suggestedPageIds: pages },
                success: replace
            });
        }
        return false;
    }
}

function inPracticeShare(root) {
    $(".share").modalDialogOpener(function(el, content, title, spinner, footer) {
        $.inpAjax({
            methodName: "GetPartial",
            data: { source: "getRateAndSharePanel", parameters: [root.contentId, root.contentTitle, root.contentPageType, root.contentPageName] },
            success: function(html) {
                content.html(html);
                spinner.hide();
            }
        });
    });

    this.submit = function(e) {
        var form = $(e).parents("form");
        var email = form.find("#email").val();
        var note = form.find("#note").val();

        $.inpAjax({
            methodName: "Share",
            data: { email: email, note: note, pageId: root.contentId, drugName: root.contentTitle, pageType: root.contentPageType, pageName: root.contentPageName },
            success: function(response) {
                $("#confirmation").fadeOut(function() { $(".emailRepeat").html(email); $(this).fadeIn(); });
            }
        });
    }

}

function inPracticeCme(contentId) {
    $(".activityElements").modalDialogOpener(function(el, content, title, spinner, footer) {
        $.inpAjax({
            methodName: "GetPartial",
            data: { source: "GetElements", parameters: [el.metadata().eid, el.attr("class").split(" ")[0]] },
            success: function(html) {
                content.html(html);
                var buttons = content.find("#eulaFooter")
                inPractice.cme.poppingEula = buttons.length > 0;
                if (buttons.length > 0) {
                
                    buttons.appendTo(footer);
                    footer.show();
                    content.scroll(function(e) { inPractice.cme.scrollin(e, content); });
                }
                spinner.hide();
            }
        });
    },
    function(hash) {
        if (!inPractice.cme.poppingEula) {
            location.reload(true);
        }
    }, true);

    this.acceptEula = function() {
        if ($("#acceptEula").hasClass('eula_ok_button_disabled')) {
            alert('You must scroll to the bottom in order to activate this button.');
        }
        else {
            $.inpAjax({
                methodName: "AcceptEula",
                data: { pageId: contentId },
                success: function(json) {
                    location.href = json.redirectUrl;
                }
            });
        }
    }

    this.declineEula = function() {
        $.inpAjax({
            methodName: "DeclineEula",
            data: { pageId: contentId },
            success: function() { $("#modalDialog").jqmHide(); }
        });        
    }

    this.scrollin = function(e, scrollWindow) {
        var heightOfEula = $("#eula").height() - scrollWindow.height();
        var heightToTop = scrollWindow.scrollTop();

        if (heightToTop > heightOfEula - 40) {
            $("#acceptEula").removeClass('eula_ok_button_disabled');
            $("#acceptEula").addClass('eula_ok_button');
        }
    }
}

function inPracticeCmeManager() {
    var service = "/WebServices/inPractice.asmx";
    var resultSize = {};
    var isGettingResults = false;
    var searchResultDiv = ".sectionContent";
    
    $(".deleteTest").click(function(e) {
        var cmeid = $(e.target).attr("name");
        $.inpAjax({
            methodName: "DeleteTest",
            data: { id: cmeid },
            success: function() { window.location.reload(); }
        });
    });

    $(".deleteTestInteraction").click(function(e) {
        var cmeid = $(e.target).attr("name");
        $.inpAjax({
            methodName: "DeleteTestInteraction",
            data: { id: cmeid },
            success: function() { window.location.reload(); }
        });
    });

    $(".deleteNonCCOCME").click(function(e) {
        var cmeid = $(e.target).attr("name");
        $.inpAjax({
            methodName: "DeleteNonCcoCme",
            data: { id: cmeid },
            success: function() { window.location.reload(); }
        });
    });

    // turn the loader gif on/off
    function gettingCmeResults(parentDiv, gettingResults) {
        var img = parentDiv.find(".jLoading");
        var showMoreResults = parentDiv.find(".jShowMoreResults");
        if (gettingResults) {
            img.show();
            showMoreResults.hide();
        } else {
            img.hide();
            showMoreResults.show();
        }
        isGettingResults = gettingResults;
    }

    this.getMoreCme = function(target, initialResultSize, totalResultSize, numResultsToGet, year) {
        var methodName = "GetPocPending";
        if (!isGettingResults) {
            var containingDiv = $(target).parents(searchResultDiv);

            // turn on the ajax loader img
            gettingCmeResults(containingDiv, true);

            // we set the size of the result set to the initial size the first time
            if (resultSize[methodName] == null) {
                resultSize[methodName] = initialResultSize;
            }

            $.inpAjax({
                methodName: methodName,
                data: {
                    startResult: resultSize[methodName],
                    numToGet: numResultsToGet,
                    year: year
                },
                success: function(html) {
                    html = html.replace(/\n/g, "").replace(/\r/g, "");
                    var size = resultSize[methodName] + numResultsToGet;
                    if (size > totalResultSize) { size = totalResultSize; }
                    resultSize[methodName] = size;

                    if (size >= totalResultSize) {
                        var resultsToGetSpan = containingDiv.find(".jShowMoreResults");
                        resultsToGetSpan.remove();
                    }
                    else if (totalResultSize - size < numResultsToGet) {
                        containingDiv.find(".jResultsToGet").fadeOutAndIn(totalResultSize - size);
                    }

                    // fade in the new result list items
                    var table = containingDiv.children(".cmeTable");
                    $('tbody', table).append(html).fadeIn("slow");

                    // fade out the old result size
                    containingDiv.find(".jResultCount").fadeOutAndIn(size);

                    inPractice.poc = new inPracticePoc();
                },
                complete: function() {
                    gettingCmeResults(containingDiv, false);
                }
            });
        }
        return false;
    };
}

function inPracticeBookshelf(pageId) {
    function toggleBookmark(pageId, successFn) {
        $.inpAjax({
            methodName: "ToggleBookmark",
            data: { pageId: pageId },
            success: function(count) {                
                $(".bookmarkCount").fadeOut(function() {
                    if (count != 0) { $(this).html(count).fadeIn(); }
                });
                successFn();
            }
        });
    }

    $(".toggleBookmark").click(function(e) {
        toggleBookmark(pageId, function() { 
            var hidden = $(".toggleBookmark").find(":hidden");
            $(".toggleBookmark").find(":visible").fadeOut(function() { hidden.fadeIn(); });
        });
    });

    $(".removeBookmark").click(function(e) {
        var target = $(e.target)
        toggleBookmark(target.attr("id"), function() {
            target.parents("tr").fadeOut();
        });
    });

    $(".addBookmark").click(function(e) {
        var id = $(e.target).attr("id");
        toggleBookmark(id, function() {
            location.reload(true);
        });
    });
}

function inPracticeSearch(root) {
    var url = root + "/Search.aspx?q=";
    var searchResultDiv = ".searchSection";
    var service = "/WebServices/inPractice.asmx";
    var resultSize = {};
    var isGettingResults = {};

    var clusterDiv = $(".clusterHolder");
    if (clusterDiv.length > 0) {
        var spinner = html.img("/images/inPractice/ajax-loader.gif", "spinner", "spinner");
        clusterDiv.prepend(spinner);

        $.inpAjax({
            methodName: "GetClusters",
            data: { searchTerm: jQuery.url.param("q") },
            success: function(html) {
                if (html.indexOf("<li>") >= 0) {
                    clusterDiv.html(html);
                }
                else {
                    clusterDiv.html("<p><em>No related search terms were found</em></p>");
                }
            },
            showErrorMessage: false,
            complete: function() { spinner.hide(); }
        });
    }

    $(".collapsibleBar").click(function(e) {
        var bar = $(this);
        var targets = bar.parents(".collapsibleSection").children(":not(.collapsibleBar)");

        var visibleNow = targets.is(":visible");
        var obj = visibleNow ? 
                {func: "slideUp", toAdd: "collapsed", toRemove: "notCollapsed"} :
                { func: "slideDown", toAdd: "notCollapsed", toRemove: "collapsed" };
                
        bar.addClass(obj.toAdd);
        bar.removeClass(obj.toRemove);
        targets[obj.func]("normal");
    });

    $(".searchFilter").click(function(e) {
        var id = $(this).attr("id");
        if (id == "filter_All") {
            $(".searchSection").show();
        } else {
            $(".searchSection").hide();
            var targ = "#section_" + id.substr(7);
            $(targ).show();
        }
        return false;
    });

    // turn the loader gif on/off
    function gettingSearchResults(category, parentDiv, gettingResults) {
        var img = parentDiv.find(".jLoading");
        var showMoreResults = parentDiv.find(".jShowMoreResults");
        if (gettingResults) {
            img.show();
            showMoreResults.hide();
        } else {
            img.hide();
            showMoreResults.show();
        }
        isGettingResults[category] = gettingResults;
    }

    var getMoreResults = function(target, category, preference, initialResultSize, numResultsToGet, totalResults) {
        if (!isGettingResults[category]) {
            var containingDiv = $(target).parents(searchResultDiv);

            // turn on the ajax loader img
            gettingSearchResults(category, containingDiv, true);

            var resultList = containingDiv.find(".resultsList");
            var searchTerm = jQuery.url.param("q");

            // we set the size of the result set to the initial size the first time
            if (resultSize[category] == null) {
                resultSize[category] = initialResultSize;
            }

            AjaxRequest({
                service: "inPractice",
                methodName: "GetResults",
                data: {
                    searchTerm: searchTerm,
                    category: category,
                    preference: preference,
                    startResult: resultSize[category],
                    numToGet: numResultsToGet,
                    total: resultSize[category]
                },
                success: function(html) {
                    var html = $(html.replace(/\n/g, "").replace(/\r/g, ""));
                    var totalResultSize = html.filter("#numResults_" + category).val();
                    numResultsToGet = html.filter("#numResultsToGet_" + category).val();

                    if (totalResultSize != 0) {
                        containingDiv.find(".jTotalResults").html(totalResultSize);
                        containingDiv.find(".jShowingResults").fadeIn();
                    }

                    var size = parseInt(resultSize[category]) + parseInt(numResultsToGet);
                    if (size > totalResultSize) { size = totalResultSize; }
                    resultSize[category] = size;

                    if (size >= totalResultSize) {
                        var resultsToGetSpan = containingDiv.find(".getMoreResults");
                        resultsToGetSpan.remove();
                    }
                    else if (totalResultSize - size < numResultsToGet) {
                        containingDiv.find(".jResultsToGet").fadeOutAndIn(totalResultSize - size);
                    }

                    // fade in the new result list items
                    if (html.length > 0) {
                        html.hide().appendTo(resultList).fadeIn();
                    }

                    // fade out the old result size
                    containingDiv.find(".jResultCount").fadeOutAndIn(size);
                },
                showErrorMessage: false,
                complete: function() {
                    gettingSearchResults(category, containingDiv, false);
                }
            });
        }
    };

    this.getMoreResults = getMoreResults;

    $(".getInitialResults").each(function(index, el) {
        getMoreResults(el, $(el).metadata().coll, $(el).metadata().pref, 0, 5);
    });

    function search(input) {
        var term = jQuery.trim($(input).val());

        var spec = $("input[@name='sFilter']:checked").val();
 
        if (term.length > 0 && term != 'Enter search terms here') {
            window.location = url + term + "&sf=" + spec;
        }
        else {
            alert("Please enter a search term");
        }
    }
    
    function searchMobile(input) {
        var term = jQuery.trim($(input).val());
        
        var spec;
        
        if ($("#filterHIV:checked").val() !==null && $("#filterOncology:checked").val() == null)
        {
            spec = "HIV";
        }
        else if ($("#filterHIV:checked").val() ==null && $("#filterOncology:checked").val() !==null)
        {
            spec = "Oncology";
        }
        else
        {
            spec = "All";
        }
 
        if (term.length > 0 && term != 'Enter search terms here') {
            window.location = url + term + "&sf=HIV";
        }
        else {
            alert("Please enter a search term");
        }
    }


    // clicking the search buttons
    $(".jSearch").click(function() { search("#q"); });
    $(".jSearchMobile").click(function() { searchMobile("#q"); });
    $(".jSearchBox").keyup(function(e) { if (e.which == 13) { search(e.target); } });   
}

function inPracticeToolTips() {
    var standard = {
        width: "600px",
        ajaxPath: ["$(this).attr('href').replace(/ /gi,'%20')"]
    };

    var help = {
        width: "300px"
    };

    var suggestedCme = {
        width: "300px",
        trigger: "click"
    };

    if (jQuery.bt) {
        var d = jQuery.bt.defaults;
        d.fill = "#FFFFF0";
        d.trigger = "click";
        d.closeWhenOthersOpen = true;
        d.ajaxLoading = "<p><img src='/images/inPractice/ajax-loader.gif' /> Loading...</p>";
        d.ajaxCache = true;
        d.positions = ["right", "left", "top", "bottom"]

        $(".helpMiniSite").bt(help);

        // references
        $(".miniSite").each(function() {
            $(this).bt(standard).click(function() { return false; }); // they don't use each in their selector...grr!
        });

        $(".supporterMiniSite").bt({
            width: "420px",
            ajaxPath: ["$(this).attr('href')"]
        }).click(function() { return false; });

        $(".suggestedMiniSite").bt(suggestedCme);
    }
}

function inPracticePoc(context) {
    $(".claimCredit").modalDialogOpener(function(el, content, title, spinner) {
        var clicked = $(el);
        var activityId = clicked.find("input:hidden").val();
        $.inpAjax({
            methodName: "GetPartial",
            data: { source: "GetActivitySubmissionPanel", parameters: activityId },
            success: function(html) {
                content.html(html);
            },
            complete: function() { spinner.hide(); }
        });
    }, function() { location.reload(true); });

    function validateText(questionId) {
        var containerDiv = $("#" + questionId);
        var textArea = containerDiv.find("textarea");
        if (textArea.length > 0) {
            var text = jQuery.trim(textArea.val());
            var freeTextRadioButton = $("#answer_" + textArea.attr("id"));
            if (freeTextRadioButton.attr("checked") && text == "") {
                containerDiv.find(".error:last").show();
                return false;
            }
        }
        return true;
    }

    function validateGroup(questionId) {
        var containerDiv = $("#" + questionId);
        var error = containerDiv.find(".error:first");
        if (containerDiv.find("input:checked").length == 0) {
            error.show();
            return false;
        }
        error.hide();
        return true;
    }    

    function getMcResponses(form) {
        var mcResponses = [];
        form.find("input:checked").each(function() {
            mcResponses.push($(this).attr("name"));
            mcResponses.push($(this).val());
        });
        return mcResponses;
    }

    function getFreeResponses(form) {
        var freeRespones = []
        form.find("textarea").each(function() {
            freeRespones.push($(this).attr("name"));
            freeRespones.push($(this).val());
        })

        if (freeRespones.length == 0) {
            freeRespones.push("");
            freeRespones.push("");
        }        
        return freeRespones;
    }

    this.submit = function(form) {
        var form = $(form);

        var valid = true;
        var error = form.find(".error:first");
        form.find(".question").each(function(i, el) {
            var id = $(el).attr("id");
            valid = valid & validateGroup(id) & validateText(id);
        });
        if (!valid) {
            location.href = "#top";
            error.show();
            return false;
        }
        error.hide();

        $.inpAjax({
            methodName: "CompletePocActivity",
            data: {
                activityId: form.attr("id"),
                mcResponses: getMcResponses(form),
                freeResponses: getFreeResponses(form)
            },
            success: function() {
                $("#pocEvaluation").fadeOut(function() {
                    var cert = $("#pocCertificate");
                    var href = cert.find("input").val();
                    cert.find("iframe").each(function() { this.contentWindow.location.href = href; });
                    cert.fadeIn();                  
                });
            }
        });
        return false;
    }
}

function inPracticeKeywords() {
    function keywordRequest(serviceMethod, data, spinner) {              
        spinner.show();
        $.inpAjax({
            methodName: serviceMethod,
            data: data,
            success: function(html) {
                location.reload(true);
            },
            complete: function() {
                spinner.hide();
            }
        });
    }

    function addEditForm(container, serviceMethod, formValues, spinner) {
        formValues = formValues ? formValues : { id: "", title: "" };
        
        container.append(
            "<form><label for='keywordTitle'>Title</label>" +
            "<div><input type='text' id='keywordTitle' name='keywordTitle' value='" + formValues.title + "' />" +
            "<input type='submit' id='saveSubmit' value='Save' />" +
            (formValues.id != "" ? "<input type='submit' id='deleteSubmit' value='Delete' /></form>" : "") +
            "</div>"
        );

        if (formValues.id != "") {
            $("#saveSubmit").css("float", "left");
            $("#deleteSubmit").css("float", "left");
        }
        
        $("#saveSubmit").click(function(e) {
            keywordRequest(serviceMethod, { keywordId: formValues.id, 
                           title: encodeURIComponent($("#keywordTitle").val()) }, spinner);
            return false;                        
        });

        $("#deleteSubmit").click(function(e) {
            if (confirm("ARE YOU SURE? This will delete the keyword and all associated content")) {
                keywordRequest("DeleteKeyword", { keywordId: formValues.id }, spinner);
            }
            return false;
        });

        spinner.hide();
    }

    $(".editKeyword").modalDialogOpener(function(el, content, title, spinner) {
        var id = $(el).attr("id").split("~")[1];
        var prevA = $(el).prev().html();
        addEditForm(content, "EditKeyword", { title: prevA, id: id }, spinner);
    });

    $(".addKeyword").modalDialogOpener(function(el, content, title, spinner) {
        addEditForm(content, "AddKeyword", null, spinner);
    });

    $(".editContentKeywords").modalDialogOpener(function(el, content, title, spinner) {
        title.html("Edit Keywords");
        var id = inPractice.contentId;
        spinner.show();

        var ml = html.div();
        ml.multiList(
            function(callback) {
                $.inpAjax({
                    methodName: "GetKeywords",
                    data: { pageId: id },
                    success: function(obj) {
                        callback({ left: obj[0], right: obj[1], text: "Title", value: "Id" }, function() {
                            $(content).html(ml);
                        });
                    },
                    complete: function() { spinner.hide(); }
                });
            },
            function(selected) {
  
                var keywordIds = [];
                selected.each(function() {
                    keywordIds.push($(this).attr("value"));
                });
                if (keywordIds.length == 0) { keywordIds.push(""); }
                keywordRequest("UpdateKeywords", { pageId: id, keywordIds: keywordIds }, spinner);
            }
        );
    });
}

function clearSearchBox() {
    if ($("#q").val() == 'Enter search terms here') {
        $("#q").removeClass('greytext');
        $("#q").val('');
    }
}

/* Legacy shit so we don't need to include cco.js in inpractice */

function popPage(path) {
    popWindow(path, 600, 530);
}

function openExternalLink(url) {
    alert("You are now leaving this CME activity and visiting an external site. The faculty, the accrediting body, and Clinical Care Options, LLC are not responsible for the accuracy or objectivity of the content of the site you are about to visit. Click 'OK' to continue to the external site.");
    CCOWindowOpen(url, "external");
}

function PopCertificate(guid, type) {
    var url = "/x/Certificate.aspx?ID=" + guid;
    if (type != null) url += "&type=" + type;

    CCOWindowOpen(url, "certificate", "height=680,width=650,status,scrollbars,toolbar", true);
}

function popWindow(path, width, height)
{
	var nURL;

	// Previously, nURL = escape(path). This would escape the querystring parameters.
	// Now, we only escape the non-querystring parameter portion of the URL
	var i = path.indexOf("?");
	if (i > 0)
	{
		// Escape the URL, but not the parameters
		nURL = escape(path.substring(0, i));
		nURL += path.substring(i, path.length);
	}
  	else
	{
		nURL = escape(path);
	}

	if (path.indexOf(".aspx") == -1)
	{
		nURL = "/layouts/CCO.Print.aspx?path=" + nURL;
		nURL += "&p=1";
	}
	
	var d = new Date();
	var millis = Math.floor(d.getTime());
	var w;
	
	var title = "print" + millis;
	w = window.open(nURL, title, "width=" + width + ", height=" + height + ", resizable, scrollbars=1");

	if (w)
		w.focus();
	else // blocked!
		alert('Message from Clinical Care Options:\n' +
				'\n' +
				'The item you clicked on cannot be displayed - most likely\n' +
				'because you are blocking popup windows for this site.\n' +
				'\n' +
				'Try clicking on the item again. If that doesn\'t work, you\n' +
				'will need to disable popup blocking to see the item.\n');
}

function CCOWindowOpen(url, title, extras,suppressLG)
{
	var date = new Date();
	var millis = Math.floor(date.getTime());
	var openedWindow;

	var internalLink = true;
	
	if (title == "external")
	{
		internalLink = false;
	}
	title = title.split(" ").join("") + millis;
	
	// what is the following for?
	
	// "normalize" URL
//	if ((url.substr(0, 4).toLowerCase() != "http") && (url.indexOf('/') > 0 || url.indexOf('/') < 0))
//	{
//		url = Url.substr(0, Url.lastIndexOf('/') + 1) + url;
//	}
	// add the print layout unless external url
	if (internalLink && !suppressLG)
	{
		// check to see if a layout is already specified
		if (url.toLowerCase().indexOf("lg=") < 0)
		{
			if (url.indexOf("?") > 0)
			{
				url += "&lg=print";
			}
			else
			{
				url += "?lg=print";
			}
		}
	}
	if (extras)
	{
        if (extras.toLowerCase().indexOf("scrollbars") < 0)
	    {
		    // Add "scrollbars=1"
		    if (extras.length == 0)
		    {
			    extras = "scrollbars=1";
		    }
		    else
		    {
			    extras += ",scrollbars=1";
		    }
	    }		
	    openedWindow = window.open(url, title, extras);
	}
	else
	{
		openedWindow = window.open(url, title);
	}
	if (openedWindow)
	{
		openedWindow.focus();
	}
	else // blocked!
	{
		alert('Message from Clinical Care Options:\n' +
				'\n' +
				'The item you clicked on cannot be displayed - most likely\n' +
				'because you are blocking popup windows for this site.\n' +
				'\n' +
				'Try clicking on the item again. If that doesn\'t work, you\n' +
				'will need to disable popup blocking to see the item.\n');
	}
}

function openWindowCentered(url, title, params, height, width, suppressLG) {
    var left = (screen.width - width) / 2;
    var top = (screen.height - height) / 2;

    CCOWindowOpen(url, title, (params + ", width=" + width + ", height=" + height + ", top=" + top + ", left=" + left), suppressLG);
}


function ccoInterstitials(contentId, show, interstitial) {
    if (show) {
        var modal = $('#modalDialog');
        $('#modalDialogHeader').css({ visibility: "hidden" });
        modal.jqm({
            modal: true,
            onShow: function(h) {
                /* callback executed when a trigger click. Show notice */
                h.w.css('opacity', .96).slideDown();
            },
            onHide: function(h) {
                /* callback executed on window hide. Hide notice, overlay. */
                h.w.slideUp("slow", function() { if (h.o) h.o.remove(); });
            }
        });
        modal.html('<iframe id="int' + interstitial + '" class="intFrame" src=\"../../Interstitials/' + interstitial + '.aspx?id=' + contentId + '&interstitial=' + interstitial + '\" onLoad=\'calcHeight("int' + interstitial + '");\' />');
        modal.jqmShow();


        this.close = function() {
            modal.jqmHide();
        }
    }
}


function calcHeight(iframeTitle) {
    //find the height of the internal page
    //Firefox returns incorrect scrollheight so use scrollMaxY + innerHeight to calculate height of content
    var the_height = document.getElementById(iframeTitle).contentWindow.scrollMaxY + document.getElementById(iframeTitle).contentWindow.innerHeight;
    //IE doesnt support scrollMaxY so use scrollHeight
    if (isNaN(the_height))
        the_height = document.getElementById(iframeTitle).contentWindow.document.body.scrollHeight + 5;
    //change the height of the iframe, maximum of 400 pixels for interstitial
    if (the_height > 400) the_height = 400;
    document.getElementById(iframeTitle).height = the_height;

}
