﻿// iit-sourcetech.com JavaScript utilities

function popupLinks() {
    if (!document.getElementsByTagName) { return; }

     // Find all <a> tags on the page
     var anchors = document.getElementsByTagName("a");

     // Loop though them
     var i;
     for (i = 0; i < anchors.length; i++) {
        var anchor = anchors[i];
        if (anchor.getAttribute("href") && anchor.getAttribute("rel") === "external") {
            //Build up a string to open the app in a new window, make sure that each application replaces any old instance of it so that we don't have tons of windows open
            var value = "return popupWindow('" + anchor.getAttribute("href") + "', '" + anchor.parentNode.parentNode.parentNode.id + "');";
            anchor.setAttribute("onclick", value);
        }
     }
 }

function popupWindow(linkUrl, windowName) {

    //call open with no URL, if there's a window with the same name already open we'll be pointed to it otherwise we'll be pointed to a new "blank" popup
    var popup = window.open('', windowName);

    //if the popup window is blank* then there wasn't a window already open, redirect the blank popup to where we really want to go
    //  *to determine "blank", it'd be ideal to only test for empty location host, but accessing that property was problematic in FireFox so we're unfortunately matching href to 
    //   literal string "about:blank" -- works fine for FF and IE as of now -- using secondary "or" check against host offers better future support and support for other browsers
    if (popup.location.href === "about:blank" || popup.location.host === "") {
        //new popup window already has focus and is brought to front, just need to redirect to the requested url

        //This code is in a try/catch because if the user chooses not to navigate away from the page, an exception will be thrown.
        //(this only will happen if the user chooses to replaceLocationIfDifferent because navigating from about:blank
        //doesn't will not yield that message)
        try { popup.location = linkUrl; }
        catch (ex) { }
    }

    if (window.focus) { popup.focus(); }

    //cancel the click on the link so the opener window doesn't also navigate to the URL of the popup
    return false;
}

// On load of the window handle popup links
window.onload = popupLinks;
