/***********************************************
 ***** FRONT END FUNCTIONALITY ***** 
 **********************************************/

window.onload = function () {
	var anchors = $$('a');
	x = anchors.length;
	var internal = true;
	for (var i=0;i<=x;i++) {
		internal = true;
		if(anchors[i]) {
			file_type = anchors[i].href.substring(anchors[i].href.lastIndexOf(".") + 1);
			if ((anchors[i].href.match('mylibrary.us') || anchors[i].href.match('65.121.241.139') || anchors[i].href.match('hpld')) && (file_type != 'pdf')) {
				internal = false;
			} else if(file_type == 'pdf') {
				internal = true;
			}
			if (internal == true && anchors[i].href != '') {
				anchors[i].target = "_blank";
			} 
		}
	}
}

document.observe('dom:loaded', function() {
	setFormHints();
	externalLinks();
	// check to see if a cookie for text sizing exists
	checkCookie();

	$('text_size').getElementsBySelector('a').each(function(el, index) {
		$(el).observe('click', function(e) {
			e.stop();

			if ($(el).hasClassName('sm')) {				
				document.body.setStyle({fontSize: '8px'});
				setCookie('sm');
			}
			else if ($(el).hasClassName('med')) {
				document.body.setStyle({fontSize: '10px'});
				setCookie('med');
			}
			else if ($(el).hasClassName('lg')) {
				document.body.setStyle({fontSize: '12px'});
				setCookie('lg');
			}
		});
	});
	
	if($('book_roll') != null) {
		var rollingBook;
		$('book_roll').observe('mouseenter', function(event) {
			if(rollingBook == undefined) {
				rollingBook = setInterval(function() {
					if($('book_roll').down(1)) {
						var elm = $('book_roll').down(1);
						var underscore = elm.id.lastIndexOf('_');
						var id = elm.id.substring(underscore + 1);
					}
					new Ajax.Updater('book_roll', 'media/next_hidden_book', {method: 'post', postBody: 'id=' + id});
				}, 2000);
			}

		});

		$('book_roll').observe('mouseleave', function(event) {
			clearInterval(rollingBook);
			rollingBook = undefined;
		});
	}
	
	if($('movie_roll') != null) {
		var rollingMovie;
		$('movie_roll').observe('mouseenter', function(event) {
			if(rollingMovie == undefined) {
				rollingMovie = setInterval(function() {
					if($('movie_roll').down(1)) {
						var elm = $('movie_roll').down(1);
						var underscore = elm.id.lastIndexOf('_');
						var id = elm.id.substring(underscore + 1);
					}
					new Ajax.Updater('movie_roll', 'media/next_hidden_movie', {method: 'post', postBody: 'id=' + id});
				}, 2000);
			}

		});

		$('movie_roll').observe('mouseleave', function(event) {
			clearInterval(rollingMovie);
			rollingMovie = undefined;
		});
	}
	
	if($('wave_close') != null) {
		$('wave_close').observe('click', function(e) {
			e.stop();
			Effect.Fade('wave_content', {duration:0.5});
			$('wave_open').show();
		});
	}

	if($('wave_open') != null) {
		$('wave_open').observe('click', function(e) {
			e.stop();
			Effect.Appear('wave_content', {duration:0.5});
			$('wave_open').hide();
		});
	}
	
	$$('input.form-hint').each(function(elm) {
		// watch for any focus events on the form input
		elm.observe('focus', function() {
			removeFormHint(elm);
		});
		// watch for any blur events on the form input
		elm.observe('blur', function() {
			displayFormHint(elm);
		});
		// watch for any blur events on the form input
		elm.up('form').observe('submit', function() {
			if(elm.value == elm.title) {
				elm.value = '';
			}
		});
		displayFormHint(elm);
	});
	
	$$('a.top-anchor').each(function(el) {
		$(el).observe('click', function(e) {
			e.stop();
			new Effect.ScrollTo('top', {duration:'0.5', offset: 0});
		});
	});
});

Event.observe(window, 'load', function() {
	/* Movie Flow Viewer */
	if (($('movie-flow') !== undefined) && ($('movie-flow') != null)) {
		var head = 0;
		var tail = 0;
		var movieIndex = 1;
		var containerWidth = 0;
		var marginWidth = 0;
		var movies = new Array();
		var anim = false;

		// Calculate actual container width from sum of item width
		$$('div.movie-item').each(function(el, index) {
			movies[index] = new Array();
			movies[index]['el'] = $(el);
			movies[index]['info'] = '';
			movies[index]['img_width'] = $(el).down('img').getWidth();
			movies[index]['img_height'] = $(el).down('img').getHeight();

			if ($(el).down('div.movie-item-info').innerHTML !== '') {
				movies[index]['info'] = $(el).down('div.movie-item-info').innerHTML;
			}

			if (index == movieIndex) {
				var rd = getScaledDim($(el).down('img'), 128, 150, movies[movieIndex]['img_width'], movies[movieIndex]['img_height']);
				new Effect.Scale($(el).down('img'), 100, {scaleFromCenter: true, scaleMode: {originalHeight: rd['height'], originalWidth: rd['width']}});
				$(el).setStyle({paddingTop: '0px'});
				$('movie-flow-caption').update(movies[index]['info']);
			}
			else {
				var rd = getScaledDim($(el).down('img'), 78, 100, 0, 0);
				new Effect.Scale($(el).down('img'), 100, {scaleFromCenter: true, scaleMode: {originalHeight: rd['height'], originalWidth: rd['width']}});
			}

			marginWidth = parseInt($(el).getStyle('marginRight').replace('px', ''));
			containerWidth += $(el).getWidth() + marginWidth;
			
			tail = index;
		});

		$('movie-flow').down('div.flow-wrapper').setStyle({'width': containerWidth + 'px'});
		$('movie-flow').setStyle({'overflowX': 'hidden'});

		// Add navigation elements
		$('movie-flow').insert('<a id="movie-flow-prev" href="#">Prev</a><a id="movie-flow-next" href="#">Next</a>');

		var moviePrevListener = function(e) {
			e.stop();

			if (!anim) {
				anim = true;

				var lm = parseInt($('movie-flow').down('div.flow-wrapper').getStyle('marginLeft').replace('px', ''));
				lm += 130;
					
				// Add element to front
				var mitems = $('movie-flow').down('div.flow-wrapper').childElements();
				mitems[mitems.length-1].remove();
				$('movie-flow').down('div.flow-wrapper').insert({top: movies[tail]['el']});
				lm = 0;
				var slm = -130;
					
				$('movie-flow').down('div.flow-wrapper').setStyle({marginLeft: slm + 'px'});
					
				head--;
				tail--;

				if (head < 0)
					head = movies.length-1;
				if (tail < 0)
					tail = movies.length-1;

				var rd = getScaledDim($(movies[movieIndex]['el']).down('img'), 78, 100, 0, 0);
				$('movie-flow').down('div.flow-wrapper').morph({marginLeft: lm + 'px'}, {duration: 0.7});
				$(movies[movieIndex]['el']).morph({paddingTop: '15px'}, {duration: 0.5, delay: 0.2});
				$(movies[movieIndex]['el']).down('img').morph({width: rd['width'] + 'px', height: rd['height'] + 'px'}, {duration: 0.5, delay: 0.2});

				if (movieIndex == 0)
					movieIndex = movies.length;

				movieIndex--;
				rd = getScaledDim($(movies[movieIndex]['el']).down('img'), 128, 150, movies[movieIndex]['img_width'], movies[movieIndex]['img_height']);
				$(movies[movieIndex]['el']).morph({paddingTop: '0px'}, {duration: 0.5, delay: 0.2});
				$(movies[movieIndex]['el']).down('img').morph({width: rd['width'] + 'px', height: rd['height'] + 'px'}, {duration: 0.5, delay: 0.2});

				$('movie-flow-caption').update(movies[movieIndex]['info']);

				setTimeout(function() {
					anim = false;	
				}, 900);
			}
		}

		var movieNextListener = function(e) {
			e.stop();

			if (!anim) {
				anim = true;

				var lm = parseInt($('movie-flow').down('div.flow-wrapper').getStyle('marginLeft').replace('px', ''));
				lm -= 130;
					
				var rd = getScaledDim($(movies[movieIndex]['el']).down('img'), 78, 100, 0, 0);
				$('movie-flow').down('div.flow-wrapper').morph({marginLeft: lm + 'px'}, {duration: 0.7});
				$(movies[movieIndex]['el']).morph({paddingTop: '15px'}, {duration: 0.5, delay: 0.2});
				$(movies[movieIndex]['el']).down('img').morph({width: rd['width'] + 'px', height: rd['height'] + 'px'}, {duration: 0.5, delay: 0.2});
					
				movieIndex++;
					
				if (movieIndex == movies.length)
					movieIndex = 0;
					
				rd = getScaledDim($(movies[movieIndex]['el']).down('img'), 128, 150, movies[movieIndex]['img_width'], movies[movieIndex]['img_height']);
				$(movies[movieIndex]['el']).morph({paddingTop: '0px'}, {duration: 0.5, delay: 0.2});
				$(movies[movieIndex]['el']).down('img').morph({width: rd['width'] + 'px', height: rd['height'] + 'px'}, {duration: 0.5, delay: 0.2});

				$('movie-flow-caption').update(movies[movieIndex]['info']);

				setTimeout(function() {
					anim = false;
					
					// Add element to front
					var mitems = $('movie-flow').down('div.flow-wrapper').childElements();
					mitems[0].remove();
					$('movie-flow').down('div.flow-wrapper').insert({bottom: movies[head]['el']});
					lm += 130;
					$('movie-flow').down('div.flow-wrapper').setStyle({marginLeft: lm + 'px'});

					head++;
					tail++;

					if (head > movies.length-1)
						head = 0;
					if (tail > movies.length-1)
						tail = 0;
				}, 900);
			}
		}

		$('movie-flow-prev').observe('click', moviePrevListener);
		$('movie-flow-next').observe('click', movieNextListener);
	}

	/* Book Flow Viewer */
	if (($('book-flow') !== undefined) && ($('book-flow') != null)) {
		var bhead = 0;
		var btail = 0;
		var bookIndex = 1;
		var containerWidth = 0;
		var marginWidth = 0;
		var books = new Array();
		var book_anim = false;

		// Calculate actual container width from sum of item width
		$$('div.book-item').each(function(el, index) {
			books[index] = new Array();
			books[index]['el'] = $(el);
			books[index]['info'] = '';
			books[index]['img_width'] = $(el).down('img').getWidth();
			books[index]['img_height'] = $(el).down('img').getHeight();

			if ($(el).down('div.book-item-info').innerHTML !== '') {
				books[index]['info'] = $(el).down('div.book-item-info').innerHTML;
			}

			if (index == bookIndex) {
				var rd = getScaledDim($(el).down('img'), 128, 150, books[bookIndex]['img_width'], books[bookIndex]['img_height']);
				new Effect.Scale($(el).down('img'), 100, {scaleFromCenter: true, scaleMode: {originalHeight: rd['height'], originalWidth: rd['width']}});
				$(el).setStyle({paddingTop: '0px'});
				$('book-flow-caption').update(books[index]['info']);
			}
			else {
				var rd = getScaledDim($(el).down('img'), 78, 100, 0, 0);
				new Effect.Scale($(el).down('img'), 100, {scaleFromCenter: true, scaleMode: {originalHeight: rd['height'], originalWidth: rd['width']}});
			}

			marginWidth = parseInt($(el).getStyle('marginRight').replace('px', ''));
			containerWidth += $(el).getWidth() + marginWidth;
			
			btail = index;
		});

		$('book-flow').down('div.flow-wrapper').setStyle({'width': containerWidth + 'px'});
		$('book-flow').setStyle({'overflowX': 'hidden'});

		// Add navigation elements
		$('book-flow').insert('<a id="book-flow-prev" href="#">Prev</a><a id="book-flow-next" href="#">Next</a>');

		var bookPrevListener = function(e) {
			e.stop();

				if (!book_anim) {
					book_anim = true;

					var lm = parseInt($('book-flow').down('div.flow-wrapper').getStyle('marginLeft').replace('px', ''));
					lm += 130;

					// Add element to front
					var bitems = $('book-flow').down('div.flow-wrapper').childElements();
					bitems[bitems.length-1].remove();
					$('book-flow').down('div.flow-wrapper').insert({top: books[btail]['el']});
					lm = 0;
					var slm = -130;

					$('book-flow').down('div.flow-wrapper').setStyle({marginLeft: slm + 'px'});

					bhead--;
					btail--;

					if (bhead < 0)
						bhead = books.length-1;
					if (btail < 0)
						btail = books.length-1;

					var rd = getScaledDim($(books[bookIndex]['el']).down('img'), 78, 100, 0, 0);
					$('book-flow').down('div.flow-wrapper').morph({marginLeft: lm + 'px'}, {duration: 0.7});
					$(books[bookIndex]['el']).morph({paddingTop: '15px'}, {duration: 0.5, delay: 0.2});
					$(books[bookIndex]['el']).down('img').morph({width: rd['width'] + 'px', height: rd['height'] + 'px'}, {duration: 0.5, delay: 0.2});
					
					if (bookIndex == 0)
						bookIndex = books.length;
						
					bookIndex--;
					
					rd = getScaledDim($(books[bookIndex]['el']).down('img'), 128, 150, books[bookIndex]['img_width'], books[bookIndex]['img_height']);
					$(books[bookIndex]['el']).morph({paddingTop: '0px'}, {duration: 0.5, delay: 0.2});
					$(books[bookIndex]['el']).down('img').morph({width: rd['width'] + 'px', height: rd['height'] + 'px'}, {duration: 0.5, delay: 0.2});

					$('book-flow-caption').update(books[bookIndex]['info']);

					setTimeout(function() {
						book_anim = false;
					}, 900);
				}
		}

		var bookNextListener = function(e) {
			e.stop();

				if (!book_anim) {
					book_anim = true;

					var lm = parseInt($('book-flow').down('div.flow-wrapper').getStyle('marginLeft').replace('px', ''));
					lm -= 130;

					var rd = getScaledDim($(books[bookIndex]['el']).down('img'), 78, 100, 0, 0);
					$('book-flow').down('div.flow-wrapper').morph({marginLeft: lm + 'px'}, {duration: 0.7});
					$(books[bookIndex]['el']).morph({paddingTop: '15px'}, {duration: 0.5, delay: 0.2});
					$(books[bookIndex]['el']).down('img').morph({width: rd['width'] + 'px', height: rd['height'] + 'px'}, {duration: 0.5, delay: 0.2});
				
					bookIndex++;

					if (bookIndex == books.length)
						bookIndex = 0;
				
					rd = getScaledDim($(books[bookIndex]['el']).down('img'), 128, 150, books[bookIndex]['img_width'], books[bookIndex]['img_height']);
					$(books[bookIndex]['el']).morph({paddingTop: '0px'}, {duration: 0.5, delay: 0.2});
					$(books[bookIndex]['el']).down('img').morph({width: rd['width'] + 'px', height: rd['height'] + 'px'}, {duration: 0.5, delay: 0.2});

					$('book-flow-caption').update(books[bookIndex]['info']);

					setTimeout(function() {
						book_anim = false;
						
						// Add element to front
						var bitems = $('book-flow').down('div.flow-wrapper').childElements();
						bitems[0].remove();
						$('book-flow').down('div.flow-wrapper').insert({bottom: books[bhead]['el']});
						lm += 130;
						$('book-flow').down('div.flow-wrapper').setStyle({marginLeft: lm + 'px'});

						bhead++;
						btail++;

						if (bhead > books.length-1)
							bhead = 0;
						if (btail > books.length-1)
							btail = 0;
				
					}, 900);
				}
			}

		$('book-flow-prev').observe('click', bookPrevListener);
		$('book-flow-next').observe('click', bookNextListener);
	}
});

function getScaledDim(img, maxw, maxh, natw, nath) {		
	var w = $(img).getWidth();
	var h = $(img).getHeight();

	if (natw > 0)
		w = natw;

	if (nath > 0)
		h = nath;

	var dims = new Array(); 
	dims['width'] = w;
	dims['height'] = h;

	if (w > maxw || h > maxh) {
		var ratio;

		if (w > h) {
			ratio = maxw / w;
		}
		else if (h > w) {
			ratio = maxh / h;
		}
		else {
			ratio = maxw / w;
		}

		dims['width'] = Math.round(w * ratio);
		dims['height'] = Math.round(h * ratio);
	}

	return dims;
}

/*
 * Function for sending email address to newsletter signup
 */
function enewsSignup() {
	if(/\w{1,}[@][\w\-]{1,}([.]([\w\-]{1,})){1,3}$/.test($F('enews_email'))) {
		new Ajax.Request('/announcements/signup', {method: 'post', postBody: 'value=' + $F('enews_email'), onSuccess: function(transport) {
			$('enews_email').value = transport.responseText;
		}});
	}
}

function selectSearch(id) {
	$('search_switcher').getElementsBySelector('a').each(function(elm) {
		elm.className = '';
	});
	$(id).className = 'selected';
	$('search_type').value = $(id).id;
}

function externalLinks() {  
	var anchors = $$('a[rel="external"]').each(function(elm) { 
		elm.target = "_blank"; 
	});  
}  

// set cookie for text sizing functionality
function setCookie(size) {
	var expireDate= new Date();
	var theyear = expireDate.getFullYear()+2;
	var themonth = expireDate.getMonth();
	var thetoday = expireDate.getDate();	
	expireDate.setTime(expireDate.getTime ()+(expireDate));
	
	var expires = "; expires="+expireDate.toGMTString();
	document.cookie = 'textSize=' + size + expires;
}

function readCookie(name) {  
    var cookiename = name + "=";  
    var ca = document.cookie.split(';');  
    for(var i=0;i < ca.length;i++) {  
        var c = ca[i];  
        while (c.charAt(0)==' ') 
			c = c.substring(1,c.length);  
        	if (c.indexOf(cookiename) == 0) 
				return c.substring(cookiename.length,c.length);  
    }  
}

function checkCookie() {
	if(readCookie('textSize') != undefined) {
		if(readCookie('textSize') == 'sm') {
			document.body.setStyle({fontSize: '8px'});
		} else if(readCookie('textSize') == 'med') {
			document.body.setStyle({fontSize: '10px'});
		} else if(readCookie('textSize') == 'lg') {
			document.body.setStyle({fontSize: '12px'});
		}
	}
}

/*
 * Functions for building, setting and removing form hints
 */
function setFormHints() {
	// loop through all form input elements where class="form-hint"
	$$('input.form-hint').each(function(elm) {
		// watch for any focus events on the form input
		elm.observe('focus', function() {
			removeFormHint(elm);
		});
		// watch for any blur events on the form input
		elm.observe('blur', function() {
			displayFormHint(elm);
		});
		// watch for any blur events on the form input
		elm.up('form').observe('submit', function() {
			if(elm.value == elm.title) {
				elm.value = '';
			}
		});
		displayFormHint(elm);
	});
}

function removeFormHint(elm) {
	// if the value of the field is equal to the title, then we need to clear it and set the styling.
	if((elm.value == elm.title) || (elm.value == 'Thank you and enjoy the newsletter!')) {
		elm.value = "";
		elm.style.color = "#666666";
	}
}

function displayFormHint(elm) {
	// if the value of the filed is empty then set it to the form hint (the title).
	if(elm.value == "") {
		elm.value = elm.title;
		elm.style.color = "#666666";
	} else if (elm.value == elm.title) {
		elm.style.color = "#666666";
	}
}
