function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      if (oldonload) {
        oldonload();
      }
      func();
    }
  }
}

// hacky, assumes oldonclick takes the event argument
// meet the almighty deadline and then consider the more general
// case...
// Can we introspect javascript functions and auto discover
// the expected arguments and then try to do the right thing?
function addOnClick(elem,func) {
  var oldonclick = elem.onclick;
  if (typeof elem.onclick != 'function') {
    elem.onclick = func;
  } else {
    elem.onclick = function(e) {
      if (oldonclick) {
        oldonclick(e);
      }
      func();
    }
  }

}


var mops = new Hash({'morphClear':0.8,'morphOpaque':1.0,'morphClearNoAuto':0.8,'morphOpaqueNoAuto':1.0});


// Handle fading in content and navigation panes on most pages.
// Don't load it here though or it will run in the wrong sequence.
function doFadeIns() 
{
    f = document.getElementsByClassName('morphClear')
    g = document.getElementsByClassName('morphOpaque')
    for(i=0;i<f.length;i++)
    {
        f[i].style.overflow='auto';
        f[i].morph('opacity: '+mops['morphClear'], {duration:2.0} );
    }
    for(i=0;i<g.length;i++)
    {
        g[i].style.overflow='auto';
        g[i].morph('opacity: '+mops['morphOpaque'],{duration:2.0});
    }

}

function doFadeOuts()
{
    f = document.getElementsByClassName('morphClear')
    g = document.getElementsByClassName('morphOpaque')
    h = document.getElementsByClassName('morphOpaqueNoAuto')
    for(i=0;i<f.length;i++) {
        f[i].style.overflow='hidden';
        f[i].morph('opacity: 0.0; display: none; ',{duration:2.0});
    }

    for(i=0;i<g.length;i++)
    {
        g[i].style.overflow='hidden';
        g[i].morph('opacity: 0.0; display: none; ',{duration:2.0});
    }
    for(i=0;i<h.length;i++)
    {
        h[i].style.overflow='hidden';
        h[i].morph('opacity: 0.0; display: none; ',{duration:2.0});
    }

}

// used to load content into the content
// pane on multiple pages
// TODO need to modify this to not clobber previous onclicks
// and possibly to not add an onclick function if it is already
// in place for an element
function bindContentPaneTriggers()
{
    for(i=0;i<cpTriggers.length;i++)
    {
       try {
       $(cpTriggers[i]).onclick=updatePaneContent;
       $(cpTriggers[i]).href='javascript:void(0)';
       }
    
       catch(e) {
       // alert(e.message) 
       
       };
    }
}

// retrieve pane content via ajax.  The tr_ prefix is needed
// because otherwise the page will scroll to the id of the trigger
// element which in this case is not what we want
function updatePaneContent(e)
{
    e= e ? e : window.event;
    var elem = Event.element(e)
    try {
        var tmp = elem.id.split('_');
        var nh = tmp[1];
    }
    catch(e)
    {
        var nh = elem.id;
        // alert(e.message)
    }
    location.href= cpBase + '#' + nh;
    paneContentById(nh)
}

// update an element with content.  
// If it isn't visible make it so. 
function paneContentById(id)
{
    id = id.replace('tr_','');


    $(cpPane).scrollTop=0;
    if( $(cpPane).style.opacity & $(cpPane).style.opacity < 0.4 )
        $(cpPane).morph('opacity: '+mops[$(cpPane).getClassName()], {duration:2.0} );

    new Ajax.Updater( cpPane, cpURL+id, {method:'get', evalScripts:true, queue:'end'});
    return;


    try {
    if( $(cpPane).style.opacity & $(cpPane).style.opacity < 0.4 )
    {
        $(cpPane).morph('opacity: 0.8', {duration:2.0});
    }
    }
    catch(e)
    {
        alert(e.message);

    }

    new Ajax.Updater( cpPane, cpURL+id, {method:'get', evalScripts:true, queue:'end'});

}

// if someone bookmarks and comes to a hashed page
// we want to do the right thing
function setCurrentTrigger()
{
    for(i=0;i<cpTriggers.length;i++)
    {
        if(location.hash == '#'+cpTriggers[i].replace('tr_',''))
        {
            paneContentById(cpTriggers[i]);
            return;
        }
    }

//    if($(cpPane).innerHTML.length > 100 )
//       $(cpPane).morph(mops[$(cpPane).className], {duration:2.0});
//    }
//    else 
//       $(cpPane).morph('opacity: 0.0', {duration:2.0});
}

function contactForm()
{

    new Ajax.Updater( 'contactForm', '/contact', {method:'get',evalScripts:true});
    $('contactForm').style.position='absolute';
    $('contactForm').style.display='block';
    $('contactForm').style.width='400px';
    $('contactForm').style.height='210px';
    $('contactForm').style.zIndex='1000000';

    var cd = $('contactForm').getDimensions();
    var bd = $('body').getDimensions();
    var top = (bd.height/4);
    var left = (bd.width/2)-(cd.width/2);

    $('contactForm').style.top=100+'px'
    $('contactForm').style.left=left+'px'

    new Effect.ScrollTo($('contactForm'));
    new Effect.Appear('contactForm',{opacity:'0.9',duration:1.2});
    $('contactEmail').onkeyup=checkComplete;
    $('contactEmail').onenter=function(){return false};
    $('contactMessage').onkeyup=checkComplete;
    checkComplete();
    $('submitButton').onclick=submitContactForm

}

function checkComplete(e)
{

    if( $('submitButton').visible() == false ) 
    {
        if( $('contactEmail').value.strip() != '' & $('contactMessage').value.strip() != '' )
            new Effect.Appear('submitButton',{duration:0.2});
    }
    else
    {
        if( $('contactEmail').value.strip() == '' | $('contactMessage').value.strip() == '' )
            new Effect.Fade('submitButton',{queue:'end',duration:0.2});
    }
}

function submitContactForm()
{

    form = Form.serialize('contact')
    var url='/contact?'+form;
    new Ajax.Updater('contactForm',url,{method:'post',evalScripts:true});

}


// If this throws an error then we won't have a
// functional email form
function setEmailActions()
{
    new Ajax.Updater( 'contactForm', '/contact', {method:'get',evalScripts:true});
    var walk = ['email','infoEmail','locEmail']

    for (i=0;i<walk.length;i++)
    {
        try {
            $(walk[i]).onclick=contactForm;
            $(walk[i]).href='javascript:void(0)';
        }
        catch(e)
        {
            // alert('setEmailActions, '+walk[i]+': '+e.message)
        }
    }


}

function dotLi()
{
    lists = document.getElementsByClassName('SubNav');
    if(lists.length)
    {
        for(i=0;i<lists.length;i++)
        {
           var children = $A(lists[i].getElementsByTagName('li'));
           for(j=0;j<children.length;j++)
           {
              if(children[j].hasClassName('arrow'))
                new Insertion.Top(children[j],'<img src="/images/arrow.gif" />&nbsp;');
              else
                new Insertion.Top(children[j],'<i>&curren;</i>');
           }
        }

    }
    lists = document.getElementsByClassName('SubNav2');
    if(lists.length)
    {
        for(i=0;i<lists.length;i++)
        {
           var children = $A(lists[i].getElementsByTagName('li'));
           for(j=0;j<children.length;j++)
           {
              if(children[j].hasClassName('arrow'))
                new Insertion.Top(children[j],'<img src="/images/arrow.gif" />&nbsp;');
              else
                new Insertion.Top(children[j],'<i>&curren;</i>');
           }
        }

    }

}

var gpx=0;
var gpy=0;
var gcount=120;
var gfaded=false
function monitorMouse()
{

    var noFade = new Array('newsletter','about');
    var section = location.pathname.split('/')
    if( noFade.indexOf(section[1]) >= 0 )
        return;

    var step = 5;
    $('mm').style.position='absolute';
    $('mm').style.top='10px';
    $('mm').style.right='10px';
    $('pageContainer').onmousemove=reportMouse;
    new PeriodicalExecuter(function(){

        if( gcount == 0 )
        {
            doFadeOuts();
            gfaded=true;
        }
        else
        {
            var gfaded=false;
            gcount-= step;
            // $('mm').innerHTML=   gpx+'.' + gpy + ' - ' + gcount;

        }

    },step)
}


var gpx=0;
var gpy=0;
function reportMouse(e)
{
   try {
   if(isNaN(gpx))
    var gpx=0;
   if(isNaN(gpy))
    var gpy=0;
   }catch(e)
   {
    gpx=0;
    gpy=0;
    // alert('reportMouse:'+e.message)
   }

   try {
    var evt = e? e : window.event;
    var currX=Event.pointerX(evt);
    var currY=Event.pointerY(evt);
   }catch(e)
   {
    // alert('reportMouse:'+e.message)
   }

    if(currX != gpx | currY != gpy )
    {
        gpx=currX;
        gpy=currY;
        if(gcount == 0)
        {
            gcount = 120; 
            doFadeIns();
        }
    }

}

addLoadEvent(dotLi);
addLoadEvent(setEmailActions)
addLoadEvent(monitorMouse);

