var W3CDOM = ( document.createElement && document.getElementsByTagName );

if( W3CDOM ) {
    Event.observe( window, 'load', setClearOnFocus, false );
    Event.observe( window, 'load', setLastModifiedDate );
    Event.observe( window, 'load', changeEmail );
    Event.observe( window, 'load', furnishExternals );
    Event.observe( window, 'load', addSomeStyle );
}

//
// This function will add a bit of styling in places
//
function addSomeStyle( e ) {
}


//
// This function will attach an event handler to any form element (input,
// textarea) with the 'clear' class. The event handler will be triggered 
// when the element receives focus
//
function setClearOnFocus() {
    // Add an onFocus event to any element with the 'clear' class
    document.getElementsByClassName( 'clear' ).each(
        function( e ) {
            Event.observe( e, 'focus', clearContents, false );
        }
    );
}


//
// This function will clear the contents of the element that it is attached
// to
//
function clearContents(e) {
    var element = Event.element( e );
    element.value = '';

    // Only perform the clear once
    Event.stopObserving( element, 'focus', clearContents, false );
}


//
// This function will change emails in the HTML to a proper mailto link. This
// is done to reduce the risk of spam agents picking up the email addresses
//
function changeEmail() {
    // Find and modify any email in the page
    document.getElementsByClassName( 'email' ).each(
        function( email ) {
            var spans = email.getElementsByTagName('span');
            if( spans.length == 2 ) {
                var address = spans[0].firstChild.nodeValue + '@' + spans[1].firstChild.nodeValue;
                Element.update( email, "<a href='mailto:" + address + "'>" + address + "</a>" );
            }
        }
    );
}

//
// This funciton will change the content of the container with the id
// 'lastModified' to be the date that the page was last modified
//
function setLastModifiedDate() {
    var lastMod = $('lastModified');
    if( lastMod ) {
        var d    = new Date( document.lastModified );
        var date = d.getDate() + " " + ( 1 + d.getMonth() ) + " " + d.getFullYear();
        Element.update( lastMod, date );
   }
}

//
// This function will check each link to determine if it is an internal link
// to another page in the site or if it is external. If external then
// add a span around the item with a class to indicate this
//
function furnishExternals()
{
    $A(document.getElementsByTagName('a')).each(
        function( anchor ) {
            if( anchor.href.indexOf('http://dewoollery') == -1 && anchor.href.indexOf('http://www.dewoollery') == -1 ) {
                new Insertion.After( anchor, '<span class="externalLink">&nbsp;</span>' );
            }
        }
    );
}
