// Blue Rivers Default JavaScript Functions

/*-----------------------------
 Event Listeners Functions
------------------------------*/

//Use prototype to kick off our listeners
Event.observe(window, 'load', init);


//Add an event listener for each function that loads with the page
function init() {

	// Does the browser support the method?
	if (!document.getElementById) {
		return;
	}
	
	//Install search event listener
	var mySearchField	= $('searchRequest');
	if(mySearchField) {
		mySearchField.observe('keyup', startSearch);
		mySearchField.observe('focus', turnOnSearchMenu);
		mySearchField.observe('blur', turnOffSearchMenu);
	}

	//Install more menu listener
	var moreImage = $('moreImage');	
	if (moreImage) {
		moreImage.observe('click', toggleMore);
	}

	//Conditionally install image roll over listeners
    attachRollOverListeners();

	attachButtonListeners();

	var commentAdd	= $('Comment_Add');
	if (commentAdd) {
		commentAdd.observe('click', addComment);
	}

	var deliciousLink = $('deliciousLink');    
	if (deliciousLink) {
		deliciousLink.observe('click', postToDelicious);
	}	
	
	var containerControl = $('floatingContainerControl');
	if (containerControl) {
		containerControl.observe('click', hideContainer);
	}
	
	var dialogBoxClose = $('dialogBoxClose');
	if (dialogBoxClose) {
		dialogBoxClose.observe('click', closeDialogBox);
		dialogBoxClose.observe('mouseover', toggleImage);
		dialogBoxClose.observe('mouseout', toggleImage);		
	}
	
	var balloonBoxClose = $('balloonBoxClose');
	if (balloonBoxClose) {
		balloonBoxClose.observe('click', hideBalloonBox);
	}
	
	var balloonBoxClose = $('balloonBoxClose');
	if (balloonBoxClose) {
		balloonBoxClose.observe('click', hideBalloonBox);
	}
	
	//updateContactForm();		
	
	//Animation the butterfly
	Butterfly.animate();
	    
}


//Install image roll over listeners
function attachRollOverListeners() {

	// Get image tag collection
	var allImages = $T('img');
	
	// Traverse the collection
	for (var i = 0; i < allImages.length; i++) {
		var imageId		= allImages[i].id;
				
		//If the image has an id check it for a link
		if (imageId) {
			var imageElement	= $(imageId);
			var imageLink 		= imageElement.up('a');

			//Attach a rollover only when the image is embedded in a link
			if (imageLink) {

				//Attach both parts of the rollover			 
				allImages[i].observe('mouseover', toggleImage);
				allImages[i].observe('mouseout', toggleImage);

			}
		}			
	}

}

function attachButtonListeners () {

	var commentButton		= $('Comment_Button');
	if (commentButton) {
		commentButton.observe('mouseover', turnCommentsButtonOn);
		commentButton.observe('mouseout', turnCommentsButtonOff);
		commentButton.observe('click', toggleComments);
	}
	
	var printerButton		= $('Printer_Button');
	if (printerButton) {
		printerButton.observe('click', printPage);
	}

}

function turnCommentsButtonOn() {
	Comment.turnCommentsButtonOn();
}

function turnCommentsButtonOff() {
	Comment.turnCommentsButtonOff();
}

function toggleComments(e) {
	Comment.toggleComments(e)
}


//Gets the source of a target event 
//This method is based on the event capture found in the book DHTML Utopia
function getSourceElement(e) {

	var sourceElement;

	if (window.event && window.event.srcElement) {
		sourceElement = window.event.srcElement;
	} else if (e && e.target) {
		sourceElement = e.target;
	}

	if (!sourceElement) {
		return;
	} else {
		return sourceElement;
	}
	
	
}

/*--------------------
 Menu Manipulation
----------------------*/

function toggleMore(e) {

	var imageModifier	= '_On';	
	var imageElement 	= getSourceElement(e);
	
	var imageId			= imageElement.id;
	var imageObj		= $(imageId);
	var imageName		= imageObj.name;
	
	var imageSource		= imageElement.src;
	
	// The moreListContainer requires the moreWrapper element 
	// It must have a child element with the list as the child element
	var moreList		= 'moreListContainer';
		
	if (imageSource.match(imageModifier)) {
		toggleImage(e);
		new Effect.SlideDown(moreList);	
		setCookie('ui', 'more|on', 3650);
		var myCookie = getCookie('ui');
		//alert(myCookie);
	} else {
		toggleImage(e);
		new Effect.SlideUp(moreList);
		setCookie('ui', 'more|off', 3650);
		var myCookie = getCookie('ui');
		//alert(myCookie);
	}

}

//Use the protoype.js function to toggle an element
function toggleElement(element) {
	$(element).toggle();
}

//Use the JavaScript provided by del.icio.us to create a new bookmark post
function postToDelicious() {
	location.href='http://del.icio.us/post?v=3&amp;url=' + encodeURIComponent(location.href) + '&amp;title=' + encodeURIComponent(document.title.replace(/^\s*|\s*$/g,''));
}


/*--------------------
 Image Rollovers
----------------------*/

function toggleImage(e, sourceImage) {

	//The file name for the rollover should have this value
	//just before the file extension for example, My_Image_On.gif
	var imageModifier	= '_On';
	var period			= '.';

	//Get the image parameters
	var imageElement = sourceImage ? sourceImage : getSourceElement(e);	
	var imageId		= imageElement.id;
	var imageObj	= $(imageId);
	
	var imageSourceTxt	= imageObj.src;
	
	//Split the text of the image source into array elements
	var imageSourcePath	= imageSourceTxt.split('/');

	//Set the imageSource Name as the last element of the array
	var imageSourceName	= imageSourcePath.pop();
		
	//Split the file name into the root name and extension
	var sourceParts		= imageSourceName.split(period);
	
	var imageTargetTxt	= '';
	
	if (imageSourceName.match(imageModifier)) {

		//Replace the image file modifier with a blank string to remove the modifier
		//so that myImageOn.gif would become myImage.gif	
		var imageTargetName		= sourceParts[0].replace(imageModifier, '') + period + sourceParts[1];
		var imageTargetPath		= imageSourcePath.join('/');
		imageTargetTxt			= imageTargetPath + '/' + imageTargetName;	
	
	} else {

		//Add the modifier so that the image has the "on" appearance	
		var imageTargetName		= sourceParts[0] + imageModifier + period + sourceParts[1];
		var imageTargetPath		= imageSourcePath.join('/');
		imageTargetTxt			= imageTargetPath + '/' + imageTargetName;			
	
	}
	
	imageObj.src	= imageTargetTxt;


}


/*--------------------
 Widget Calls
----------------------*/

// Inserts the podcast object into the the content element of the document
// This approach allows users to choose when to load the object
function showPodcast(resourceURL){

	var contentElement	= $('content');	
	
	//**NEEDS IMPROVEMENT***
	//Should be moved to a dialog box
	contentElement.innerHTML = 'Thank you for selecting the Blue Rivers podcast. Please wait while it loads';

	Story.hideContentToolBar();
	Comment.hideNumComments();

	//Internet Explorer handles QuickTime objects differently
	if (window.ActiveXObject) {
		var codeBaseURL = 'http://www.apple.com/qtactivex/qtplugin.cab'; 
		contentElement.innerHTML = '<object id="podcastObject" classid="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B" codebase="'+ codeBaseURL + '" width="300" height="316" style="height: 316px; left: 200px; position: absolute; top: 16px; width: 300px; z-index: 1; "><param name="src" value="' + resourceURL + '" /><param name="controller" value="true" /><param name="autoplay" value="false" /><param name="scale" value="tofit" /><param name="volume" value="100" /><param name="loop" value="false" /></object>';
	} else {
		contentElement.innerHTML = '<object id="podcastObject" type="video/quicktime" width="300" height="316" data="' + resourceURL + '" style="height: 316px; left: 200px; position: absolute; top: 16px; width: 300px; z-index: 1; "><param name="src" value="' + resourceURL + '"/><param name="controller" value="true"/><param name="autoplay" value="false"/><param name="scale" value="tofit"/><param name="volume" value="100"/><param name="loop" value="false"/></object>';
	}


}


//Displays an image in a container element
function displayImage(imageElement) {

	// Set image attributes
	var imageElmId 			= imageElement.id;
	var imageObj			= $(imageElmId);
	var imageSrc			= imageObj.src;
	var imageLabel			= imageObj.alt;
	var imageTag			= '<img src="' + imageSrc + '" />';

	// Set container attributes
	var containerObj		= new Container;
		
	containerObj.setObjectContent(imageTag);
	containerObj.setLabelContent(imageLabel);
	containerObj.displayContainer();
	
}

function hideContainer() {
	var containerObj	= new Container;
	containerObj.hide();
}

// This function needs to be called hideBalloonBox
// because it is a generic function called by many events
function hideBalloonBox() {

	var ballBox = new BalloonBox;
	ballBox.closeBalloonBox();

}

/* Date Functions */
function getTodaysDate() {

	var dateObject		= new Date();
	var currentMonth	= dateObject.getMonth() + 1;
	var currentDate		= dateObject.getDate();
	var currentYear		= dateObject.getFullYear();
	var todaysDate 		= currentMonth + '/' + currentDate + '/' + currentYear;

	return todaysDate;

}


/* Cookie Functions */
function setCookie(name, value, expires, path, domain, secure) {

	// Set time in milliseconds
	var objDate = new Date();
	objDate.setTime( objDate.getTime() );

	//Set for x number of days method could be improved to give the choice
	if (expires) {
		//Miliseconds, seconds, minutes, hours = 1 day
		expires = expires * 1000 * 60 * 60 * 24;
	}

	var expiresDate = new Date( objDate.getTime() + (expires) );
	
	//Build Cookie
	var myCookie 	= name + '='; //Set name
	myCookie		+= escape( value ); // Set value 
	myCookie		+= ( ( expires ) ? ';expires=' + expiresDate.toGMTString() : '' ) ; //Set expiration
	myCookie		+= ( ( path ) ? ';path=' + path : '' ) ; //Set path
	myCookie		+= ( ( domain ) ? ';domain=' + domain : '' ); //Set domain
	myCookie		+= ( ( secure ) ? ';secure' : '' ); //Set security

	//Set cookie
	document.cookie = myCookie;

}

function getCookie(name) {

   var result 			= '';
   var myCookie 		= ' ' + document.cookie + ';';
   var searchName 		= ' ' + name + '=';
   var startOfCookie 	= myCookie.indexOf(searchName)

   var endOfCookie;

   if (startOfCookie != -1) {
    	// Skip past cookie name
      startOfCookie += searchName.length;
      endOfCookie = myCookie.indexOf(';',startOfCookie);
	  
	  // Capture the string between start of cookie and end of cookie
      result = unescape(myCookie.substring(startOfCookie,endOfCookie));

   }

   	return result;
}

/* Utility Functions */

function $T(tagName) {
	return document.getElementsByTagName(tagName);
}

// Get labels as a hash with 
// the input id as the hash key and the label text as the value
function getLabels() {

	var fieldLabels		= $T('label');
	var labels			= new Hash({ });
	
	for (var i = 0; i < fieldLabels.length; i++) {
		var fieldLabelID	= fieldLabels[i].htmlFor;
		var fieldLabelName	= fieldLabels[i].firstChild.nodeValue;
		labels[fieldLabelID] = fieldLabelName;
	}
	
	return labels;
}

//Returns the true position of a given element
//Requires that the element be passed as $(elmId)
function getXPos(elmId){

	var xPos	= $(elmId).offsetLeft;
	var tempElm	= $(elmId).offsetParent;

	while (tempElm != null) {
		xPos += tempElm.offsetLeft;
		tempElm = tempElm.offsetParent;
	}

	return xPos;

}

function getYPos(elmId){

	var yPos 	= $(elmId).offsetTop;
	var tempElm	= $(elmId).offsetParent;

	while (tempElm != null) {
		yPos += tempElm.offsetTop;
		tempElm = tempElm.offsetParent;
	}
	
	return yPos;
}

//Prompts browser for print dialog box
function printPage() {
	window.print();  
}
