// paths
var headerImageDir = "http://www.x-client.com/v/5.5/images/headerBar/";
if (window.isc_useS3) headerImageDir = "http://s3.amazonaws.com/isc/5.5/wwwImages/headerBar/";
// keep ssl URL in production 
if (location.protocol == "https:") headerImageDir = "/images/headerBar/";

var headerBlogURL = "http://blog.smartclient.com/";

//>NeverShip
if (!window.isc_useS3) headerImageDir = "/images/headerBar/";
//<NeverShip

var defaultImageDir = "text/",
    px60ImageDir = "60/",
    overImageDir = "over/"
;

// when on isomorphic.com (shopping cart) link back to smartclient.com
var hostURL = "";
if (window.location.hostname.indexOf("isomorphic.com") != -1) {
    if (window.location.hostname.indexOf("wrath") == -1) {
        // production
        hostURL = "http://www.smartclient.com";
    } else {
        hostURL = "http://wrath.smartclient.com:" + window.location.port;
    }
}


var blankImgUrl = headerImageDir+"blank.gif"

// browser information
var isOpera = (navigator.appName == "Opera" || navigator.userAgent.indexOf("Opera") != -1),
    isNS = (navigator.appName == "Netscape" && !isOpera),
    isMoz = navigator.userAgent.indexOf("Gecko/") != -1,
    isIE = (navigator.appName == "Microsoft Internet Explorer" && !isOpera),
    _geckoVIndex = navigator.userAgent.indexOf("Gecko/") + 6,
    geckoVersion = parseInt(navigator.userAgent.substring(_geckoVIndex, _geckoVIndex+8)),
    leaveScrollbarGap = isMoz && geckoVersion < 20051107,
    isNS6 = isNS && navigator.userAgent.indexOf("Netscape6") != -1,
    isStrict = (document.compatMode == "CSS1Compat") || isNS6
;
var pngRegistry = [];

function IEPngImgStyle(imageUrl) {
    return "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\"" + imageUrl +
           "\",sizingMethod=\"scale\");";
}

// draw the header gradient
document.write("<img id='header_gradient' src='" + headerImageDir + "header_gradient.png' " +
               "width='100%' height='68' align='TEXTTOP' border='0' suppress='TRUE'/>");

var headerImages = [
    {
        linkUrl : hostURL + "/",
        imageUrl : headerImageDir + "header_logo.png",
        width:230,
        height:68
    },
    {
        type:"spacer",
        width:"40%"
    },
    {
        linkUrl : hostURL + "/company/news.jsp",
        filename : "news.png",
        width:46,
        height:42
    },
    {
        type:"spacer",
        width:7
    },
    {
        linkUrl : hostURL + "/technology/index.jsp",
        contextRegexp : /^\/technology\//,
        filename : "overview.png",
        width:46,
        height:42
    },
    {
        type:"spacer",
        width:14
    },
    {
        linkUrl : hostURL + "/featureExplorer.jsp",
        filename : "demos.png",
        width:46,
        height:42
    },
    {
        type:"spacer",
        width:12
    },
    {
        linkUrl : headerForumsURL,
        filename : "forums.png",
        width:46,
        height:42
    },
    {
        type:"spacer",
        width:10
    },
    {
        linkUrl : headerBlogURL,
        filename : "blog.png",
        width:46,
        height:42
    },
    {
        type:"spacer",
        width:10
    },
    {
        linkUrl : hostURL + "/product/documentation.jsp",
        filename : "docs.png",
        width:46,
        height:42
    },
    {
        type:"spacer",
        width:12
    },
    {
        linkUrl : hostURL + "/product/index.jsp",
        contextRegexp : /^\/product\//,
        ignoreRegexp : /documentation.jsp/,
        filename : "product.png",
        width:46,
        height:42
    },
    {   
        type:"spacer",
        width:12
    },
    {
        linkUrl : hostURL + "/services/index.jsp",
        contextRegexp : /^\/services\//,
        filename : "services.png",
        width:46,
        height:42
    },
    {
        type:"spacer",
        width:"60%"
    },
    {
        linkUrl : hostURL + "/company/index.jsp",
        contextRegexp : /^\/company\//,
        filename : "company.png",
        width:46,
        height:42
    },
    {
        type:"spacer",
        width:10
    },
    {
        linkUrl : hostURL + "/devlogin/login.jsp",
        filename : "login.png",
        width:46,
        height:42,
        hide:authenticated
    },
    {
        linkUrl : hostURL + "/logout.jsp",
        filename : "logout.png",
        width:46,
        height:42,
        hide:!authenticated
    }
];

var baseImages = {},
    overImages = {}
;

for (var i = 0; i < headerImages.length; i++) {
    var img = headerImages[i],
        imageUrl = img.imageUrl,
        linkUrl = img.linkUrl;
        filename = img.filename,
        showRollover = false,
        contextRegexp = img.contextRegexp,
        ignoreRegexp = img.ignoreRegexp;
    ;
    
    if (linkUrl && window.headerBaseURL) {
        // not absolute and not a JS url
        if(!linkUrl.match(/http(s?):\/\//) && !linkUrl.indexOf("javascript:") == 0) {
            linkUrl = headerBaseURL + (linkUrl.indexOf("/") == 0 ? "" : "/") + img.linkUrl;
        }
    }

    // sidebar navigation changes the url, so to see which top-level image we should enlarge,
    // check a special reged that's supplied on the image.
    //
    // we have the cheesy ignoreRegexp to mask out URLs we don't want.  We want, for example,
    // /product/ to enlarge the product image, but for /product/documentation.jsp, it should be
    // the docs image.  This is just a quick hack.
    //
    // Also hack the feature explorer: if we arrive at a page with a marker (location.hash)
    // set.  Technically FE icon should enlarge dynamically when FE is shown from the home
    // page, but this creates a lurch.
    if ((contextRegexp && document.location.pathname.match(contextRegexp)
        && (ignoreRegexp ? !document.location.pathname.match(ignoreRegexp) : true)) ||
        (img.filename == "demos.png" && 
         (document.location.hash && !document.location.href.indexOf("whysmart"))) ||
        // bust out the big forums image when on the forums
        (linkUrl == headerForumsURL && location.href.indexOf(headerForumsURL) == 0))
    {
        img.width = img.height = 60;
        imageUrl = headerImageDir + px60ImageDir + img.filename;
    }

    if (img.hide) {
        img.type = "spacer";
        img.width = 0;
        continue;
    }
    if (linkUrl) {
        if (img.click) {
            linkUrl += "' onClick='" + img.click;
        }
        if (img.linkUrl != "/" && endsWith(document.location.pathname, img.linkUrl)) {
            img.width = img.height = 60;
            imageUrl = headerImageDir + px60ImageDir + filename;
        }
    }

    // in prod, we have a special iscBaseURL that we set in the forums headers that we must
    // prefix to all links except the forums link because prod has virtual hosts defined, so to
    // get to website content, we need to request as www.smartclient.com instead of
    // forums.smartclient.com
    if (window.iscBaseURL && linkUrl != headerForumsURL && linkUrl != headerBlogURL) {
        linkUrl = window.iscBaseURL+linkUrl;
    }

    if (imageUrl == null && filename == null) continue;
    if (imageUrl == null) {
        // initialize the images
        baseImages[i] = new Image();
        overImages[i] = new Image();
        imageUrl = headerImageDir + defaultImageDir + filename;
        if (isIE) {
            baseImages[i].src = blankImgUrl;
            baseImages[i].style.cssText = IEPngImgStyle(imageUrl);
            overImages[i].src = blankImgUrl;
            overImages[i].style.cssText = IEPngImgStyle(headerImageDir + overImageDir + filename);
        } else {
            baseImages[i].src = imageUrl;
            overImages[i].src = headerImageDir + overImageDir + filename;
        }
        showRollover = true;
    }
    img.handle =
        writeHeaderImage(imageUrl, linkUrl, img.width, img.height, i, showRollover);
}

function applyFilters() {
    if (!isIE || !pngRegistry) return;
    for (var i = 0; i < pngRegistry.length; i++) {
        var png = pngRegistry[i];
        var e = document.getElementById(png.id);
        e.style.cssText = IEPngImgStyle(png.url);
    }
    pngRegistry = null;
}

function writeHeaderImage(imageUrl, linkUrl, width, height, id, showRollover, suppressDiv) {

    pngRegistry[pngRegistry.length] = {
        id: "img_"+id,
        url: imageUrl
    };

    var rollover =
        showRollover ? "' onmouseover='over(\"" + id + "\")' onmouseout='out(\"" + id + "\")" : "";
        imageUrl = isIE ? blankImgUrl : imageUrl;

    var showFE = linkUrl.match(/featureExplorer.jsp/);

    document.write(
        (!suppressDiv ?
               "<DIV class='headerImage' id='_" + id + 
               "' style='position:absolute; top:-100px; left:-100px;'>" : "") +
                   "<A href='" + linkUrl + rollover + "' "
                   + (showFE ? "onclick='showFeatures();return false;'" : "") + ">" +
                   "<IMG src='" + imageUrl + "' width=" + width + " height=" + height +
                   " id='img_" + id + "'></A>" +
        (!suppressDiv ? "</DIV>" : ""));
    return document.getElementById("_" + id);
}

// copied from isc.endsWith
function endsWith(string1, substring) {
    if (string1 == null) return false;

    var startPos = string1.length - substring.length;
    if (startPos < 0) return false; // substring longer than main string
    return (string1.indexOf(substring, startPos) == startPos);
}

var headerHeight = 68;

function layoutHeaderImages() {
    var remainingSpace = getPageWidth() - 20;
    var percentSizes = {};
    for (var i = 0; i < headerImages.length; i++) {
        var img = headerImages[i];

        var width = img.width;
        if (typeof width == "string" && width.indexOf('%') != -1) {
            percentSizes[i] = parseInt(width.slice(0, -1));
        } else {
            remainingSpace -= width;
        }
    }

    // don't go under the minimum width of the header images
    if (remainingSpace < 0) {
        for (var i in percentSizes) {
            percentSizes[i] = 0;
        }
    } else {
        var totalPercent = 0;
        for (var i in percentSizes) {
            totalPercent += percentSizes[i];
        }
        for (var i in percentSizes) {
            percentSizes[i] = Math.floor(percentSizes[i] * remainingSpace / totalPercent);
        }
    }

    
    var pos = 10;
    for(var i = 0; i < headerImages.length; i++) {
        var img = headerImages[i],
            width = parseInt(img.width)
        ;
        if (img.type == "spacer") {
            pos += (typeof img.width == "string" ? percentSizes[i] : width);
            continue;
        }
        var top = (headerHeight - img.height) / 2;
        img.handle.style.left = pos + "px";
        img.handle.style.top = top + "px";
        pos += width;
    }
    
    // adjust the header gradient width in case page was resized
    //>IDocument not necessary, header gradient reflows automatically in IE, Moz, Safari.
    // However if it is ever necessary, this calculation needs to take into account any
    // extra pixel left behind by rounding when allocating percent space //<IDocument
    //document.getElementById('header_gradient').width = pos + 10;
}

function getPageWidth() {
    if (isNS) {
        if (isMoz) {
            if (leaveScrollbarGap) {
                if (window.innerWidth != null) return window.innerWidth - 16;
                else return 500;
            } else return document.body.clientWidth;
        }
        return window.innerWidth;
    } else {
        var wd = window,
            documentBody = wd.document.body
        ;
        if (isStrict) documentBody = wd.document.documentElement;
        
        if (documentBody) {
            return documentBody.clientWidth;
        }
        return 500;
    }
}

function over(id) {
    var img = document.getElementById("img_"+id);
    if (isIE) {
        img.style.cssText = overImages[id].style.cssText;
    } else {
        img.src = overImages[id].src;
    }
}

function out(id) {
    var img = document.getElementById("img_"+id);
    if (isIE) {
        img.style.cssText = baseImages[id].style.cssText;
    } else {
        img.src = baseImages[id].src;
    }
}

function showFeatures() {
    // if already on the home page, just show the FE
    if (window.showTestDrive) {
        showTestDrive();
    } else {
        // jump to home page and show the FE
        // NOTE: in devenv, headerBaseURL is derived from the current host by a .jsp and set up
        // as a global variable and as a cookie.  The cookie enables the forums to correctly
        // link back to devenv hosts. 
        window.location.href = (window.headerBaseURL ? 
                                window.headerBaseURL : 
                                // NOTE: avoid domain switching, since we preserve
                                // smartclient.com
                                (window.location.href.indexOf("www.smartclient") != -1 ?
                                 "http://www.smartclient.com" : "http://smartclient.com"))
                + "/featureExplorer.jsp";
    }
}

window.onresize = layoutHeaderImages;

function delayedLayout() {
    layoutHeaderImages() // NOTE: needed or header flashes visibly after load
    // also do delayed layout, as workaround for delayed reporting of correct page size when a
    // scrollbar is introduced?
    applyFilters();
    setTimeout("layoutHeaderImages()", 100); 
}

// do initial layout so the headerBar images at least show up before pageLoad fires
layoutHeaderImages();

// preserve body onload handler
if (isIE) window.attachEvent("onload", delayedLayout);
else window.addEventListener("load", delayedLayout, true);

