Event.observe(window, 'load', setupGlobalJs);

function setupGlobalJs(e)
{
	var daFoot=$('footerToTop');
	Event.observe(daFoot, 'click', scrollToTop);

	// Every page has a box at the top for showing session messages
	// Only style this div if it has content.
	if($('messageBox'))
	{
		if($('messageBox').down())
		{ $('messageBox').addClassName('hasContent'); }
	}
	
	
	// hide view by island box and make it toggle to open
	if( $('viewByIsland') )
	{
		$('viewByIsland').down('ul').style.display = 'none';
		$('viewByIsland').down().observe('click',toggleViewByIsle);
	}
	
	// focus listing id field in quicksearch
	// if ($('listing_id')) setfocus('listing_id');
	
	// focus listing id field in quicksearch IF it's not below the fold
	if ($('listing_id'))
	{
		vHeight = measureViewport().height;
		eOffset = findPos( $('listing_id') ).top;
		if(eOffset < vHeight){ setfocus('listing_id'); }
	}
	
	Event.stop(e);
}

function toggleViewByIsle(clickEvent)
{
  var list = clickEvent.target.next(); // should be a UL
  if( list.style.display == 'none' )
  {
    new Effect.BlindDown(list)
  } else {  new Effect.BlindUp(list) }
}


function scrollToTop(e)
{
	new Effect.ScrollTo('header', {offset: -24});
	Event.stop(e);
}

function setfocus(theField) {	$(theField).focus(); }


function measureViewport()
{
	// http://andylangton.co.uk/articles/javascript/get-viewport-size-javascript/
	var viewportwidth;
	var viewportheight;
 // the more standards compliant browsers (mozilla/netscape/opera/IE7) use window.innerWidth and window.innerHeight
 
 if (typeof window.innerWidth != 'undefined')
 {
      viewportwidth = window.innerWidth,
      viewportheight = window.innerHeight
 }
 
// IE6 in standards compliant mode (i.e. with a valid doctype as the first line in the document)

 else if (typeof document.documentElement != 'undefined'
     && typeof document.documentElement.clientWidth !=
     'undefined' && document.documentElement.clientWidth != 0)
 {
       viewportwidth = document.documentElement.clientWidth,
       viewportheight = document.documentElement.clientHeight
 }
 
 // older versions of IE
 
 else
 {
       viewportwidth = document.getElementsByTagName('body')[0].clientWidth,
       viewportheight = document.getElementsByTagName('body')[0].clientHeight
 }
 
 return {'width':viewportwidth,'height':viewportheight}
 
 }


function findPos(obj) 
{ //http://www.quirksmode.org/js/findpos.html
	var curleft = curtop = 0;
	if (obj.offsetParent) 
	{
		do
		{
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop;
		} while (obj = obj.offsetParent);

	}
	return {'left':curleft, 'top':curtop};
}