// BANANAS DESIGN
// Common Javascript Functions
// Collection April 2008, needs some clean-up.

// --------------------------------------------------------------------------------------
// GENERIC FUNCTIONS
// --------------------------------------------------------------------------------------

// Used to add more than one handler to the load event by Simon Willison
function addLoadEvent(func) {
	var oldonload = window.onload;
	if (typeof window.onload != 'function') {
		window.onload = func;
	} else {
		window.onload = function() {
			oldonload();
			func();
		}
	}
}

// Finds element which triggers the event
function find_target(e) {
	/* Begin the DOM events part, which you */
	/* can ignore for now if it's confusing */
	var target; 

	if (window.event && window.event.srcElement) 
		target = window.event.srcElement;
	else if (e && e.target)
		target = e.target;
	if (!target)
		return null;

	return target;
}

// cross-browser event handling for IE5+, NS6+ and Mozilla/Gecko
// By Scott Andrew
function addEvent(elm, evType, fn, useCapture) {
	if (elm.addEventListener) {
		elm.addEventListener(evType, fn, useCapture); 
		return true; 
	} else if (elm.attachEvent) {
		var r = elm.attachEvent('on' + evType, fn); 
		return r; 
	} else {
		elm['on' + evType] = fn;
	}
}




//------------------------------------------------------------------------------
function QuickModalDialog(filePath, width, height)
{
    OpenModalDialog("alert", filePath, width, height,null, null, 1, 0, 0, "")
}

function OpenModalDialog(filePath, windowName, width, height, top, left, center, help, resizable, status)
{

  // uncomment this if NS 7 displays modal dialogs wrong, test this later
  /*
  if ( navigator.userAgent.toLowerCase().indexOf('netscape/7.0')!=-1 )
  {
      //alert("fix stupid bug in Netscape 7 browser")
    height = height + 76;
  }
  */

    if (false)//(window.showModalDialog) 
    {
        window.showModalDialog(
        filePath,
        windowName,
        "dialogHeight: " + height + "px; " +
        "dialogWidth: " + width + "px; " +
        "dialogTop: " + top +"px; " +
        "dialogLeft: "+ left + "px; " +
        "center: " + center + "; " +
        "help: " + help + "; " +
        "resizable: " + resizable + "; " +
        "status: "+ status + ";");
    }
    else
    {
        OpenWindow(filePath, windowName, width, height, 0, resizable, 0, null)
    }
}
// **************************************************************************************

// --------------------------------------------------------------------------------------
// OPEN WINDOW
// --------------------------------------------------------------------------------------
function OpenWindow(filePath, windowName, width, height, statusBar, resizable, scrollBars, openerWindow)
{ 

/*
  if ( navigator.userAgent.toLowerCase().indexOf('netscape/7.0')!=-1 )
  {
    //alert("fix stupid bug in Netscape 7 browser")
    height = height + 76;
  }
*/
  
  newWindow = window.open(
    filePath, 
    windowName, 
    "toolbar=0,"+
    "location=0,"+
    "directories=0,"+
    "status="+statusBar+","+
    "menubar=0,"+
    "scrollbars="+scrollBars+","+
    "resizable="+resizable+","+
    "width="+width+","+
    "height="+height+"")


  if (openerWindow!=null)
  {
    newWindow.opener = openerWindow
  }
  
  // if not msie3, focus the window after 1/4 second
 // if (navigator.appName && (!((navigator.appName.indexOf("Microsoft")!=-1)&&(navigator.appVersion.indexOf("3.")!=-1))))
  //{
   // timer=window.setTimeout('newWindow.focus()', 250)
 // }
}
//------------------------------------------------------------------------------
function OpenWindowAtPosition(filePath, windowName, width, height, top, left, statusBar, resizable, scrollBars, openerWindow)
{ 

  if ( navigator.userAgent.toLowerCase().indexOf('netscape/7.0')!=-1 )
  {
    //alert("fix stupid bug in Netscape 7 browser")
    height = height + 76;
  }

  newWindow = window.open(
    filePath, 
    windowName, 
    "toolbar=0,"+
    "location=0,"+
    "directories=0,"+
    "status="+statusBar+","+
    "menubar=0,"+
    "scrollbars="+scrollBars+","+
    "resizable="+resizable+","+
    "width="+width+","+
    "height="+height+","+
    "top="+top+","+
    "left="+left+"")


  if (openerWindow!=null)
  {
    newWindow.opener = openerWindow
  }
  
  // if not msie3, focus the window after 1/4 second
  if (navigator.appName && (!((navigator.appName.indexOf("Microsoft")!=-1)&&(navigator.appVersion.indexOf("3.")!=-1))))
  {
    timer=window.setTimeout('newWindow.focus()', 250)
  }
}
// **************************************************************************************



// --------------------------------------------------------------------------------------
// ROLLOVER FUNCTIONS
// --------------------------------------------------------------------------------------

function setupRollovers() {
	if (!document.getElementsByTagName)
		return;
	var all_links = document.getElementsByTagName('a');
	for (var i = 0; i < all_links.length; i++) {
		var link = all_links[i]; 
		if (link.className &&
				(' ' + link.className + ' ').indexOf(' rollover ') != -1) {
			if (link.childNodes &&
					link.childNodes.length == 1 &&
					link.childNodes[0].nodeName.toLowerCase() == 'img') {
				link.onmouseover = mouseover;
				link.onmouseout = mouseout;
			}
		}
	}
}


function mouseover(e) {
	var target = find_target(e);
	if (!target) return;

	// the only child node of the a tag in target will be an img tag
	var img_tag = target.childNodes[0];

	// Take the "src", which names an image called "something.ext",
	// Make it point to "something_over.ext"
	// This is done with a regular expression
	img_tag.src = img_tag.src.replace(/(\.[^.]+)$/, 'Hi$1');
}

function mouseout(e) {
	var target = find_target(e);
	if (!target) return;

	// the only child node of the A-tag in |target| will be an IMG-tag
	var img_tag = target.childNodes[0];

	// Take the "src", which names an image as "something_over.ext",
	// Make it point to "something.ext"
	// This is done with a regular expression
	img_tag.src = img_tag.src.replace(/Hi(\.[^.]+)$/, '$1');
}

// USAGE: When the page loads, set up the rollovers, like this:
// window.onload = setupRollovers;
// **************************************************************************************



// --------------------------------------------------------------------------------------
// APPLE POPOP WINDOW FUNCTIONS
// --------------------------------------------------------------------------------------
// Copyright © 2000 by Apple Computer, Inc., All Rights Reserved.
//
// You may incorporate this Apple sample code into your own code
// without restriction. This Apple sample code has been provided "AS IS"
// and the responsibility for its operation is yours. You may redistribute
// this code, but you are not permitted to redistribute it as
// "Apple sample code" after having made changes.
//
// modified 13/12/04 Glen - Terabyte
//
// ********************************
// application-specific functions *
// ********************************

// store variables to control where the popup will appear relative to the cursor position
// positive numbers are below and to the right of the cursor, negative numbers are above and to the left
var xOffset = 30;
var yOffset = -5;

function showPopup (targetObjectId, eventObj , divX, divY) {
    if(eventObj)
	{
		
		// if DropDownList exists, hide it to stop it covering images
		var highlightsListHolder = document.getElementById('ArchivesListHolder');
		highlightsList = null;
		
		if(highlightsListHolder != null)
		{
			var allLists = highlightsListHolder.getElementsByTagName('SELECT');
					
			if(allLists[0] != null && allLists[0].tagName == 'SELECT')
			{
				highlightsList = allLists[0];
			}
			
			if(highlightsList != null)
			{
				highlightsList.style.visibility = 'hidden';
			}
		}
		
		// hide any currently-visible popups
		//hideCurrentPopup();
		// stop event from bubbling up any farther
		eventObj.cancelBubble = true;
		// move popup div to current cursor position 
		// (add scrollTop to account for scrolling for IE)
		//var newXCoordinate = (eventObj.pageX)?eventObj.pageX + xOffset:eventObj.x + xOffset + ((document.body.scrollLeft)?document.body.scrollLeft:0);
		//var newYCoordinate = (eventObj.pageY)?eventObj.pageY + yOffset:eventObj.y + yOffset + ((document.body.scrollTop)?document.body.scrollTop:0);
		//var newXCoordinate = divX;
		//var newYCoordinate = divY;
		//moveObject(targetObjectId, newXCoordinate, newYCoordinate);
		// and make it visible
		if( changeObjectVisibility(targetObjectId, 'visible') )
		{
		    // if we successfully showed the popup
		    // store its Id on a globally-accessible object
		    window.currentlyVisiblePopup = targetObjectId;
		    return true;
		}
		else
		{
	    	// we couldn't show the popup, boo hoo!
	    	return false;
		}
    }
	else
	{
		// there was no event object, so we won't be able to position anything, so give up
		return false;
    }
} // showPopup

function hideCurrentPopup() {
    // note: we've stored the currently-visible popup on the global object window.currentlyVisiblePopup
    if(window.currentlyVisiblePopup) {
	changeObjectVisibility(window.currentlyVisiblePopup, 'hidden');
	window.currentlyVisiblePopup = false;
    }
} // hideCurrentPopup

function hidePopup(popup) {
	window.ClosePopup = popup
	if(window.ClosePopup)
	{
		changeObjectVisibility(window.ClosePopup, 'hidden');
		window.ClosePopup = false;
	}
	
	// Show dropdown list again
	if(highlightsList != null)
	{
		highlightsList.style.visibility = 'visible';
	}
} // hidePopup

// ***********************
// hacks and workarounds *
// ***********************

// initialize hacks whenever the page loads
window.onload = initializeHacks;

// setup an event handler to hide popups for generic clicks on the document
// document.onclick = hideCurrentPopup;

function initializeHacks() {
    // this ugly little hack resizes a blank div to make sure you can click
    // anywhere in the window for Mac MSIE 5
    if ((navigator.appVersion.indexOf('MSIE 5') != -1) 
	&& (navigator.platform.indexOf('Mac') != -1)
	&& getStyleObject('blankDiv')) {
	window.onresize = explorerMacResizeFix;
    }
    resizeBlankDiv();
    // this next function creates a placeholder object for older browsers
    createFakeEventObj();
}

function createFakeEventObj() {
    // create a fake event object for older browsers to avoid errors in function call
    // when we need to pass the event object to functions
    if (!window.event) {
	window.event = false;
    }
} // createFakeEventObj

function resizeBlankDiv() {
    // resize blank placeholder div so IE 5 on mac will get all clicks in window
    if ((navigator.appVersion.indexOf('MSIE 5') != -1) 
	&& (navigator.platform.indexOf('Mac') != -1)
	&& getStyleObject('blankDiv')) {
	getStyleObject('blankDiv').width = document.body.clientWidth - 20;
	getStyleObject('blankDiv').height = document.body.clientHeight - 20;
    }
}

function explorerMacResizeFix () {
    location.reload(false);
}
// **************************************************************************************


// Copyright © 2000 by Apple Computer, Inc., All Rights Reserved.
//
// You may incorporate this Apple sample code into your own code
// without restriction. This Apple sample code has been provided "AS IS"
// and the responsibility for its operation is yours. You may redistribute
// this code, but you are not permitted to redistribute it as
// "Apple sample code" after having made changes.
//
// ************************
// layer utility routines *
// ************************

function getStyleObject(objectId) {
    // cross-browser function to get an object's style object given its id
    if(document.getElementById && document.getElementById(objectId)) {
	// W3C DOM
	return document.getElementById(objectId).style;
    } else if (document.all && document.all(objectId)) {
	// MSIE 4 DOM
	return document.all(objectId).style;
    } else if (document.layers && document.layers[objectId]) {
	// NN 4 DOM.. note: this won't find nested layers
	return document.layers[objectId];
    } else {
	return false;
    }
} // getStyleObject

function changeObjectVisibility(objectId, newVisibility) {
    // get a reference to the cross-browser style object and make sure the object exists
    var styleObject = getStyleObject(objectId);
    if(styleObject) {
	styleObject.visibility = newVisibility;
	return true;
    } else {
	// we couldn't find the object, so we can't change its visibility
	return false;
    }
} // changeObjectVisibility

function moveObject(objectId, newXCoordinate, newYCoordinate) {
    // get a reference to the cross-browser style object and make sure the object exists
    var styleObject = getStyleObject(objectId);
    if(styleObject) {
	styleObject.left = newXCoordinate;
	styleObject.top = newYCoordinate;
	return true;
    } else {
	// we couldn't find the object, so we can't very well move it
	return false;
    }
} // moveObject


// **************************************************************************************


// --------------------------------------------------------------------------------------
// MACROMEDIA FUNCTIONS
// --------------------------------------------------------------------------------------

function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

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 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];}
}
// **************************************************************************************




/* FLASH FUNCTIONS
 *
 * FlashObject embed
 * by Geoff Stearns (geoff@deconcept.com, http://www.deconcept.com/)
 *
 * v1.1.1 - 05-17-2005
 *
 * writes the embed code for a flash movie, includes plugin detection
 *
 * Usage:
 *
 *	myFlash = new FlashObject("path/to/swf.swf", "swfid", "width", "height", flashversion, "backgroundcolor");
 *	myFlash.write("objId");
 *
 * for best practices, see:
 *  http://blog.deconcept.com/2005/03/31/proper-flash-embedding-flashobject-best-practices/
 *
 */

var FlashObject = function(swf, id, w, h, ver, c) {
	this.swf = swf;
	this.id = id;
	this.width = w;
	this.height = h;
	this.version = ver;
	this.align = "middle";

	this.params = new Object();
	this.variables = new Object();

	this.redirect = "";
	this.sq = document.location.search.split("?")[1] || "";
	this.bypassTxt = "<p>Already have Macromedia Flash Player? <a href='?detectflash=false&"+ this.sq +"'>Click here if you have Flash Player "+ this.version +" installed</a>.</p>";
	
	if (c) this.color = this.addParam('bgcolor', c);
	this.addParam('quality', 'high'); // default to high
	this.doDetect = getQueryParamValue('detectflash');
}

var FOP = FlashObject.prototype;

FOP.addParam = function(name, value) { this.params[name] = value; }

FOP.getParams = function() { return this.params; }

FOP.getParam = function(name) { return this.params[name]; }

FOP.addVariable = function(name, value) { this.variables[name] = value; }

FOP.getVariable = function(name) { return this.variables[name]; }

FOP.getVariables = function() { return this.variables; }

FOP.getParamTags = function() {
    var paramTags = "";
    for (var param in this.getParams()) {
        paramTags += '<param name="' + param + '" value="' + this.getParam(param) + '" />';
    }
    return (paramTags == "") ? false:paramTags;
}

FOP.getHTML = function() {
    var flashHTML = "";
    if (navigator.plugins && navigator.mimeTypes.length) { // netscape plugin architecture
        flashHTML += '<embed type="application/x-shockwave-flash" src="' + this.swf + '" width="' + this.width + '" height="' + this.height + '" id="' + this.id + '" name="' + this.id + '" align="' + this.align + '"';
        for (var param in this.getParams()) {
            flashHTML += ' ' + param + '="' + this.getParam(param) + '"';
        }
        if (this.getVariablePairs()) {
            flashHTML += ' flashVars="' + this.getVariablePairs() + '"';
        }
        flashHTML += '></embed>';
    } else { // PC IE
        flashHTML += '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="' + this.width + '" height="' + this.height + '" name="' + this.id + '" align="' + this.align + '">';
        flashHTML += '<param name="movie" value="' + this.swf + '" />';
        if (this.getParamTags()) {
            flashHTML += this.getParamTags();
        }
        if (this.getVariablePairs() != null) {
            flashHTML += '<param name="flashVars" value="' + this.getVariablePairs() + '" />';
        }
        flashHTML += '</object>';
    }
    return flashHTML;	
}

FOP.getVariablePairs = function() {
    var variablePairs = new Array();
    for (var name in this.getVariables()) { 
    	variablePairs.push(name + "=" + escape(this.getVariable(name))); 
    }
    return (variablePairs.length > 0) ? variablePairs.join("&"):false;
}

FOP.write = function(elementId) {
	if(detectFlash(this.version) || this.doDetect=='false') {
		if (elementId) {
			document.getElementById(elementId).innerHTML = this.getHTML();
		} else {
			document.write(this.getHTML());
		}
	} else {
		if (this.redirect != "") {
			document.location.replace(this.redirect);
		} else if (this.altTxt) {
			if (elementId) {
				document.getElementById(elementId).innerHTML = this.altTxt +""+ this.bypassTxt;
			} else {
				document.write(this.altTxt +""+ this.bypassTxt);
			}
		}
	}		
}

/* ---- detection functions ---- */
function getFlashVersion() {
	var flashversion = 0;
	if (navigator.plugins && navigator.mimeTypes.length) {
		var x = navigator.plugins["Shockwave Flash"];
		if(x && x.description) {
			var y = x.description;
   			flashversion = y.charAt(y.indexOf('.')-1);
		}
	} else {
		result = false;
	    for(var i = 15; i >= 3 && result != true; i--){
   			execScript('on error resume next: result = IsObject(CreateObject("ShockwaveFlash.ShockwaveFlash.'+i+'"))','VBScript');
   			flashversion = i;
   		}
	}
	return flashversion;
}

function detectFlash(ver) {	return (getFlashVersion() >= ver) ? true:false; }

// get value of query string param
function getQueryParamValue(param) {
	var q = document.location.search || document.location.href.split("#")[1];
	if (q) {
		var detectIndex = q.indexOf(param +"=");
		var endIndex = (q.indexOf("&", detectIndex) > -1) ? q.indexOf("&", detectIndex) : q.length;
		if (q.length > 1 && detectIndex > -1) {
			return q.substring(q.indexOf("=", detectIndex)+1, endIndex);
		} else {
			return "";
		}
	}
}

/* add Array.push if needed */
if(Array.prototype.push == null){
	Array.prototype.push = function(item) { this[this.length] = item; return this.length; }
}
// **************************************************************************************
