/*-------------
GLOBALS
-------------*/

//shortcut aliases-----------
var YUD = YAHOO.util.Dom;
var $ = YUD.get;
var $$ = YUD.getElementsByClassName;

var YUE = YAHOO.util.Event;

var MOUSEX;
var	MOUSEY;

//---------------------------

//=======preloads for header=======
YUE.onAvailable('container',commonPreload);

function commonPreload()
{
//	YUD.addClass(YUD.getElementsByClassName('hidefirst'), 'hide'); <--moved to page footer to speed it up
	
	YUE.addListener($('togglesearch'), 'click', toggleSearchBox);
	YUE.addListener($('togglelogin'), 'click', toggleLoginBox);
	YUE.addListener(document, 'mousemove', setMousePositions);//always know where mouse is
    
    YUE.addListener($$('confirmdelete'), 'click', displayDeleteConfirm);
    
    wireUpClearLoginBoxes();

	
	linkTextBoxToButton('tbSearch', 'btnSearch');
	linkTextBoxToButton('tbLogin', 'btnLogin');
	linkTextBoxToButton('tbPwd', 'btnLogin');




    //DEBUG:
//    YUE.addListener($('aspnetForm'),'submit',function(e){alert(e); });
    //YUE.addListener($('btnSearch'),'click',function(e){alert(YUE.getTarget(e).id);YUE.stopEvent(e); /* YUE.alert(YUE.getTarget(e));alert('search');*/});
//    YUE.addListener($('btnLogin'),'click',function(e){alert('login');/*YUE.stopEvent(e); YUE.alert(YUE.getTarget(e));*/});

}


//TOP LOGIN BOXES MGT-----------------------------------------
function wireUpClearLoginBoxes()
{
    YUE.addListener($('tbLogin'),'focus',clearLoginBox);
    YUE.addListener($('tbPwd'),'focus',clearPwdBox);
    YUE.addListener($('tbLogin'),'blur',resetLoginBox);
    YUE.addListener($('tbPwd'),'blur',resetPwdBox);    
}

function clearLoginBox()
{
    if (this.value == 'email address')
        this.value = '';
}

function clearPwdBox()
{
    if (this.value == 'password')
    this.value = '';
    
    // cater to IE's stupid read-only rule for setting attributes
    var element;
    
    if (document.all) //ugly browser sniff
    {
        element = document.createElement("<input type='password' class='txtfield' id='tbPwd' name='tbPwd' />");
        this.parentNode.replaceChild(element,this);
        $('tbPwd').focus();
        $('tbPwd').focus(); //yup, gotta be twice
        YUE.addListener($('tbPwd'),'blur',resetPwdBox); //cuz the old one is dead/gone
	    linkTextBoxToButton('tbPwd', 'btnLogin'); //cuz the old one is dead/gone
    } 
    else //FF et al.
    {
        this.setAttribute('type', 'password');
    }
}

function resetLoginBox()
{
    if (this.value == '')
    this.value = 'email address';
}

function resetPwdBox()
{
    if (this.value == '')
        this.value = 'password';

    if (document.all) //ugly browser sniff
    {
        var element;
        if (this.value != 'password')
            var element = document.createElement("<input type='password' class='txtfield' id='tbPwd' name='tbPwd' value='" + this.value +"' />");
        else
            var element = document.createElement("<input type='text' class='txtfield' id='tbPwd' name='tbPwd' value='password' />");

        this.parentNode.replaceChild(element,this);
        YUE.addListener($('tbPwd'),'focus',clearPwdBox); //cuz the old one is dead/gone
	    linkTextBoxToButton('tbPwd', 'btnLogin'); //cuz the old one is dead/gone
    } 
    else //FF et al.
    {
        this.setAttribute('type', 'password');
    }
            
}

function writeEmail(s,e)
{
    document.write("<a class=emailme href='mailto:" + s + "%40" + e + "'> <img src='/images/emailme.gif' />  </a>");
}

//---------------------------------------------------------------


//called by pages that need it
function wireUpWhatsATagClick()
{
    YUE.on($$('whatsatag'),'click',listenerWireUpWhatsATagClick);
}

function listenerWireUpWhatsATagClick(e)
{
	var el = this.nextSibling;
	var i = 0;

	while (i < 5)//it should be within 5 siblings (with defined classses), if not, we bail as a failsafe
	{
	
	   //back up the tree and hunt from there
	   if (el == null)
	   {
            el = this.parentNode;
	   }
	   
	    while (typeof(el.className) == 'undefined')//cuz hasClass chokes on undefineds.
	    {
	        el = el.nextSibling;
	    }
	
	    
	    if (YUD.hasClass(el,'tagdescription'))
	    {
	        toggleBlind(el);
	        break;
	    }
	    else
	        el = el.nextSibling;
	    
	    i++;
	}
	
	YUE.stopEvent(e);
}

function toggleSearchBox(e)
{		
	hide('toploginbox');
	toggleBlind('topsearchbox');
	YUE.preventDefault(e);
}

function toggleLoginBox(e)
{
	hide('topsearchbox');
	toggleBlind('toploginbox');
	YUE.preventDefault(e);
}
//=============================

/*-------------
Utilities
---------------*/

function displayDeleteConfirm(e)
{
        if (!confirm("Are you sure you want to delete that?"))
            YUE.stopEvent(e);
}

//link text box with button so user can hit enter to "click" the button
function linkTextBoxToButton(textbox, button)
{
	YUE.addListener(textbox,'keydown',listenerLinkTextBoxToButton, button);
}

function listenerLinkTextBoxToButton(e, btn)
{
    if (e.keyCode == 13)
    {
//        console.log(e);
//        console.log($(btn));
        YUE.stopEvent(e);
//    alert('start handler');
//        YUE.preventDefault(e);
//        YUE.stopPropagation(e);
//        console.log(YUE.getTarget(e));
//        console.log(e);
//        console.log($(btn));
       $(btn).click();
        //YUE.stopEvent(e); 
//    alert('end handler');       
    }
}

function hide(id)
{
//	slideUp(id,parseInt(YUD.getStyle(id,'height')),0);
	
	if (!YUD.hasClass($(id), 'hide'))
		YUD.addClass($(id),'hide');	
}

function show(id)
{
	if (YUD.hasClass($(id), 'hide'))
		YUD.removeClass($(id), 'hide'); 	
}

function toggleHide(id)
{
	if (YUD.hasClass($(id), 'hide'))
		show(id);
	else
		hide(id);
}

function blindDown(el, start, finish)
{
	show(el);
		
	var h = $(el).offsetHeight;
		
    h = h - (isNaN(parseInt(YUD.getStyle(el,'padding-top'))) ? 0 : parseInt(YUD.getStyle(el,'padding-top')));
    h = h - (isNaN(parseInt(YUD.getStyle(el,'padding-bottom'))) ? 0 : parseInt(YUD.getStyle(el,'padding-bottom')));  
    h = h - (isNaN(parseInt(YUD.getStyle(el,'border-top-width'))) ? 0 : parseInt(YUD.getStyle(el,'border-top-width')));
    h = h - (isNaN(parseInt(YUD.getStyle(el,'border-bottom-width'))) ? 0 : parseInt(YUD.getStyle(el,'border-bottom-width')));
				
    $(el).style.height = '0';
    
    var anim = new YAHOO.util.Anim(el, 
    {height: { from:0, to:h } }, 
    0.5, YAHOO.util.Easing.easeOutStrong);
   
   anim.animate();
   
   
    //without this, the element has a fixed height that can't be manipulated naturally 
    //for example if something within it were to grow, it (as the containers) would stay fixed.
   setTimeout('this.resetHeight()',1000);
   this.resetHeight = function()
   {
       $(el).style.height = 'auto';
   }
}

function blindUp(el, start, finish)
{//not working correctly - not sure I want it anyway.

//    var h = $(el).offsetHeight;
//            
//    var anim = new YAHOO.util.Anim(el, 
//    {height: { from:h, to:0 } }, 
//    0.5, YAHOO.util.Easing.easeNone);
//  
//    anim.animate();

//   //read it for the blindDown
   hide(el);
   
//   setTimeout('this.resetHeight()',1000);
//   this.resetHeight = function()
//   {
//       $(el).style.height = 'auto';
//   }
//   $(el).style.height = h + "px";

}

function toggleBlind(id, top, bottom)
{
	if (YUD.hasClass($(id), 'hide'))
		blindDown(id);
	else
		blindUp(id);
}

function toggleFade(el)
{
	if (YUD.hasClass($(el), 'hide'))
		fadeIn(el);
	else
		fadeOut(el);
}

function fadeOut(el)
{
    var anim = new YAHOO.util.Anim(el, 
    {opacity: { to:0 } }, 
    0.5, YAHOO.util.Easing.easeOutStrong);
   
    anim.animate();

   setTimeout('this.hideit()',500);
   this.hideit = function()
   {
       hide(el);
   }
    
}

//because IE breaks cleartype with opacity changes, I'm creating an element
//laying it exactly over the top of the element to be faded, then fading it OUT
//giving the illusion of fading IN the element in question. 
function fadeIn(el, preFadeColor)
{        
    show(el);

    var region = YUD.getRegion(el);
    
    var overlay = document.createElement('div');

    YUD.setStyle(overlay,'position','absolute');
    YUD.setStyle(overlay,'z-index','10000');
    YUD.setStyle(overlay,'background-color', preFadeColor ? preFadeColor : '#fff'); 

    //width
    var width = parseInt(region.right) - parseInt(region.left);
    YUD.setStyle(overlay,'width', width + "px"); 

    //height
    var height = parseInt(region.bottom) - parseInt(region.top);
    YUD.setStyle(overlay,'height',height + 'px');

    YUD.setStyle(overlay,'top',region.top + 'px'); 
    YUD.setStyle(overlay,'left',(region.left -2) + 'px');//-2 for IE, in FF it's now 2px wider   

    var parent = YUD.get(el).parentNode;
    parent.appendChild(overlay);

    var anim = new YAHOO.util.Anim(overlay, 
    {opacity: {from:1, to:0 } }, 
    0.5, YAHOO.util.Easing.easeOutStrong);

    anim.animate();

    setTimeout('this.nukeOverlay()',750);

    this.nukeOverlay = function() {parent.removeChild(overlay); }
}


//MARGINALLY FUNCTIONAL, NOT BEING USED ANYWHERE AT PRESENT
//function toggleSlide(el)
//{
//	if (YUD.hasClass($(el), 'hide'))
//		slideIn(el);
//	else
//		slideOut(el);
//}

//function slideOut(el)
//{
//   setTimeout('this.showit()',500);
//   this.showit = function()
//   {
//       show(el);
//   }

//    var anim = new YAHOO.util.Anim(el, 
//    {width: { from:0} }, 
//    0.5, YAHOO.util.Easing.easeOutStrong);
//   
//    anim.animate();    
//}

//function slideIn(el)
//{    
//    var anim = new YAHOO.util.Anim(el, 
//    {width: { to:1 } }, 
//    0.5, YAHOO.util.Easing.easeBounceBoth);
//   
//    anim.animate();

//   setTimeout('this.hideit()',500);
//   this.hideit = function()
//   {
//       hide(el);
//   }
//        
//}


//assumptions: these will be triggered by mouseover/mouseout events and you don't want to hide 
//it if the mouse is over the containing element.
//Also, the "hideAllInvisFirsts()" call makes sure only one invisfirst item will be visible at a time - essentially nuking the delay 
//once you move  to another item
function toggleVisibility(id, el) //id=string or element, el=the original element that is the subject of the event
{	
	if (YUD.hasClass($(id), 'invisible'))
	{	
		hideAllInvisFirsts();
		YUD.removeClass($(id), 'invisible');
	}

/*		Detect the position of the mouse, and the region of the element, if the mouse is
		over the element, don't make it invisble. This should keep the delay from happening 
		if the person moved back onto (or is still on) the element.
*/		
	else
	{		
		this.invisibilize = function invisibilize()
		{
			if (!YUD.hasClass($(id), 'invisible') && !mouseIsOverElement($(el)))
				YUD.addClass($(id),'invisible');
		}
		this.timeoutID = window.setTimeout(this.invisibilize,500);
	}
}


function hideAllInvisFirsts()
{
	var invisFirsts = YUD.getElementsByClassName('invisfirst')

	for (var i = 0; i<invisFirsts.length; i++)
	{
		if (!YUD.hasClass(invisFirsts[i], 'invisible'))
			YUD.addClass(invisFirsts[i],'invisible');
	}
}

//assumptions: the closest DIV is the top container we'll want to find
function findContainer(el, containerCssClass)
{
	var currentNode = el;
		
	while (!YUD.hasClass(currentNode,containerCssClass))// && i < 10);
	{
		currentNode = currentNode.parentNode;
		//console.log(currentNode);

		//failsafe
		if (currentNode.parentNode.nodeName == 'HTML')//went all the way up, bail
			return el;
	}
			
	return currentNode;
}

function removeElement(el)
{
	el.parentNode.removeChild(el);
}

// Removes leading whitespaces
function lTrim(value) 
{	
	var re = /\s*((\S+\s*)*)/;
	return value.replace(re, "$1");
}

// Removes ending whitespaces
function rTrim(value) 
{	
	var re = /((\s*\S+)*)\s*/;
	return value.replace(re, "$1");	
}

// Removes leading and ending whitespaces
function trim(value) 
{
	return lTrim(rTrim(value));	
}

String.prototype.trim = function () 
{
    return this.replace( /^\s*(\S*(\s+\S+)*)\s*$/, "$1");
}

/*------------------
MOUSE MANAGER
-------------------*/

function mouseIsOverElement(el)
{
	var breathingRoom = 20;
	
	
	if(el)//it exists
	{
		var region = YUD.getRegion(el);
		

/*	console.log("top:" + (region.top-breathingRoom));
	console.log("bottom:" + (region.bottom+breathingRoom));
	console.log("right: " + (region.right+breathingRoom));
	console.log("left: " + (region.left-breathingRoom));
	
	console.log("x: " + MOUSEX);
	console.log("y: " + MOUSEY);
*/
		
		return (MOUSEY > region.top-breathingRoom 
				&& MOUSEY < region.bottom+breathingRoom 
				&& MOUSEX < region.right+breathingRoom 
				&& MOUSEX > region.left-breathingRoom); 
	}		
}

//event listener for func at load that assigns these variables so they're available
function setMousePositions(event) 
{
  if (typeof event == "undefined")
  {
    event = window.event;
  }

  var scrollingPosition = getScrollingPosition();
  
  var cursorPosition = [0, 0];

  if (typeof event.pageX != "undefined" && typeof event.x != "undefined")
  {
    cursorPosition[0] = event.pageX;
    cursorPosition[1] = event.pageY;
  }
  else
  {
    cursorPosition[0] = event.clientX + scrollingPosition[0];
    cursorPosition[1] = event.clientY + scrollingPosition[1];
  }

	MOUSEX = cursorPosition[0];
	MOUSEY = cursorPosition[1];
}

function getScrollingPosition() 
{
  //array for X and Y scroll position
  var position = [0, 0];

  //if the window.pageYOffset property is supported
  if(typeof window.pageYOffset != 'undefined')
  {
    //store position values
    position = [
        window.pageXOffset,
        window.pageYOffset
    ];
  }

  //if the documentElement.scrollTop property is supported
  //and the value is greater than zero
  if(typeof document.documentElement.scrollTop != 'undefined'
    && document.documentElement.scrollTop > 0)
  {
    //store position values
    position = [
        document.documentElement.scrollLeft,
        document.documentElement.scrollTop
    ];
  }

  //if the body.scrollTop property is supported
  else if(typeof document.body.scrollTop != 'undefined')
  {
    //store position values
    position = [
        document.body.scrollLeft,
        document.body.scrollTop
    ];
  }

  //return the array
  return position;
}