/** Fixes all A tags in the document. */
function fixAnchors() {
    var anchors = document.getElementsByTagName("a");
    for (var i = 0; i < anchors.length; i++) {
        var el = anchors[i];
        // WCM document links need a shorter name
        if (el.className == "wcm-document") {
            fixWcmDocument(el);
        }
        // links to /wps/portal might be rewritten to /wps/myportal
        if (document.location.href.indexOf("/myportal/") >= 0) {
            fixPortal(el);
        }
        // external links open in a new window
        if (isExternal(el.getAttribute("href"))) {
            fixExternal(el);
        }
    }
}


/* Returns true if href is a link to an external site. */
function isExternal(href) {
    if (!href) {
        return false;
    }

    if (href.indexOf("/wps/") >= 0) {
        return false;
    }
    if (href.indexOf("javascript:") >= 0) {
        return false;
    }
    if (href.indexOf("generali") >= 0) {
        return false;
    }
    return true;
}


/* Strips all path info from the HTML inside this tag */
function fixWcmDocument(element) {
    var html = element.innerHTML;
    html = html.substring(html.lastIndexOf("/") + 1);
    element.innerHTML = html;
    element.style.display = 'block';
}

/* Replaces /portal/ by /myportal/ */
function fixPortal(element) {
    var link = element.getAttribute("href");
    if (!link) {
        return;
    }
    if (link.indexOf("/portal/") >= 0) {
        link = link.replace("/portal/", "/myportal/");
        element.setAttribute("href", link);
    }
    
}

/* Replaces /myportal/ by /portal/ */
function fixMyPortal(element) {
    var link = element.getAttribute("href");
    if (!link) {
        return;
    }
    if (link.indexOf("/myportal/") >= 0) {
        link = link.replace("/myportal/", "/portal/");
        element.setAttribute("href", link);
    }
    
}

/* Adds target="_new" */
function fixExternal(el) {
    el.setAttribute("target", "_new");
}