// overloading prototype
String.prototype.trim = function () {
    return this.replace(/^\s*/, "").replace(/\s*$/, "");
}

//////////////////////////////
// DisableFormButton
function DisableFormButton(buttonId)
{
    if (top == self)
    {
        $(buttonId).disabled = false;
    }
}

//////////////////////////////
// UtilCheckLightViewPageLoad
function UtilCheckLightViewPageLoad(urlString)
{
    var queryParams = urlString.toQueryParams();
    
    if ($(queryParams.id))
        Lightview.show(queryParams.id);
}

//////////////////////////////
// UtilValidatePhone
function UtilValidatePhone(areacode, phone, isOptional)
{
    var phoneregex = /[2-9](\d{2})[- ]?(\d{3})[- ]?(\d{4})$/;            
    var phoneNum = areacode + phone;
    if (areacode == '' && phone == '' && isOptional)
        return true;
    else
        return phoneregex.test(phoneNum.trim());
}


function UtilIsValidCurrency(amount)
{
    return RegExp(/^\$?[0-9\,]+(\.\d{2})?$/).test(String(amount).replace(/^\s+|\s+$/g, ""));
}

//////////////////////////////
// UtilUnCheckRadioButtons
function UtilUnCheckRadioButtons(selector)
{
    // get all the radio buttons
    var nodes = $$(selector);
    
    // loop through inputs and clear items
    nodes.each( function(node)
    {
        node.checked = false;
    });
    return;
}  

//////////////////////////
// stop automatic submit
function bar(evt){
  var evt = (evt) ? evt : ((event) ? event : null);
  var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
  if ((evt.keyCode == 13) && (node.type=="text"))  { return false;} 
}

function UtilSetOpacity(value, element) {
    element.style.opacity = value/10;
    element.style.filter = 'alpha(opacity=' + value*10 + ')';
}

////////////////////////
//  TRAJ: Flash
function UtilIEFix(){ 
	var strBrowser = navigator.userAgent.toLowerCase(); 
	if(strBrowser.indexOf("msie") > -1 && strBrowser.indexOf("mac") < 0)
	{  
		var theObjects = document.getElementsByTagName('object');  
		var theObjectsLen = theObjects.length;  
		for (var i = 0; i < theObjectsLen; i++) 
		{   
			if(theObjects[i].outerHTML)
			{    
				if(theObjects[i].data)
				{     
					theObjects[i].removeAttribute('data');    
				}    
				var theParams = theObjects[i].getElementsByTagName("param");
				var theParamsLength = theParams.length;
				
				for (var j = 0; j < theParamsLength; j++) 
				{
					if(theParams[j].name.toLowerCase() == 'flashvars')
						var theFlashVars = theParams[j].value;
				}
			
				var theOuterHTML = theObjects[i].outerHTML;
				var re = /<param name="FlashVars" value="">/ig;
				theOuterHTML = theOuterHTML.replace(re,"<param name='FlashVars' value='" + theFlashVars + "'>");
				theObjects[i].outerHTML = theOuterHTML;   
			}  
		} 
	}
}
window.onunload = function() { if (document.getElementsByTagName) {  var objs = document.getElementsByTagName("object");  for (i=0; i<objs.length; i++) {   objs[i].outerHTML = "";  } }}

////////////////////////
// TRAJ: Positioning Utils
function UtilFindPosition(obj) 
{
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		curleft = obj.offsetLeft
		curtop = obj.offsetTop
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft
			curtop += obj.offsetTop
		}
	}
	return [curleft,curtop];
}
function UtilAnchorElements(anchorNode, childNode)
{
	// position menu under button
	var anchorPos = UtilFindPosition(anchorNode);
	childNode.style.position = "absolute";
	childNode.style.left = anchorPos[0] + leftOffSet + 'px';
	childNode.style.top = anchorPos[1] + topOffSet + 'px';
}

////////////////////////
// TRAJ: Element display
function UtilToggleElementDisplay(elementId)
{
	var theElement = $(elementId);
	if (theElement.style.display=='none')
		theElement.style.display='block';
	else
		theElement.style.display='none';
}
function UtilHideAllElement(className)
{
	var nodes = $$("." + className);
	nodes.each( function(node){ node.style.display='none'; });
}
function UtilHideElement(elementId)
{
	$(elementId).style.display='none';
}

////////////////////////
// TRAJ: Default Text Values
function RegisterDefaultInputValue(elementId, settings)
{
	var theNode = $(elementId);
	var initValue = theNode.value;
	if (!settings)
	    settings = new DInputValueSettings('#666666','#000000');

	Event.observe(theNode, 'blur', function() { ToggleDefaultInputValue(elementId, initValue, settings); } );
	Event.observe(theNode, 'focus', function() { ToggleDefaultInputValue(elementId, initValue, settings); } );
}
function ToggleDefaultInputValue(elementId, initValue, settings)
{
	if (!settings)
        settings = new DInputValueSettings('#666666','#000000');

	var theNode = $(elementId);
	if (theNode.value==initValue)
	{
		theNode.value = "";
        theNode.style.color = settings.activeColor;
	}
	else if (theNode.value=="")
	{
	    theNode.style.color = settings.defaultColor;
		theNode.value = initValue;
	}
}
var DInputValueSettings = Class.create(); 
DInputValueSettings.prototype = {   
    initialize: function(defaultColor, activeColor) {
        this.defaultColor = defaultColor;
        this.activeColor = activeColor;
    }
}; 

////////////////////////
// TRAJ: Email
/*
function CheckEmail(theValue)
{
	var myRegxp = /^[a-z0-9!#$%&\'*+\/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&\'*+\/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+(?:[A-Z]{2}|[a-z]{2}|aero|arpa|asia|biz|cat|com|coop|edu|gov|info|int|jobs|mil|mobi|museum|name|net|org|pro|tel|travel)\b$/;
	return myRegxp.test(theValue);
}*/
function EmailSignupForm_Init()
{
    if ($('email-container'))
        UtilToggleElementDisplay('email-container');
        
    var settings = new DInputValueSettings('#666666','#000000');
	RegisterDefaultInputValue('signupEmailAddress', settings);
}
function EmailSignup_Submit(newsletter, campaign, email)
{
    if (!newsletter)
        newsletter = "sn";

	// open signup
	if (!email)
	    email = $('signupEmailAddress').value;
	openNewsletter(newsletter, email, campaign);

	// reset element
	if ($('signupEmailAddress'))
	{
	    $('signupEmailAddress').value = "";
	    ToggleDefaultInputValue('signupEmailAddress', 'Enter E-mail Address');
	}
}

// signup for Spanish version
function EmailSignup_SubmitEs(newsletter, campaign, email)
{
if (!newsletter)
        newsletter = "sn";

	// open signup
	if (!email)
	    email = $('signupEmailAddress').value;
	openNewsletter(newsletter, email, campaign);

	// reset element
	if ($('signupEmailAddress'))
	{
	    $('signupEmailAddress').value = "";
	    ToggleDefaultInputValue('signupEmailAddress', 'Provea su e-mail');
	}
}

////////////////////////
// TRAJ: JSSlideShow
var JSSlideShow = Class.create({

    // constructor
    initialize: function(args) {

        // properties
        this.lastSlideId = null;
        if (args.mouseoutOpacity)
            this.mouseoutOpacity = args.mouseoutOpacity;
        if (args.mouseoverOpacity)
            this.mouseoverOpacity = args.mouseoverOpacity;
        if (args.autoIterTimeout)
            this.autoIterTimeout = args.autoIterTimeout;
    
        // init ctrls
        var ctrls = this.getSlideCtrls();
        if (ctrls)
        {
            for (var i=0; i < ctrls.length; i++)
            {
                // side & ctrl
                var ctrl = ctrls[i];

                // set id
                ctrl.id = 'ctrl_' + i;

                // opacity and zIndex
                if (i > 0)	
                    ctrl.setOpacity(this.mouseoutOpacity);                    
                else
                    ctrl.className = 'selected'; // first ctrl                
            }	

            // events
            ctrls.invoke('observe', 'click', this.btnCtrl_Click.bindAsEventListener(this));
            ctrls.invoke('observe', 'mouseover', this.btnCtrl_MouseOver.bindAsEventListener(this));
            ctrls.invoke('observe', 'mouseout', this.btnCtrl_MouseOut.bindAsEventListener(this));
        }
        
        
        // init slides
        var slides = this.getSlides();
        if (slides)
        {
            
            for (var i=0; i < slides.length; i++)
            {
                // slide
                var slide = slides[i];

                // set id
                slide.id = 'slide_' + i;

                // opacity and zIndex
                if (i > 0)	
                    slide.setStyle({zIndex:1,display:'none'});
                else
                {
                    // initial slide & ctrl
                    slide.setStyle({zIndex: 3}); // first slide
                    this.lastSlideId = slide.id;
                }
                
            }	
        }
    },
    
    getSlides: function()
    {
        return $('slide-container').childElements();
    },
    
    getSlideCtrls: function ()
    {
        var slideCtrls = $('slide-ctrls');
        if (slideCtrls)
            return $('slide-ctrls').childElements();
        return null;
    },
    
    switchSlides: function(lastSlide, newSlide)
    {
        // other slides z-index, move back
        var slides = this.getSlides();
        slides.each(function(element){
            if (element.id!=this.lastSlideId && element.id!=newSlide.id) 
            {
                element.setStyle({zIndex: 2});
                element.setStyle({zIndex: 1});
            }
        });

        // slide: hide & move first
        newSlide.setStyle({zIndex: 6, display:'none'});

        // last slide: move second
        $(this.lastSlideId).setStyle({zIndex: 4});

        // slide: fade in
        newSlide.appear({duration:1, from:0, to:1});
        
        // capture new last slide
        this.lastSlideId = newSlide.id;
    },
    
    startAutoIter: function()
    {
        var slideshow = this;
        s=setTimeout(function() {slideshow.autoIterSlides()},this.autoIterTimeout)
    },
    
    autoIterSlides: function(slideNum)
    {
        if (!slideNum)
            slideNum = 1;

	    var slides = this.getSlides();
	    var slidesLength = slides.length;
	    
        // iterate through
        var newSlide = $('slide_' + slideNum);
        var lastSlide = $(this.lastSlideId);
        this.switchSlides(lastSlide, newSlide);
        
        if (slideNum==slidesLength-1)
            slideNum = 1;
        else
            slideNum += 1;

        var slideshow = this;
        s=setTimeout(function() {slideshow.autoIterSlides(slideNum)},this.autoIterTimeout)
    },
    
    // following functions reference slide show from outside (weird)
    clearSlideCtrlClassNames: function()
    {
        var ctrls = this.getSlideCtrls(); 
        for (var i=0; i < ctrls.length; i++)
        {
            var ctrl = ctrls[i];
            ctrl.className = '';
            ctrl.setOpacity(this.mouseoutOpacity);
        }
    },
    
    // events
    btnCtrl_MouseOut: function(event) 
    {
        var element = Event.findElement(event, 'li');
        if (element.className!='selected')	
        element.setOpacity(this.mouseoutOpacity);
    },

    btnCtrl_MouseOver: function (event) 
    {
        var element = Event.findElement(event, 'li');
        if (element.className!='selected')
            element.setOpacity(this.mouseoverOpacity);
    },
    
    btnCtrl_Click: function(event){
    
        var element = Event.findElement(event, 'li');
        var num = element.id.split('_')[1];
        var newSlide = $('slide_' + num);
        
        // hide last photo
        if (this.lastSlideId != newSlide.id)
        {
            var lastSlide = $(this.lastSlideId);

            // switch
            this.switchSlides(lastSlide, newSlide);

            // clear controls
            this.clearSlideCtrlClassNames();
            element.setOpacity(this.mouseoverOpacity);
            element.className = 'selected';
        }
    }
});

var JSSlideShow_ArrowCtrls = Class.create({

    // constructor
    initialize: function(args) {

        // properties
        this.ctrls_container_moving = false;
        this.ctrls_container_pos = 0;
        
        if (args.scroll_speed)
            this.scrollSpeed = args.scroll_speed;
        else
            this.scrollSpeed = 150;
            
        if (args.scroll_width)
            this.ctrls_container_min = -args.scroll_width;
        else
            this.ctrls_container_min = -0;
        
        // events
        $('slide-btn-last').observe('mouseover', this.btnCtrlArrow_MouseOver.bindAsEventListener(this));
        $('slide-btn-next').observe('mouseover', this.btnCtrlArrow_MouseOver.bindAsEventListener(this));
        
        $('slide-btn-next').observe('mouseout', this.btnCtrlArrow_MouseOut.bindAsEventListener(this));
        $('slide-btn-last').observe('mouseout', this.btnCtrlArrow_MouseOut.bindAsEventListener(this));
    },

    btnCtrlArrow_MouseOut: function(event) {
    
        this.ctrls_container_moving = false;
    },

    btnCtrlArrow_MouseOver: function(event) {
    
        var element = Event.findElement(event, 'img');

        this.ctrls_container_moving = true;
        JSSlideShow_ScrollCtrls(element.id);
    }
});

function JSSlideShow_ScrollCtrls(elementId, speed)
{
    if (arrowCtrls.ctrls_container_moving)
    {
        if (elementId=='slide-btn-next' && arrowCtrls.ctrls_container_pos > arrowCtrls.ctrls_container_min)
            arrowCtrls.ctrls_container_pos--;
        else if (arrowCtrls.ctrls_container_pos < 0)
            arrowCtrls.ctrls_container_pos++;

        $('slide-ctrls').setStyle({left:arrowCtrls.ctrls_container_pos + 'px'});
        setTimeout("JSSlideShow_ScrollCtrls('" + elementId + "')",speed);
    }
}



////////////////////////
//  TRAJ: Cookie Utils
function setCookie(cookieName, cookieValue, expireDate)
{
	removeCookie(cookieName);
	if (expireDate == "")
		expires = "";
	else
	{
		expires = new Date();
		expires.setDate(expires.getDate() + expireDate);
		expires = expires.toGMTString();
	}
	theCookie = cookieName+"="+cookieValue+";expires="+expires;
	document.cookie = theCookie; 
}
function removeCookie (cookieName)
{
	expires = new Date();
	document.cookie = cookieName+"= ;expires="+expires.toGMTString();
}
function getCookie (cookieName)
{
	cookieValue = null;
	if (document.cookie.indexOf(cookieName) == -1)
		return cookieValue;
	else
	{
		cookieStart = document.cookie.indexOf(cookieName);
		cookieValStart = (document.cookie.indexOf("=", cookieStart) + 1);
		cookieValEnd = document.cookie.indexOf(";", cookieStart);
		if (cookieValEnd == -1)
			cookieValEnd = document.cookie.length
		cookieValue = document.cookie.substring(cookieValStart, cookieValEnd);
		return cookieValue;
	}
}
function detectCookies()
{
	setCookie("test", "test", "");
	tmp = getCookie("test");
	if (tmp != "test") { return false; }else{ return true; }
}

////////////////////////
//  TRAJ: Random Util
function randNum(seed)
{
	var randomNum = Math.floor(Math.random() * seed);
	return randomNum;
}


////////////////////////
//  TRAJ: AJAX Util
function SendAJAXRequest(url, doOnComplete, pars)
{
	var myAjax = new Ajax.Request(url,{method: 'get', parameters: pars, onComplete: doOnComplete });
}
function UtilParseResponse(startTag, endTag, responseText, trimTags)
{
	var result = responseText;
	// trim top
	var start = result.indexOf(startTag);
	var len = result.length;
	result = result.substring(start, len);
	
	// trim bottom
	len = result.length;
	var end = result.indexOf(endTag) + endTag.length;
	result = result.substring(0,end);
	
	// trim start & end tags
	if (trimTags)
	{
		result = result.substring(startTag.length, result.length);
		result = result.substring(0, result.length - endTag.length);
	}
	return result;
}

////////////////////////
//  TRAJ: Javascript Blog
function Blog_GetBlog(originalRequest)
{
	if(originalRequest==null)
		SendAJAXRequest('/efc/efc_wao/wao_blog.asp',Blog_GetBlog,'');
	else
	{
		var startTag = '<a name="HighlightBlogStart"></a>';
		var endTag = '<a name="HighlightBlogEnd"></a>';
		
		$('blog').innerHTML = UtilParseResponse(startTag, endTag, originalRequest.responseText) + $('blog').innerHTML;
	}
}
function Blog_GetBlogPhoto(originalRequest)
{
	if(originalRequest==null)
		SendAJAXRequest('/efc/efc_wao/wao_blog.asp',Blog_GetBlogPhoto,'');
	else
	{
		// fix this regular expression
		var regExp = '<img id="PhotoHighlight".*?>';
		var re = new RegExp(regExp, 'm');
		var result = re.exec(originalRequest.responseText);
		if (result==null)
		    result='';
		$('blog-photo').innerHTML = result;
	}
}

////////////////////////
//  TRAJ: Javascript Polls
function Poll_ClosePopup(childWindow)
{
	childWindow.close();
	document.location.reload();	
}

////////////////////////
// inline picture poll
function Poll_GetPicturePoll(originalRequest, pollId, source)
{
	if(originalRequest==null)
	{
		var url = '/aquariumlibraryweb/ui/poll/InlinePicturePoll.aspx';
		var pars = 'pid=' + pollId + '&source=' + source;
		SendAJAXRequest(url, Poll_GetPoll, pars);
	}
	else
	{
		// show poll			
		var startTag = '<a name="StartPoll"></a>';
		var endTag = '<a name="EndPoll"></a>';
		
		$('poll').innerHTML = UtilParseResponse(startTag, endTag, originalRequest.responseText);
		$('poll').style.display = 'block';
	}
}

// vote picture poll
function Poll_PictureVote(pollId, source)
{
	// get value
	var selectedValue = "";	
    var nodes = $$('.answers input');
    
    if (nodes!='')
    {
        nodes.each( function(node){ 
           if (node.checked == true)
                selectedValue = node.value;
        });
    }
	
	if (selectedValue > 0)
	{
		// hide form & show wait
		$('poll').innerHTML = '<h4 class="pollstatus">Retrieving the results...</h4>';

		// count vote
		var url = '/aquariumlibraryweb/ui/poll/InlinePicturePoll.aspx';
		var pars = 'a=2&pid=' + pollId + '&aid=' + selectedValue + '&source=' + source;
		SendAJAXRequest(url, null, pars);
		setCookie('MBAP'+pollId, '1', 30);
		
		// get results
		setTimeout('Poll_GetPictureResults(null, ' + pollId + ', ' + source + ')', 2000);
	}
}

function Poll_GetPictureResults(originalRequest, pollId, source)
{
	if(originalRequest==null)
	{
		var url = '/aquariumlibraryweb/ui/poll/picturepoll.aspx?v=false';
		var pars = 'pid=' + pollId + '&source=' + source;
		SendAJAXRequest(url, Poll_GetPictureResults, pars);
	}
	else
	{
		// show results					
		var startTag = '<a name="StartQuestion"></a>';
		var endTag = '<a name="EndQuestion"></a>';

		var result = UtilParseResponse(startTag, endTag, originalRequest.responseText);
	
		var startTag = '<a name="StartResults"></a>';
		var endTag = '<a name="EndResults"></a>';
	    result += UtilParseResponse(startTag, endTag, originalRequest.responseText);
		
		$('poll').innerHTML = result;
		    
		$('poll').style.display = 'block';
	}
}

///////////////////////////////////////
// regular inline poll
// grace: added source param (for collective action exhibit)
function Poll_GetPoll(originalRequest, pollId, source)
{
	if(originalRequest==null)
	{
		var url = '/aquariumlibraryweb/ui/poll/InlinePoll.aspx';
		var pars = 'pid=' + pollId + '&source=' + source;
		SendAJAXRequest(url, Poll_GetPoll, pars);
	}
	else
	{
		// show poll			
		var startTag = '<a name="StartPoll"></a>';
		var endTag = '<a name="EndPoll"></a>';
		
		$('poll').innerHTML = UtilParseResponse(startTag, endTag, originalRequest.responseText);
		$('poll').style.display = 'block';
	}
}

// vote
function Poll_Vote(pollId, source)
{
	// get value
	var selectedValue = "";
	var radioObj = document.getElementsByName('rbtnLstAnswers');
	for(var i = 0; i < radioObj.length; i++) {
		if(radioObj[i].checked)
			selectedValue = radioObj[i].value;
	}	
	
	if (selectedValue > 0)
	{
		// hide form & show wait
		$('poll').innerHTML = 'Retrieving the results...<br><br><br><br>';

		// count vote
		var url = '/aquariumlibraryweb/ui/poll/InlinePoll.aspx';
		var pars = 'a=2&pid=' + pollId + '&aid=' + selectedValue + '&source=' + source;
		SendAJAXRequest(url, null, pars);
		setCookie('MBAP'+pollId, '1', 30);
		
		// get results
		setTimeout('Poll_GetResults(null, ' + pollId + ', ' + source + ')', 2000);
	}
}

function Poll_GetResults(originalRequest, pollId, source)
{
	if(originalRequest==null)
	{
		var url = '/aquariumlibraryweb/ui/poll/poll.aspx?v=false';
		var pars = 'pid=' + pollId + '&source=' + source;
		SendAJAXRequest(url, Poll_GetResults, pars);
	}
	else
	{
		// show results					
		var startTag = '<a name="StartQuestion"></a>';
		var endTag = '<a name="EndQuestion"></a>';

		var result = UtilParseResponse(startTag, endTag, originalRequest.responseText);
	
		var startTag = '<a name="StartResults"></a>';
		var endTag = '<a name="EndResults"></a>';
		result += UtilParseResponse(startTag, endTag, originalRequest.responseText);
		
		$('poll').innerHTML = result + '<div class="poll-thanks">Thanks for taking the poll.</div>';
		    
		$('poll').style.display = 'block';
	}
}

function Poll_SubmitWriteYourOwn(originalRequest, pollId, answerId, userText)
{
    if(originalRequest==null)
	{
	    var url = '/AquariumLibraryWeb/ui/customPoll/CustomPoll.aspx';
	    var pars = 'pollId=' + pollId + '&answerId=' + answerId + '&userText=' + encodeURI(userText);
	    SendAJAXRequest(url, Poll_SubmitWriteYourOwn, pars);
	}
	else
	{
		var result = UtilParseResponse(startTag, endTag, originalRequest.responseText);
	}
}


////////////////////////
//  TRAJ: Pull Down Menus
var sInitPageComplete = false;  // for sync & other page javascript
var sCloseAllNodes = true;      // for menu button mouse-off bug
var sLastOpenNode = "";         // so we don't open the same menu twice
var sOpenMe = "";               // prevents two menus from opening (timeout bug)
var leftOffSet = 0;             // off set for anchoring issues
var topOffSet = 24;
var closeMenuDelay = 500;       // delay before closing menus
var openMenuDelay = 400;        // no accidental mouse overs :)
Event.observe(window, 'load', function (){ GlobalNav_Init(); })

function PDOpenMenu(menuId, showEffect)
{
	if (sInitPageComplete && sLastOpenNode!=menuId)
	{
		// close all & set last opened
		PDCloseAllNodes(true);
		sLastOpenNode = menuId;
	    sOpenMe = menuId;
	    PDPositionMenu(menuId);
	    setTimeout("timeoutOpenMenu("+showEffect+", '"+menuId+"');", openMenuDelay);
	}
	sCloseAllNodes = false;
}
function PDPositionMenu(menuId)
{
    for (i=0;i<pdRegNodes.length;i++)
    {
	    var node = pdRegNodes[i];
	    if (menuId==node.menuId)
	        UtilAnchorElements($(node.btnId), $(node.menuId));
    }
}
function timeoutOpenMenu(showEffect, menuId)
{
    if (sOpenMe == menuId && !sCloseAllNodes)
    {
	    if (showEffect)
		    new Effect.SlideDown(menuId, {duration:.5});
	    else
	    {
		    var menuNode = $(menuId);
		    menuNode.style.display="block";
	    }
	    sOpenMe = "";
	}
}
function PDSelectMenuItem(node, className)
{
	node.className = className;
	sCloseAllNodes = false;
}
function PDSetTimeout()
{
	sCloseAllNodes = true;
	setTimeout("PDCloseAllNodes()", closeMenuDelay);
}
function PDCloseAllNodes(force)
{
	if (sInitPageComplete && (sCloseAllNodes || force))
	{
		// close all registered menus
		sOpenMe = "";
		sLastOpenNode = "";
		for (i=0;i<pdRegNodes.length;i++)
		{
			var node = pdRegNodes[i];
			var menuNode = $(node.menuId);
			menuNode.style.display = "none";
			
			// un-select Menu Item
			if (node.settings.btnOutClass)//!='undefined')
			{
				var btnNode = $(node.btnId);
				PDSelectMenuItem(btnNode, node.settings.btnOutClass);
			}
		}		
		sCloseAllNodes = false;
	}
}
var pdRegNodes = new Array();
function PDRegisterMenu(btnId, menuId, settings)
{
	// store registered button & menu
	var strSet = Object.toJSON(settings);
	eval("pdRegNodes[pdRegNodes.length] = { btnId:'" + btnId + "', menuId:'" +  menuId + "', settings:" + strSet + "}");

	// get nodes	
	var btnNode = $(btnId);
	var menuNode = $(menuId);
	
	// wire parent button
	Event.observe(btnNode, 'mouseout',	function (){ PDSetTimeout();});
	PDWireExpandableNode(btnNode, menuId, settings);

    // wire pulldown menu items
	if (settings.itemOverClass || item.itemOutClass)
	{
		var itemNodes = $A(menuNode.getElementsByTagName(settings.itemTagName));
		itemNodes.each(function(itemNode){

			if (settings.itemOverClass)
				Event.observe(itemNode, 'mouseover', function (){ PDSelectMenuItem(itemNode, settings.itemOverClass)});

			if (settings.itemOutClass)
				Event.observe(itemNode, 'mouseout', function (){ PDSelectMenuItem(itemNode, settings.itemOutClass); PDSetTimeout()});
		});
	}

	// anchor menu under button
	UtilAnchorElements(btnNode, menuNode)
	menuNode.style.display = 'none';
}
function PDWireExpandableNode(anchorNode, expandableNode, settings)
{
	if (settings.btnOverClass)
		Event.observe(anchorNode, 'mouseover', function (){ PDOpenMenu(expandableNode, settings.showEffect);	PDSelectMenuItem(anchorNode, settings.btnOverClass)	});
	else
		Event.observe(anchorNode, 'mouseover', function (){ PDOpenMenu(expandableNode, settings.showEffect);	});
}
var PDSettings = Class.create(); 
PDSettings.prototype = {   
    initialize: function(itemTagName, showEffect, itemOverClass, itemOutClass, btnOverClass, btnOutClass) {
        this.itemTagName = itemTagName;         // tag name for pulldown menu item (ex. li, div, etc)
        this.showEffect = showEffect;           // show slide down effect? true / false
        this.itemOverClass = itemOverClass;     // css class for pulldown menu item
        this.itemOutClass = itemOutClass;       //..
        this.btnOverClass = btnOverClass;       // css class parent button
        this.btnOutClass = btnOutClass;         //..
    }
}; 
function GlobalNav_Init()
{
    // email signup
    if ($('signupEmailAddress'))
        EmailSignupForm_Init();
        
    var settings = new DInputValueSettings('#001275','#001275');
	if ($('search-field'))
	    RegisterDefaultInputValue('search-field', settings);
	if ($('webHeader_searchFor'))
	    RegisterDefaultInputValue('webHeader_searchFor', settings);	
    
    if ($('pd-global-btn1'))
    {
	    // register global nav
	    topOffSet = 38;
	    leftOffSet = 0;

        var settings = new PDSettings('a',false, 'item-over','item-out');
	    PDRegisterMenu('pd-global-btn1', 'pd-global-menu1', settings);
	    PDRegisterMenu('pd-global-btn2', 'pd-global-menu2', settings);
	    PDRegisterMenu('pd-global-btn3', 'pd-global-menu3', settings);
	    PDRegisterMenu('pd-global-btn4', 'pd-global-menu4', settings);
	}
	// important to do this or nothing will work
	sInitPageComplete = true;
}

////////////////////////
//  TRAJ: OpenNewWindow
var win = null;
var justOpenedPDF;
function randomizePopup(seed, pURL, inName, inTitle, inWidth, inHeight, inFeatures)
{
	if(detectCookies())
	{
		var randomNum = randNum(seed);
		if (randomNum==0)
			openNewWindow(pURL, inName, inTitle, inWidth, inHeight, inFeatures);
	}
}
function openNewWindow(inURL, inName, inTitle, inWidth, inHeight, inFeatures) {

	var features = setWindowFeatures(inTitle, inWidth, inHeight, inFeatures);
	dealWithPDF(inURL, inName, features);
	
	win = window.open(inURL, inName, features);
	if (!justOpenedPDF)
		win.focus();
}
function openNewWindowResized(inURL, inName, inTitle, inWidth, inHeight, inFeatures) 
{
	var features = setWindowFeatures(inTitle, inWidth, inHeight, inFeatures);
	dealWithPDF(inURL, inName, features)

	if(win)
		win.close();

	win = window.open(inURL, inName, features);	
	if (!justOpenedPDF)
		win.focus();
}
function setWindowFeatures(inTitle, inWidth, inHeight, inFeatures) 
{
	var features = inFeatures;
	if(features != '') features += ',';
	features += 'title=' + inTitle + ',';
	if(inWidth > 0 && inHeight > 0)
		features += 'width=' + inWidth + ',height=' + inHeight;
	return features
}
function dealWithPDF(inURL, inName, features)
{
	// PDF WINDOW
	var isPDF = false;
	if(inURL!=null && inURL!='')
	{
		// does URL contain .pdf
		var theURL = inURL.split(".");
		theURL = theURL[1];
		if (theURL!=null)
		{
			if(theURL.substring(0,3).toLowerCase()=="pdf")
			{
				// mark as a pdf & just opened pdf
				isPDF = true;
				justOpenedPDF = true;
			}
		}
	}

	// close window twice (both this time and next click)
	if(win && (isPDF || justOpenedPDF))
	{
		// close, open & then close
		win = window.open('/blank.html', inName, features);
		win.close();
		//win = window.open('/blank.html', inName, features);
		//win.focus();
		
		if (!isPDF && justOpenedPDF)
			justOpenedPDF = false;
	}
}

////////////////////////
//  Flickr Photos
var flickrPopup = null;
var leaveSiteWarning = "http://www.montereybayaquarium.org/LeavingSite.asp";
function PopFlickrThumb(url)
{
    tmp = getCookie("flickr-leaving");
    if (flickrPopup || tmp == "true")
        openNewWindow(url,'flickr','flickr',780,580,'scrollbars,toolbar,resizable,location');
    else
        openNewWindow(leaveSiteWarning + "?url=" + url,'flickr','flickr',780,580,'scrollbars,toolbar,resizable,location');

    setCookie('flickr-leaving', 'true', 1);

    flickrPopup = win;
}

////////////////////////
//  TRAJ: Legacy
function clickButton(e, buttonid){ 
      var bt = document.getElementById(buttonid); 
      if (typeof bt == 'object'){ 
            if(navigator.appName.indexOf("Netscape")>(-1)){ 
                  if (e.keyCode == 13){ bt.click(); return false; } 
            } 
            if (navigator.appName.indexOf("Microsoft Internet Explorer")>(-1)){ 
                  if (event.keyCode == 13){ bt.click(); return false; } 
            } 
      } 
} 
function openCamWindow(inURL, inWidth, inHeight) {
	openNewWindow(inURL, 'popup', 'Monterey Bay Aquarium', inWidth, inHeight, '');
}
function openEmailAPage(key,qs){
	var url = '/aquariumLibraryWeb/ui/email/Email.aspx?k='+ key
	if (qs!=null)
	     url += '&qs=' + qs;
	openNewWindow(url, 'EmailAPage', 'Monterey Bay Aquarium',500,580,'scrollbars,toolbar,resizable')
}
function openNewsletter(key, initEmailAddress, campaignCode) {
	var url = '/newslettermgmt/web/SubscriptionDetails.aspx?k=' + key;
	if (initEmailAddress!=null)
	     url += '&e=' + initEmailAddress;
	if (campaignCode!=null)
	     url += '&cp=' + campaignCode;
	openNewWindow(url,'popup','newsletter',500,580,'scrollbars,toolbar,resizable')
}
function openGlossary(inTerm) {
	var url = '/AquariumLibraryWeb/ui/glossary/glossarySearch.aspx#' + inTerm
	openNewWindow(url, 'glossary', 'Monterey Bay Aquarium: Glossary', 485, 500, 'resizable,scrollbars,menubar')
}
function redirectGlossary(url)
{
	window.resizeTo(780,580);
	document.location.href=url;
}
function redirectFAQ(url)
{
	if(url.indexOf('?popup') > 0)
		openNewWindow(url,'Popup','Popup',780,580,'scrollbars,toolbar,resizable,location')
	else
		document.location.href = url;
}
function URLEncode(plaintext)
{
	var SAFECHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_.!~*'()";
	var HEX = "0123456789ABCDEF";
	var encoded = "";
	for (var i = 0; i < plaintext.length; i++ ) {
		var ch = plaintext.charAt(i);
	    if (ch == " ") {
		    encoded += "+";				// x-www-urlencoded, rather than %20
		} else if (SAFECHARS.indexOf(ch) != -1) {
		    encoded += ch;
		} else {
		    var charCode = ch.charCodeAt(0);
			if (charCode > 255) {
			    alert( "Unicode Character '" 
                        + ch 
                        + "' cannot be encoded using standard URL encoding.\n" +
				          "(URL encoding only supports 8-bit characters.)\n" +
						  "A space (+) will be substituted." );
				encoded += "+";
			} else {
				encoded += "%";
				encoded += HEX.charAt((charCode >> 4) & 0xF);
				encoded += HEX.charAt(charCode & 0xF);
			}
		}
	}
	return encoded;
}

// Living species list
var kHabitats = 0;
var kInhabitants = 1;
function popSearchLSL(searchString)
{
	openNewWindow('/efc/living_species/default.asp?searchString='+ URLEncode(searchString) ,'fieldguidePopup','Field Guide',500,520,'scrollbars,toolbar,resizable');
}
function openLivingSpeciesList(inArea, inGroup, inInhabitant) {	
	popLSL(inArea,inGroup,inInhabitant);
}
function popLSL(inArea, inGroup, inInhabitant) {
	var url = '/animals/AnimalDetails.aspx?legacyid=' + inInhabitant;
	document.location.href = url;
}
function openHTMLWindow(inURL, inWidth, inHeight) {
	openNewWindow(inURL, '', 'Monterey Bay Aquarium', inWidth, inHeight, 'resizable,scrollbars,menubar,toolbar,location');
}
function openKelpForestInteractive(inName) {
	var url = '/redirects/kelp_forest_interactive.asp';
	openNewWindow(url, inName, 'Monterey Bay Aquarium: Kelp Forest Interactive', 615, 600, 'resizable,scrollbars');
}
function openSplashZoneCD(inTrack) {
	var url = '/redirects/splash_zone_music.asp?track=' + inTrack;
	openNewWindow(url, 'splash_zone_cd', 'Splash Zone CD', 320, 540, '');
}
function openFAQPopup(categoryID, windowName, anchorID)
{
	strURL = '/aquariumlibraryweb/ui/faq/faqSearch.aspx?';

	if (categoryID!=null && categoryID!='')
		strURL += 'categoryId=' + categoryID;

	if (anchorID!=null && anchorID!='')
		strURL += '#' + anchorID;

	openNewWindowResized(strURL,windowName,'FAQPopup',470,600,'scrollbars,resizable,location,toolbar')
}
function openFAQ(categoryID)
{
	openFAQPopup(categoryID, 'FAQPopup')
}
function openOtterTimeline() {
	var url = '/redirects/otter_timeline.asp'
	openNewWindow(url, '', 'Monterey Bay Aquarium: Otter Timeline', 600, 510, 'resizable,scrollbars')
}

// swap images
function MM_findObj(n, d) { //v3.0
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document); return x;
}
function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}
function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}


function launchCardPopup()
{
    if (getCookie ('sfw_oi_100hrs'))
        document.location.href = '/cr/cr_seafoodwatch/download.aspx';
    else
    {
        setCookie('sfw_oi_100hrs', true, '1/1/2010')
        openNewWindow('/cr/cr_seafoodwatch/report/signup_cards.aspx','popup','popup',485,580,'scrollbars,toolbar,resizable,location')
    }
        
    return true;
}
function GoToPocketGuides()
{
    opener.location.href = '/cr/cr_seafoodwatch/download.aspx';	
	return true;
}
