/**
 * general function can be applied to a normal link as follows:
 *
 * <a href="url" target="winname" onclick="return popupLink(this);">...</a>
 *
 */
function popupLink (link, x, y, options) {
    if (!options) options = 'scrollbars=auto,status=no,resizable=yes';
    var windowXY = findWindowCenter(x ? x : 400, y ? y : 400);
    var name = link.target ? link.target : '_blank';
    var href = appendTargetParam(link.href, "popup");
    var newWin = open(href, name, windowXY + ',' + options);
    if (!newWin.opener) newWin.opener = self;
    newWin.focus();
    return false;
}

function popupForgotPassword (link) {
    return popupLink(link, 400, 250, 'toolbar=0,scrollbars=0,location=0,status=0,menubar=0,resizable=0');
}

function popupJournal (link) {
    return popupLink(link, 400, 450);
}

function popupCoach (link) {
    return popupLink(link, 300, 450);
}

function popupAudio (link) {
    return popupLink(link, 300, 180, 'scrollbars=no,status=no,resizable=no');
}

function popup_pdf (link) {
    return popupLink(link, 800, 600);
}

function popup_msoffice (link) {
    // do nothing: this was causing too much problems with popping up un-chromed windows in IE
    return true;
    // return popupLink(link, 800, 600);
}

function popup_doc (link) {
    return popup_msoffice(link);
}

function popup_ppt (link) {
    return popup_msoffice(link);
}

function popupAnnotate (link) {
    return popupLink(link, 500, 350);
}

function findWindowCenter(winWidth, winHeight) {
    // Target the window to open in the center of the screen
    var screenWidth = screen.width;
    var screenHeight = screen.height;

    var windowX = (screenWidth - winWidth) / 2;
    var windowY = (screenHeight - winHeight) / 2;

    var centerString = "width=" + winWidth + ",height=" + winHeight + ",top=" + windowY + ",left=" + windowX;

    return centerString;
}

/**
 * HACK: this is nasty!!
 * use it to add target=popup param, which lets app know whether to put close or back buttons
 */
function appendTargetParam (url, val) {
    var targetRe = /([?&])target=[^?&]*/;
    if (url.match(targetRe))
        return url.replace(targetRe, "$1target=" + val);
    else
        return url + ((url.indexOf('?') > 0) ? "&" : "?") + "target=" + val;
}
