/*  Will attempt to open the given URL in the background window,
    or if this window has no PIO background window:
        - opens in a new window if this one's a popup
        - opens in this window otherwise. */
function openInBg(url) {
    if (hasPioBgWin()) {
        window.opener.location = url;
    } else if (isPioPopup()) {
        window.open(url);
        window.close();
    } else {
        window.location = url;
    }
}

/*  Like openInBG, but if there's no PIO background window, does nothing. */
function openInBgOnly(url) {
    if (hasPioBgWin()) {
        window.opener.location = url;
    }
}

// "Exit the map", that is:
// if this window has a PIO background window, close this one.
// if has no BG window but is a popup, close this one and open PIO in new win.
// if this IS a main window (i.e. from a search engine), open PIO in this win.
function exitMap(exitUrl) {
    if (hasPioBgWin()) {
        window.close();
    } else if (isPioPopup()) {
        window.open(exitUrl);
        window.close();
    } else {
        window.location = exitUrl;
    }
}

/*  Returns true if the background window (this window's opener) exists
    and identifies as PIO. */
function hasPioBgWin() {
    return window.opener && !window.opener.closed &&
        window.opener.privateislandsonline;
}

// returns true if the current window (or the window object passed to it)
// has a name that indicates it's a PIO popup window.
function isPioPopup() {
    var theWin;
    if (arguments.length == 1) {
        theWin = arguments[0];
    } else {
        theWin = window;
    }
    return theWin.name.split('_')[0] == 'privateislandsonline';
}