/* main.js -- Main JavaScript starting point for the web page.  */

/*
 * Copyright (C) 2003-2011 Tudor Hulubei <tudor@hulubei.net>.
 * Distributed under the GNU General Public License.
 */


/* Global variables.  */
var g_hostName = 'hulubei.net';
var g_topDirectory = '/tudor';
var g_webSite = g_hostName + g_topDirectory;
var g_cookiePrefix = 'TudorHulubei';
var g_fontCookie = g_cookiePrefix + ':Font';
var g_schemeCookie = g_cookiePrefix + ':Scheme';
var g_mapCookie = g_cookiePrefix + ':Map';
var g_originalLanguage = 'en';
var g_expirationDate = null;
var g_pagePath = PagePath();
var g_imageNames = new Array();
var g_imageDirectories = new Array();
var g_imageStems = new Array();
var g_imageExtensions = new Array();


function PagePath()
{
    var url = location.href;

    /* We get called with `location.href' as either:

       http://hulubei.net/tudor/photography/Black&WhiteIndex.html

       or, in case of Google translations, something like:

       http://216.239.39.120/translate_c?\
           hl=en&ie=UTF-8&oe=UTF-8&langpair=en%7Cfr&\
           u=http://hulubei.net/tudor/photography/Black%26WhiteIndex.html&\
           prev=/language_tools

       In the first case, we want the part after /tudor, while in the second we want
       the part after /tudor but before the first &.  */

    var i = url.indexOf('?');

    if (i != -1)
    {
        var urlArguments = url.slice(i, url.length);
        var arguments = urlArguments.split('&');

        for (a = 0; a < arguments.length; a++)
        {
            /* FIXME: This is specific to Google.  */
            if (arguments[a].slice(0, 2) == 'u=')
            {
                url = arguments[a].split('=')[1];
                break;
            }
        }

        if (a == arguments.length)
            return '/';
    }

    i = url.indexOf(g_topDirectory) + g_topDirectory.length;
    return url.slice(i, url.length);
}


/* Substitute character string c2 for every c1 in aString.  */
function StringReplace(aString, c1, c2)
{
    if (aString == '')
        return aString;
    if (c1 == '')
        return aString;

    /* Avoid infinite recursion when substituting aa for a by
       providing an offset into the string.  */
    var argc = StringReplace.arguments.length;
    if (argc < 4) { n = 0; } else { n = StringReplace.arguments[3]; }

    /* Find the first occurrence of c1 after the threshold.  */
    var i = aString.indexOf(c1, n);

    /* Stop recursion and return the current string when c1 not found.  */
    if (i < 0)
        return aString;

    /* Extract substrings s1 and s2 around the c1.  */
    var s1 = aString.substring(0, i);
    var s2 = aString.substring(i + c1.length, aString.length);

    /* Recurse with this new string.  */
    return StringReplace(s1 + c2 + s2, c1, c2, (i + c2.length));
}


function FixWPMenuLinks()
{
    /* This ugly hack works around the fact that WordPress'
       get_archives() doesn't allow us to specify the class for the
       anchors.  This code adds the proper class (MenuLink) to any
       anchor enclosed in a span of class WPMenuLink and then removes
       the span.  */
    var menu = document.getElementById("Menu");

    if (!menu)
        return;

    var spans = menu.getElementsByTagName("span");
    for (var i = 0; i < spans.length;)
    {
        var span = spans[i];
        if (span.getAttribute("class") == "WPMenuLink" &&
            span.hasChildNodes())
        {
            var parent = span.parentNode;
            while (span.hasChildNodes())
            {
                var child = span.firstChild;
                if (child.nodeName == "A" || child.nodeName == "a")
                    child.setAttribute("class", "MenuLink");
                parent.appendChild(child);
            }
            parent.removeChild(span);
        }
        else
            i++;
    }
}


function OpenImageWindow(url, name, width, height)
{
    /* Make sure the `name' argument contains no spaces,
       dashes, dots or slashes, otherwise IE will complain.
       Use underscores instead.  Mozilla & Opera seem to
       work just fine without this, but...  */
    name = StringReplace(name, ' ', '_');
    name = StringReplace(name, '-', '_');
    name = StringReplace(name, '.', '_');
    name = StringReplace(name, '/', '_');

    height += 50;
    width += 20;

    /* No spaces in the property list either.  */
    var newWindow = window.open(
        url, name,
        "directories=no,location=no,toolbar=no," +
        "scrollbars=no,status=no,menubar=no,resizable=yes");
    newWindow.resizeTo(width, height);
}


function LoadImage(url, name, width, height)
{
    document.write('<a onclick="javascript:OpenImageWindow(\'' + url + '\', \'' + name);
    document.write('\', ' + width + ', ' + height + ');">' + name + '</a>'); /* No NL.  */
}


function SetExpirationDate()
{
    if (g_expirationDate)
        return;

    /* Create an instance of the Date object and set it so that
       cookies using it will expire in 10 years (10 * 365 days).  */
    g_expirationDate = new Date();
    g_expirationDate.setTime(
        g_expirationDate.getTime() + 10 * 365 * 24 * 60 * 60 * 1000);
}


function DefaultWindowStatus()
{
    return document.title;
}


function GenerateSpacer(before, after)
{
    var spacer = "";

    for (var i = 0; i < before; i++)
        spacer += "&nbsp;";

    spacer += "|";

    for (var i = 0; i < after; i++)
        spacer += "&nbsp;";

    document.write(spacer);
}


function GenerateSearchBox(name, title)
{
    if (is_nav && !is_nav5up)
    {
        /* Netscape 4.7x displays the ugliest box ever...
           We bravely sacrifice functionality for aesthetics.  */
        return;
    }

    var textColor = "white";
    var linkColor = "#80c8ff";
    var visitedLinkColor = "#6096c0";
    var activeLinkColor = "#ff4400";
    var backgroundColor = "#606067";

    document.write('<div class="' + name + '">');

    if (title)
        document.write(title);

    document.write('<form method="get" name="search" style="display: inline; margin: 0; border: 0; padding: 0;" action="http://www.google.com/custom">');
    document.write('<input style="display: inline; margin: 0; border: 0; padding: 0;" type=\'hidden\' name=\'domains\' value=\'' + g_hostName + '\'/>');
    document.write('<input style="display: inline; margin: 0; border: 0; padding: 0;" type=\'hidden\' name=\'client\' value=\'pub-4036224197250044\'/>');
    document.write('<input style="display: inline; margin: 0; border: 0; padding: 0;" type=\'hidden\' name=\'forid\' value=\'1\'/>');
    document.write('<input style="display: inline; margin: 0; border: 0; padding: 0;" type=\'hidden\' name=\'channel\' value=\'9598769365\'/>');
    document.write('<input style="display: inline; margin: 0; border: 0; padding: 0;" type=\'hidden\' name=\'ie\' value=\'ISO-8859-1\'/>');
    document.write('<input style="display: inline; margin: 0; border: 0; padding: 0;" type=\'hidden\' name=\'oe\' value=\'ISO-8859-1\'/>');
    document.write('<input style="display: inline; margin: 0; border: 0; padding: 0;" type=\'hidden\' name=\'hl\' value=\'en\'/>');
    document.write('<input style="display: inline; margin: 0; border: 0; padding: 0;" type=\'hidden\' name=\'cof\' value=\'');
    document.write('L:http://' + g_webSite + '/graphics/heading.jpg;');
    document.write('LH:75;LW:450;GL:1;FORID:1;DIV:#336699;');
    document.write('BIMG:http://' + g_webSite + '/graphics/background-' + backgroundColor + '.jpg;');
    document.write('BGC:' + backgroundColor + ';T:' + textColor + ';LC:' + linkColor + ';VLC:' + visitedLinkColor + ';ALC:' + activeLinkColor + ';');
    document.write('GALT:#bbbbbb;GFNT:gray;GIMP:red;AH:center;S:http://' + g_hostName + '/;\'/>');

    document.write('<input class="' + name + '" type="text\"name="q"');
    document.write('       maxlength="255" value="Search"');
    document.write('       onclick="javascript:ClearSearchForm(this.form); return true;"');
    document.write('       onblur="javascript:ResetSearchForm(this.form); return true;"/>');

    document.write('<input type=\'hidden\' name=\'sitesearch\' value=\'' + g_hostName + '\'/>');

    document.write('</form>');
    document.write('</div>\n');
}


function GeneratePlusOneButton()
{
    document.write('<g:plusone></g:plusone>');    
}


function ClearSearchForm(form)
{
    form.q.value = "";
}


function ResetSearchForm(form)
{
    if (form.q.value == "")
        form.q.value = "Search";
}


function DiscardAlienFrames()
{
    /* If this document has been loaded inside a frameset, make this
       the only frame.  Useful for getting rid of the ugly frame
       inserted by Google's online translation software.  */
    if (self != top)
    {
        /* FIXME: Konqueror and IE on Mac OS X fail to reload the
           frame.  No clue why.  */
        if (document.images)
            top.location.replace(location.href);
        else
            top.location.href = location.href;
    }
}


function AddImage(name, directory, stem, extension)
{
    /* Record the image's parameters.  */
    var i = g_imageNames.length;
    g_imageNames[i] = name;
    g_imageDirectories[i] = directory;
    g_imageStems[i] = stem;
    g_imageExtensions[i] = extension;
}


function GetAllStyleSheets()
{
    if (!window.ScriptEngine && navigator.__ice_version)
    {
        return document.styleSheets;
    }

    if (document.getElementsByTagName)
    {
        var Lt = document.getElementsByTagName('link'),
            St = document.getElementsByTagName('style');
    }
    else if (document.styleSheets && document.all)
    {
        var Lt = document.all.tags('LINK'),
            St = document.all.tags('STYLE');
    }
    else
    {
        return [];
    }

    for (var x = 0, os = []; Lt[x]; x++)
    {
        var rel = Lt[x].rel ? Lt[x].rel : Lt[x].getAttribute ? Lt[x].getAttribute('rel') : '';
        if (typeof(rel) == 'string' && rel.toLowerCase().indexOf('style') + 1)
            os[os.length] = Lt[x];
    }

    for (var x = 0; St[x]; x++)
        os[os.length] = St[x];

    return os;
}


function GenerateImage(name, directory, stem, extension, title, width, height)
{
    if (is_nav4)
        return;

    var image = directory + '/' + stem + '.' + extension;

    document.write(
        '<img src=\'' + image +
        '\' name=\'' + stem +
        '\' width=\'' + width +
        '\' height=\'' + height +
        '\' alt=\'' + title +
        '\' title=\'' + title + '\'/>\n');

    AddImage(name, directory, stem, extension);
}


function SetAnchorTargets()
{
    /* Make sure the browser is up to the task.  */
    if (!document.getElementsByTagName)
        return;

    /* Get all the links in the document.  */
    var anchors = document.getElementsByTagName("a");

    /* XHTML doesn't support the tag attribute.  Instead, we use
       rel="external-*" to denote the fact that we want the tag to be
       loaded in a new window, whose name would be the text after
       "external-".  */
    for (var i = 0; i < anchors.length; i++)
    {
        var anchor = anchors[i];

        /* Obtain the value of the target from the "rel" attribute.  */
        if (anchor.getAttribute("href"))
        {
            var rel = anchor.getAttribute("rel");
            if (rel && (rel.substring(0, 9) == "external-"))
                anchor.target = rel.substring(9, rel.length);
        }
    }
}


function RestorePreAutoFillStyles()
{
    if(event.srcElement.style.backgroundColor != "" &&
       event.srcElement.style.backgroundColor != "#a0d0ff")
    {
        /* Color of choice for Google Toolbar's AutoFill.  */
        event.srcElement.style.backgroundColor = "red";
        event.srcElement.style.color = "black";
    }
}


function FixGoogleToolbarAutoFill()
{
    inputList = document.getElementsByTagName("INPUT");
    for (var i = 0; i < inputList.length; i++)
    {
        if (is_ie)
            inputList[i].attachEvent(
                "onpropertychange", RestorePreAutoFillStyles);
        else
            inputList[i].addEventListener(
                "onpropertychange", RestorePreAutoFillStyles, false);
        inputList[i].style.backgroundColor = "";
    }

    selectList = document.getElementsByTagName("SELECT");
    for (var i = 0; i < selectList.length; i++)
    {
        if (is_ie)
            selectList[i].attachEvent(
                "onpropertychange", RestorePreAutoFillStyles);
        else
            selectList[i].addEventListener(
                "onpropertychange", RestorePreAutoFillStyles, false);
        selectList[i].style.backgroundColor = "";
    }
}


function main()
{
    if (is_nav4)
        return null;

    window.onresize = function() { main(); }

    SetAnchorTargets();
    FixWPMenuLinks();
    FixGoogleToolbarAutoFill();
    SetExpirationDate();
    DiscardAlienFrames();

    window.status = DefaultWindowStatus();
    return true;
}


/* Run this first!  */
DiscardAlienFrames();

/* We need this for cookies.  */
SetExpirationDate();

/* Local Variables: */
/* mode: C++ */
/* End: */

