//Insert Logo and Hide it specifically for Print Stylesheet
function printLogo(){
	var logoHeader = $('header');
	
	var imgSrc = ('/images/EntrepreneurshipOrg/global/logo.gif');
	var imgWidth = 280;
	var imgHeight = 84;
	var imgAlt = ('Entrepreneurship.org');
	
	var imageContainer = new Element('img');
	imageContainer.writeAttribute('src', imgSrc);
	imageContainer.writeAttribute('alt', imgAlt);
	imageContainer.writeAttribute('width', imgWidth);
	imageContainer.writeAttribute('height', imgHeight);	
	imageContainer.addClassName('hide');
	
	logoHeader.insert({top: imageContainer});
}

function globalSearch() {
    var searchBoxes = $$('#header fieldset.globalSearch');

    searchBoxes.each(function(searchBox) {
        var searchInput = searchBox.down('label').down('input');
        var searchSubmit = searchBox.down('label').next('label').down('input');

        
        searchSubmit.observe('click', function(event) {
        if (searchInput.getValue() == 'Enter Keywords' || searchInput.getValue() == '') {
                event.stop();
                return false;
            }

            document.location.href = '/en/Search.aspx?q=' + searchInput.getValue();
            event.stop();
        });
    });
}

//Twitter Feed Handler
//JSON Ajax Reader
function jsonFeed() {
	var twitterContainers = $$('div.twitterFeed', 'div.twitterFeedMedical');
	
	if(!twitterContainers[0]) return false;
	
	if(twitterContainers[0].hasClassName('twitterFeedMedical')){
		//alert('medical tweet');
		var postCount = twitterContainers[0].down('code').innerHTML;
		//alert(postCount);
		twitterContainers[0].down('code').remove();
		
		twitterContainers.each(function(twitterContainer){
			var currentTweet = 0;
			
			//Below is what needs to be created on the back in as a proxy/cache for the actual feed so we 
			//don't hit the limits twitter has imposed on json feeds. (150 requests a minute)
			//var url = 'http://api.twitter.com/1/statuses/user_timeline.json?user=creativeplay';
			//var url = '/themes/cpp/scripts/user_timeline.js';
			var twitterUL = new Element('ul');
			
			twitterContainer.insert({
				bottom: twitterUL
			});

			var url = '/Proxy/Twitter.aspx?req=http://api.twitter.com/1/statuses/user_timeline.json?user=emedcommunity'
			
			//new Ajax.PeriodicalUpdater(twitterContainer, url, {frequency: 2, decay: 2})
			
			//The initial loading of the latest twitter post
			new Ajax.Request(url, {
				  method: 'get',
				  onSuccess: function(transport) {
					var json = transport.responseText.evalJSON();
					
					json.each(function(tweet, index){
						if(index > (postCount - 1)){
							tweet.remove();
						} 
							
						//currentTweet = tweet.text;
						
						var username = tweet.user.screen_name
						var created = tweet.created_at.truncate(20, '.');

						var tweetID = tweet.id
						var tweetURL = "http://www.twitter.com/" + username + "/status/" + tweetID + ""
						var tweetTime = tweet.created_at
						
						tweetTime = tweetTime.truncate(10, '');
						
						var tweetAnchor = new Element('a', { href: tweetURL}).update("Latest Tweet");
						
						var profileURL = "http://www.twitter.com/" + username + "/"
											
						//Regex magic that goes through each tweet looking for properly made URLs and turns them into links.
						function urlify(text) {
							var urlRegex = /(https?:\/\/[^\s]+)/g;
							return text.replace(urlRegex, function(url) {
								return '<a href="' + url + '" title="Visit ' + url + '" target="_blank">' + url + '</a>';
							});
						}
						
						var tweetURLified = urlify(tweet.text); //Tell the urlifier to process the tweet's text
						
						var tweetTemplate = new Template('<li>&quot;'+ tweetURLified + '&quot;<p><a href="' + profileURL + '" target="_blank">' + tweetTime + '</a></p></li>');
										
						twitterUL.insert({
							bottom: tweetTemplate.evaluate(tweet)
						});	

					});
					
			  },
			  onFailure: function(){
				//If the feed fails, this is what they should see.
				var failureMessage = '<p>It appears our twitter stream is temporarily unavailable.</p><p><a href="https://twitter.com/signup?follow=creativeplay&commit=Join+Today" target="_blank">Please click here to visit our feed at Twitter</a>, or try again later.</p>'
				twitterContainer.insert({
					bottom: failureMessage
				});
			  }
			  
			  
			});
			
		});
		
	} else {
		twitterContainers.each(function(twitterContainer){
			var currentTweet = 0;
			
			//Below is what needs to be created on the back in as a proxy/cache for the actual feed so we 
			//don't hit the limits twitter has imposed on json feeds. (150 requests a minute)
			//var url = 'http://api.twitter.com/1/statuses/user_timeline.json?user=creativeplay';
			//var url = '/themes/cpp/scripts/user_timeline.js';
			var twitterUL = new Element('ul');
			
			twitterContainer.insert({
				bottom: twitterUL
			});
			
			var url = '/Proxy/Twitter.aspx?req=http://api.twitter.com/1/statuses/user_timeline.json?user=ThomAtKauffman'
			
			//new Ajax.PeriodicalUpdater(twitterContainer, url, {frequency: 2, decay: 2})
			
			//The initial loading of the latest twitter post
			new Ajax.Request(url, {
				  method: 'get',
				  onSuccess: function(transport) {
					var json = transport.responseText.evalJSON();
					
					json.each(function(tweet, index){
						if(index > 2){
							tweet.remove();
						} 
							
						//currentTweet = tweet.text;
						
						var username = tweet.user.screen_name
						var created = tweet.created_at.truncate(20, '.');

						var tweetID = tweet.id
						var tweetURL = "http://www.twitter.com/" + username + "/status/" + tweetID + ""
						var tweetTime = tweet.created_at
						
						tweetTime = tweetTime.truncate(10, '');
						
						var tweetAnchor = new Element('a', { href: tweetURL}).update("Latest Tweet");
						
						var profileURL = "http://www.twitter.com/" + username + "/"
											
						//Regex magic that goes through each tweet looking for properly made URLs and turns them into links.
						function urlify(text) {
							var urlRegex = /(https?:\/\/[^\s]+)/g;
							return text.replace(urlRegex, function(url) {
								return '<a href="' + url + '" title="Visit ' + url + '" target="_blank">' + url + '</a>';
							});
						}
						
						var tweetURLified = urlify(tweet.text); //Tell the urlifier to process the tweet's text
						
						var tweetTemplate = new Template('<li>&quot;'+ tweetURLified + '&quot;<p><a href="' + profileURL + '" target="_blank">' + tweetTime + '</a></p></li>');
										
						twitterUL.insert({
							bottom: tweetTemplate.evaluate(tweet)
						});	

					});
					
			  },
			  onFailure: function(){
				//If the feed fails, this is what they should see.
				var failureMessage = '<p>It appears our twitter stream is temporarily unavailable.</p><p><a href="https://twitter.com/signup?follow=creativeplay&commit=Join+Today" target="_blank">Please click here to visit our feed at Twitter</a>, or try again later.</p>'
				twitterContainer.insert({
					bottom: failureMessage
				});
			  }
			  
			  
			});
			
		});
	}	
	
}
//Print Button
//Looks for anchors with the 'print' class
//Adds a hook of window.print to allow for print functionality. 
function printPage() {
	var printButtons = $$('a.print');
	
	if(!printButtons){
		return false;
	}
	
	printButtons.each(function(printButton){
		printButton.observe('click', function(event){
			window.print();
			event.stop();
		});
	});	
}

//Rating List Module
//Adds functionality to an unordered list of numbers
//for rating items in a Sitecore tree via AJAX.
function ratingList(){
	var ratingLists = $$('ul.rating');
	
	ratingLists.each(function(ratingList){
		
		var ratingListItems = ratingList.select('li');
	
		ratingListItems.each(function(ratingListItem, index){
			var itemID = ratingList.previous('dfn').readAttribute('id');
			itemID = itemID.sub('}', '');
			itemID = itemID.sub('{', '');
			
			var ratingMessage = ratingList.previous('dfn');
			
			ratingListItem.observe('mouseenter', function(event){
				var previousSiblings = ratingListItem.previousSiblings();
				ratingListItem.addClassName('ratingSelected');
				previousSiblings.each(function(previousSibling){
					previousSibling.addClassName('ratingSelected');
				});
			});
			
			ratingListItem.observe('mouseleave', function(event){
				var previousSiblings = ratingListItem.previousSiblings();
				ratingListItem.removeClassName('ratingSelected');
				previousSiblings.each(function(previousSibling){
					previousSibling.removeClassName('ratingSelected');
				});
			});
			
			ratingListItem.observe('click', function(event){
				var selectedRating = index + 1;
				updateRating(itemID, selectedRating, ratingMessage, ratingListItems);
			});
			
		});
	
	});
	
	function updateRating(itemID, selectedRating, ratingMessage, ratingListItems){
		var cookie = readCookie('ratedItems');
		var ratingListItems = ratingListItems;
		
		if(cookie != null && cookie.include(itemID)){
			ratingMessage.update('<strong>Already Rated</strong>');
		}
		else {
			var url = '/api/item.aspx?item={'+itemID+'}&'+'rating='+selectedRating;
			ratingMessage.update('<strong>Sending rating...</strong>');
			
			new Ajax.Request(url, {
				method: 'post',
				onSuccess: function(transport) {
					readRating(itemID, ratingMessage, ratingListItems);
				}
			});
		}
	}
	
	function readRating(itemID, ratingMessage, ratingListItems){
		var url = '/api/item.aspx?item='+itemID;
		var ratingListItems = ratingListItems;
		
		new Ajax.Request(url, {
			method: 'get',
			evalJSON: 'force',
			onSuccess: function(transport) {
				
				var currentRating = transport.responseJSON.Fields['Rating Total']/transport.responseJSON.Fields['Rating Count'];
				//console.log(currentRating);
				//console.log(ratingListItems);
				ratingListItems.each(function(ratingListItem){
					ratingListItem.removeClassName('rated');
				});
				
				var previousSiblings = ratingListItems[currentRating.floor()].previousSiblings();
				//console.log(previousSiblings);
				previousSiblings.each(function(previousSibling){
					previousSibling.addClassName('rated');
				});
				
				//console.log(ratingMessage);
				ratingMessage.update('Rating <strong>Posted</strong>');
				
				var cookie = readCookie('ratedItems');
				setCookie('ratedItems', cookie + ':' + itemID);
			}
		});
	}
}

//Columned List Sort Utility
//Properly reorganizes a list to allow for columns
function listSorter(list, columns) {
	var numColumns = columns;
	var listItems = list.childElements();
	
	var totalItems = listItems.size();
	
	var sortedItems = [];
	
	var numRows = totalItems / numColumns;
	numRows = numRows.ceil();
	
	numRows.times(function(n){
		var sortedRow = [];
	
		numColumns.times(function(m){
			var listNumerator = n + (m * numRows);
			
			if(listItems[listNumerator]){
				sortedRow[m] = listItems[listNumerator];
			}
		});
		
		sortedItems[n] = sortedRow;
	});
		
	sortedItems = sortedItems.flatten();
		
	sortedItems.each(function(sortedItem){
		list.insert({
			bottom: sortedItem
		});
	});
	
	return sortedItems;
}

//Height Balance
//Normalizes the height of the elements passed in,
//based on the number of columns desired
function heightBalance(balanceElements, columns){
	balanceElements.eachSlice(columns, function(balanceElementSlice){
		var sliceHeight = balanceElementSlice.max(function(sliceElement){
			return sliceElement.getHeight();
		});
		
		balanceElementSlice.each(function(balanceElement){
			balanceElement.setStyle({
				height: sliceHeight + 'px'
			});
		});
	});
}

//Category Assist
//Organizes and adjusts heights of category listings
//Example: Biz Connect Directory
function categoryAssist() {
	var categoryLists = $$('#article ul.categories');
	
	categoryLists.each(function(categoryList){
		listSorter(categoryList, 2);

		var balanceElements = categoryList.childElements();	
		heightBalance(balanceElements, 2);
	});
	
	categoryLists = $$('#media ul.categories, #main #article ul.listing');
	
	categoryLists.each(function(categoryList){
		var balanceElements = categoryList.childElements();	
		heightBalance(balanceElements, 4);
	});
}

// Tab Switch Views
// Used to switch from List to Map view
function switchViews(){
	var menuTabs = $$('ul.tabs li');
	var menuViews = $$('div.view');
	
	var windowLocation = window.location.pathname;
	
	var currentView = readCookie('currentTab' + windowLocation);
	if(currentView != null){
		
	}
	else {
		currentView = 0;
	}
	
	menuViews.each(function(menuView, index){
		if(index == currentView){
			menuTabs[currentView].toggleClassName('current');
		}
		else {
			menuView.addClassName('hidden');
		}
	});
	
	menuTabs.each(function(menuTab, index){
		menuTab.observe('click', function(event){
			menuViews[index].fire('kauffman:swapView', { tabIndex: index });
		});
	});
		
	document.observe('kauffman:swapView', function(event){
		var newIndex = event.memo.tabIndex;
		menuTabs[currentView].toggleClassName('current');
		menuViews[currentView].addClassName('hidden');
		
		currentView = newIndex;
		setCookie('currentTab' + windowLocation, currentView);
		menuTabs[currentView].toggleClassName('current');
		menuViews[currentView].removeClassName('hidden');
	});

//	$('interactiveMapView').removeClassName("hidden");
//	$('listViewTab').removeClassName("current");
//	$('listView').addClassName("hidden");
//	$('mapViewTab').addClassName("current");
//		
//	// if map view tab is clicked, reset and hide list view
//	$('mapViewTab').observe("click", function(evt){
//		$('interactiveMapView').removeClassName("hidden");
//		$('listViewTab').removeClassName("current");
//		$('listView').addClassName("hidden");
//		$('mapViewTab').addClassName("current");
//	});
//	
//	// if list view tab is clicked, reset and hide map view
//	$('listViewTab').observe("click", function(evt){
//		$('listView').removeClassName("hidden");
//		$('mapViewTab').removeClassName("current");
//		$('interactiveMapView').addClassName("hidden");
//		$('listViewTab').addClassName("current");
//	});
};


//Signature Fixes
function signatureAssist() {
	var signatures = $$('#sigList');
	
	if(!signatures) return false;
	
	signatures.each(function(signature){
		listSorter(signature, 4);

		var balanceElements = signature.childElements();	
		heightBalance(balanceElements, 2);
	});
	
	
}

//Carousel Controls
//Rotates through UL.carousel and gives control and updates OL.carousel
function carousel() {
	var items = $$('ul.carousel li'); //Array of carousel list items
	//var controls = $$('ol.navCarousel li'); //Array of carousel controls
	
	if(!items[0]) return false; //Let's check to be sure this exists
	
	//fix buttons 
	var carouselButtons = $$('ul.carousel li a.button');
	carouselButtons.each(function(button){
		var buttonWidth = button.getWidth();
		//console.log(buttonWidth);
		var carouselButtonCap = new Element('span').addClassName('button');
		var carouselItem = button.previous('p');
		carouselButtonCap.setStyle({
			width: (buttonWidth + 62) + 'px'
		});
		carouselButtonCap.insert({
			top: button 
		});
		
		carouselItem.insert({
			bottom: carouselButtonCap 
		});
		
		
	});
	
	var controlsContainer = new Element('ol');
	var controls = [];
	controlsContainer.addClassName('navCarousel');

	var queue = Effect.Queues.get('carouselQueue'); //create the queue for the animation sequence.
	
	items.each(function(item, index) {
		if(item.empty()){
			item.remove();
		}
		if(index != 0){
			item.setOpacity(0);
		}
		
		controls[index] = new Element('li');
		controls[index].update('Slide ' + index);
		
		controls[index].observe('click', function(event){
			controls[index].fire('kauffman:carouselUpdate', { indexMove: -(index - currentItem) });
			carousel.stop();
			event.stop();
		});
		
		controlsContainer.insert({
			bottom: controls[index]
		}); 
	});
	
	items[0].up('ul').insert({
		after: controlsContainer
	});
	
	var items = $$('ul.carousel li'); //we've removed empties, now redefine variable correctly.
	
	var currentItem = 0; //We need to make sure our current items starts with the 1st, ala the 0
	
	var previousItem = items.size(); //Previous item is the last one, grabbing the total amount tells us what # that is.
	
	controls[currentItem].addClassName('current'); //Add a current class to the active items specific control
	
	document.observe('kauffman:carouselUpdate', function(event){ 
		if(queue.effects.size() == 0) {
			
			controls[currentItem].removeClassName('current'); //Remove the class from the previous items control.
			var itemMove = event.memo.indexMove;
			
			previousItem = currentItem;
			currentItem = (items.size() + ((currentItem - itemMove) % items.size())) % items.size(); //incrementally step up the index
			
			if(previousItem == currentItem){ //Stops the user from choosing the already current item twice.
				controls[currentItem].addClassName('current');
				return false;
			}
			
			new Effect.Parallel([new Effect.Opacity(items[previousItem], {
				from: 1,
				to: 0,
				duration: 1,
				afterFinish: function(){
								items[previousItem].setStyle({
									left: '-999em',
									zIndex: '0'
								});							
							}
			}), new Effect.Opacity(items[currentItem], {
				from: 0,
				to: 1,
				duration: 1,
				beforeStart: function(){
								items[currentItem].setStyle({
									left: '0',
									zIndex: '1000'
								});	
				}
			})], {
				queue: {
					position: 'end',
					scope: 'carouselQueue',
					limit: 2
				}
			});
			
			controls[currentItem].addClassName('current');
			
		};
		
	});
	
	carousel = new PeriodicalExecuter(function(){
		controls[currentItem].fire('kauffman:carouselUpdate', { indexMove: -1 });
	}, 8);
	 
}

//Carousel Controls
//Rotates through UL.carousel and gives control and updates OL.carousel
function newsCarousel() {
	var items = $$('dl.carousel dt'); //Array of carousel list items
	//var controls = $$('ol.navCarousel li'); //Array of carousel controls
	
	if(!items[0]) return false; //Let's check to be sure this exists
	
	items.each(function(item, index){
		if(index%2 != 0){
			items[index] = null;
		}
	});
	
	items = items.compact();
	
	items.each(function(item, index){
		item.addClassName('marked');
		if (index > 0) {
			item.setStyle({
				position: 'relative',
				left: '540px'
			});
			item.hide();
			(3).times(function(index){
				if (item.next(index)) {
					/*item.next(index).setOpacity(0);*/
					item.next(index).setStyle({
						position: 'relative',
						left: '540px'
					});
					item.next(index).hide();
				}
			});
		}
	});
	
	var controlsContainer = new Element('ol');
	var controls = [];
	controlsContainer.addClassName('navCarousel');

	var queue = Effect.Queues.get('newsCarouselQueue'); //create the queue for the animation sequence.
	
	controls[0] = new Element('li');
	controls[0].update('Slide 1');
	
	controlsContainer.insert({
		bottom: controls[0]
	});

	controls[1] = new Element('li');
	controls[1].update('Slide 2');
	
	controlsContainer.insert({
		bottom: controls[1]
	});
	
	controls.each(function(control, index){
		control.observe('click', function(event){
			control.fire('kauffman:newsCarouselUpdate', { indexMove: -(2*index - 1), direction: index });
			//carousel.stop();
			event.stop();
		});
	});
	
	items[0].up('dl').insert({
		after: controlsContainer
	});
	
	var currentItem = 0; //We need to make sure our current items starts with the 1st, ala the 0
	
	var previousItem = items.size(); //Previous item is the last one, grabbing the total amount tells us what # that is.
	
	controls[currentItem].addClassName('current'); //Add a current class to the active items specific control
	
	document.observe('kauffman:newsCarouselUpdate', function(event){ 
		if(queue.effects.size() == 0) {
			
			var itemMove = event.memo.indexMove;
			var itemDirection = event.memo.direction;
			
			previousItem = currentItem;
			currentItem = (items.size() + ((currentItem - itemMove) % items.size())) % items.size(); //incrementally step up the index
			
			var itemsToTransition = [];
			var itemTracker;
			
			itemsToTransition[0] = items[previousItem];
			itemTracker = items[previousItem];
			
			(3).times(function(index){
				if(itemTracker.next(index)){
					itemsToTransition[index + 1] = itemTracker.next(index);
				}
			});
			//console.log(itemsToTransition);
			
			var parallelEffects = [];
			itemsToTransition.each(function(itemToTransition, index){
				parallelEffects[index] = new Effect.Move(itemToTransition, {
					x: itemMove * 540,
					y: 0,
					mode: 'relative',
					duration: 1,
					sync: true,
					afterFinish: function(){
						itemToTransition.hide();				
					}
				});
			});
			
			new Effect.Parallel(parallelEffects, {
				queue: {
					position: 'end',
					scope: 'navCarouselQueue'
				}
			});
			
			//console.log('Here we are');
			
			var parallelEffects = [];
			itemsToTransition.clear();
			itemsToTransition[0] = items[currentItem];
			itemTracker = items[currentItem];
			
			(3).times(function(index){
				if(itemTracker.next(index)){
					itemsToTransition[index + 1] = itemTracker.next(index);
				}
			});
			//console.log(itemsToTransition);
			
			itemsToTransition.each(function(itemToTransition, index){
				itemToTransition.setStyle({
					left: -itemMove * 540 + 'px'
				});
				parallelEffects[index] = new Effect.Move(itemToTransition, {
					x: itemMove * 540,
					y: 0,
					mode: 'relative',
					duration: 1,
					sync: true,
					beforeStart: function(){
						window.setTimeout(function() {
							itemToTransition.show();
						}, 1200);
					}
				})
			});
			
			new Effect.Parallel(parallelEffects, {
				queue: {
					position: 'end',
					scope: 'navCarouselQueue'
				}
			});
		};
		
	});
	
	/*carousel = new PeriodicalExecuter(function(){
		controls[currentItem].fire('parker:carouselUpdate', { indexMove: -1 });
	}, 10);*/
	
}

//Carousel Event Tracking
//Tracks both main carousel and news carousel items event click.

function carouselTracking (){
	var highlightCarousels = $$('ul.carousel li');
	var newsCarousels = $$('dl.carousel dt');
	
	
	if(!highlightCarousels[0]) return false;
	//console.log(carousels);
	
	highlightCarousels.each(function(highlightCarousel,index){
		carouselLinks = highlightCarousel.select('a');
		
		carouselLinks.each(function(carouselLink){
			carouselLink.observe('click', function(event){
				var trackCategory = '';
				var trackAction = '';
				var trackLabel = '';
				
				var trackCategory = 'Home Highlight Carousel';
				
				var trackAction = 'Link from Frame: ' + (index+1);
								
				var trackLabel = carouselLink.readAttribute('title') + ' @ ' + carouselLink.readAttribute('href');
				
				/*console.log('tracking category:', trackCategory);
				console.log('tracking action:', trackAction);
				console.log('tracking label:', trackLabel);*/
				
				
				//event.stop();
				
				carouselLink.fire('kauffman:trackEvent', { 
					trackingCategory: trackCategory,
					trackingAction: trackAction,
					trackingLabel: trackLabel
				});
			});
		});
	});
	
	newsCarousels.each(function(newsCarousel,index){
		carouselLinks = newsCarousel.select('a');
		
		carouselLinks.each(function(carouselLink){
			carouselLink.observe('click', function(event){
				var trackCategory = '';
				var trackAction = '';
				var trackLabel = '';
				
				var trackCategory = 'News Carousel';
				
				var trackAction = 'Link from Frame: ' + (index+1);
								
				var trackLabel = carouselLink.readAttribute('title') + ' @ ' + carouselLink.readAttribute('href');
				
				/*console.log('tracking category:', trackingCategory);
				console.log('tracking action:', trackingAction);
				console.log('tracking label:', trackingLabel);*/
				
				
				//event.stop();
				
				carouselLink.fire('kauffman:trackEvent', { 
					trackingCategory: trackCategory,
					trackingAction: trackAction,
					trackingLabel: trackLabel
				});
			});
		});
	});
	
	
	document.observe('kauffman:trackEvent', function(event){
		//console.log('test');
		trackingCategory = event.memo.trackingCategory;
		trackingAction = event.memo.trackingAction;
		trackingLabel = event.memo.trackingLabel;
		//alert(trackingCategory);
		//alert(trackingAction);
		//alert(trackingLabel);
		_gaq.push(['_trackEvent', trackingCategory, trackingAction, trackingLabel]);
		//pageTracker._trackEvent(trackingCategory, trackingAction, trackingLabel);
		//console.log('pageTracker._trackEvent('+trackingCategory+', '+trackingAction+', '+trackingLabel+');');
	});
}


//Footer Padding Corrector
//Adjust the footer padding for the browser size
function positionElements() {
	var docFooter = $('footer');
	
	var viewportDimensions = document.viewport.getDimensions();
	
	docFooter.setStyle({
		padding: '0 ' + (viewportDimensions.width - 932)/2 + 'px',
		width: viewportDimensions.width - (viewportDimensions.width - 932) + 'px'
	});

}

//Google Maps Replacement
//Replaces static image maps on the site with dynamic Google Maps
function googleMapReplacement(){
	var googleMaps = $$('img.map');
	
	googleMaps.each(function(googleMap){
		//console.log('Map Replacing');
		var imageURL = googleMap.src;
		var imageParams = imageURL.toQueryParams();
		
		var eventLocation = 'Event Location';
		
		//console.log(imageParams.center);
		
		var latlng = new google.maps.LatLng(40.718217,-73.998284);
	    var myOptions = {
	      zoom: 14,
	      center: latlng,
	      mapTypeId: google.maps.MapTypeId.ROADMAP,
		  mapTypeControl: false
	    };
		
		var mapElement = new Element('div');
		mapElement.addClassName('map');
		mapElement.setStyle({
			width: googleMap.getWidth() + 'px',
			height: googleMap.getHeight() + 'px'
		});
		
		googleMap.insert({
			after: mapElement
		});
	    var map = new google.maps.Map(mapElement, myOptions);

		var marker = new google.maps.Marker({
			position: latlng, 
			map: map, 
			title: eventLocation
		});
		
		if(googleMap.previous('dl').down('dd.location')){
			//console.log('Map Window Loading');
			var eventInfo = googleMap.previous('dl').down('dd.location').innerHTML;
			
			var infowindow = new google.maps.InfoWindow({
			    content: eventInfo
			});

			infowindow.open(map,marker);
			google.maps.event.addListener(marker, 'click', function() {
			  infowindow.open(map,marker);
			});
		}
		
		marker.setMap(map);
		googleMap.remove();

	});
}

//Hover Fixes
//Adds the hover class to hoverable elements
function hoverFix(){
	var hoverElements = $$('ul.sortOptions > li:first-child, ul#navMain > li');
	
	if(!hoverElements[0]) return false;
	
	hoverElements.each(function(hoverElement){
	
	if(!hoverElement.down('ul')) return false; //Check to see if there are children to show
	
		hoverElement.observe('mouseenter', function(event){
			hoverElement.addClassName('hover');
			hoverElement.down('ul').setStyle({
				left: 'auto'
			});
		});
		hoverElement.observe('mouseleave', function(event){
			hoverElement.removeClassName('hover');
			hoverElement.down('ul').setStyle({
				left: '-999em',
				position: 'absolute'
			});
		});
	});
}

//Hover Fixes for Media Tool
//Adds the hover class to hoverable elements
function mediahoverFix(){
	var hoverElements = $$('.e360tv ul.categories > li');
	
	if(!hoverElements[0]) return false;
	
	hoverElements.each(function(hoverElement){
	
	/*	hoverElement.down('a').observe('click', function(event){
			event.stop();
		});
	*/
	
	if(!hoverElement.down('ul').down('li')) return false; //Check to see if there are children to show
	
		hoverElement.observe('mouseenter', function(event){
			hoverElement.addClassName('hover');
		});
		hoverElement.observe('mouseleave', function(event){
			hoverElement.removeClassName('hover');
		});
		hoverElement.down('a').observe('click', function(event){
			event.stop();
		});
	});
}

//First and Last LI Selector
//Note: Prototype Driven
function liFirstLast() {
    var firstLIs = $$('ul > li:first-child, ol > li:first-child');
    var lastLIs = $$('ul > li:last-child, ol> li:last-child');
	
	var secondLIs = $$('ul.categories > li:nth-child(2)');
	var thirdLIs = $$('ul > li:nth-child(3)');
	var fourthLIs = $$('ul.categories > li:nth-child(4)');

    firstLIs.each(function(liFirst) {
        liFirst.addClassName('first');
    });

    lastLIs.each(function(liLast) {
        liLast.addClassName('last');
    });

    thirdLIs.each(function(liThird) {
        liThird.addClassName('third');
    });
	//All this to get a lowercase e in the navMain.
	//Cufon.set('fontFamily', 'Helvetica Neue Condensed').replace('#header ul#navMain > li > a', {hover: true});
	
	if(!secondLIs[0]){ return false }

    secondLIs.each(function(liSecond) {
        liSecond.addClassName('second');
    });

    fourthLIs.each(function(liFourth) {
        liFourth.addClassName('fourth');
    });
	

}

//Secondary Navigation Handler
//Note: Hides and shows navigation sub lists.
//Special case for eLaw Page that shows the automatically opens the first two.
function navHandler() {
	var navSecondary = $('navSecondary');
	var viewport = $('viewport');
	var navItems = $$('ul#navSecondary li ul');
	
	//console.log(navSecondary);
	//console.log(navItems);
	if(!navItems) return false;	//Let's check to be sure this exists
	
//	if(viewport.hasClassName('elaw')){
//		//console.log('elawed');
//		
//		navItems.each(function(navItem, index){
//			navItems[0].addClassName('open');
//			navItems[1].addClassName('open');
//			navItems[0].up('li').addClassName('open');
//			navItems[1].up('li').addClassName('open');
//			navItem.up('li').down('a').observe('click', function(event){
//				navItem.toggleClassName('open');
//				navItem.up('li').toggleClassName('open');
//				event.stop();
//			});
//			
//		});
//	} else {
		//console.log('not elawed');
		navItems.each(function(navItem, index){
			navItem.up('li').down('a').observe('click', function(event){
				navItem.toggleClassName('open');
				navItem.up('li').toggleClassName('open');
				event.stop();
			});
			
		});
//	}
}

//External Link Helper
//Updates Links with External Relation to
//use target="_blank"
function externalLinks(){
	var links = $$('a[rel=external]');
	
	links.each(function(externalLink){
		externalLink.writeAttribute('target', '_blank');
	});
}

//Input Clear
//Clears text inputs on a page on focus
//Note: Prototype driven
function inputClear() {
	var textInputs = $$('input[type="text"], textarea');
	
	textInputs.each(function(textInput){
		textInput.initialValue = textInput.value;
		textInput.observe('focus', function(event) {
//			if(textInput.value == textInput.initialValue){
//				textInput.clear();
//			}
			textInput.addClassName('active');
			if(textInput.previous('dfn')){
				textInput.previous('dfn').setStyle({color: '#000'});
			}	
		});
		textInput.observe('blur', function(event){
//			if(textInput.value.blank() == true) {
//				textInput.value = textInput.initialValue;
//			}
			textInput.removeClassName('active');
			if(textInput.previous('dfn')){
				textInput.previous('dfn').setStyle({color: '#6D6D6D'});
			}
		});
		if(textInput.previous('dfn')){
			if(textInput.previous('dfn').getStyle('position') == 'absolute'){
				if (textInput.value.blank() == false) {
					textInput.previous('dfn').hide();
				}
				textInput.observe('focus', function(event) {
					textInput.previous('dfn').hide();
				});
				textInput.observe('blur', function(event){
					if (textInput.value.blank() == true) {
						textInput.previous('dfn').show();
					}
				});
			}
		}
	});
}

//Search Clear
function searchClear() {
	var textInputs = $$('.globalSearch input[type="text"]');
	
	textInputs.each(function(textInput){
		textInput.initialValue = textInput.value;
		textInput.observe('focus', function(event) {
			if(textInput.value == textInput.initialValue){
				textInput.clear();
			}
		});
		textInput.observe('blur', function(event){
			if(textInput.value.blank() == true) {
				textInput.value = textInput.initialValue;
			}
		});
	});

}

//Header Helper
//Adjusts styling on various headings
function headerHelper() {
	var opacityUpdates = $$('.internal #breakout h2 abbr, .internal #breakout h2 em');
	
	if (!$('hasIE6')) {
		opacityUpdates.each(function(opacityUpdate){
			opacityUpdate.setOpacity(.75);
		});
	}
}

// Cookie Functions
// Set the cookie 
function setCookie(name, value, expires, path, domain, secure) {
	// set time, it's in milliseconds
	var today = new Date();
	today.setTime( today.getTime() );
	
	/*
	if the expires variable is set, make the correct
	expires time, the current script below will set
	it for x number of days, to make it for hours,
	delete * 24, for minutes, delete * 60 * 24
	*/
	if ( expires )
	{
	expires = expires * 1000 * 60 * 60 * 24;
	}
	var expires_date = new Date( today.getTime() + (expires) );
	
	document.cookie = name + "=" +escape( value ) +
	( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) +
	( ( path ) ? ";path=" + path : "" ) +
	( ( domain ) ? ";domain=" + domain : "" ) +
	( ( secure ) ? ";secure" : "" );
}

// Read the cookie 
function readCookie(name) { 
	var needle = name + "="; 
	var cookieArray = document.cookie.split(';'); 
	for(var i=0;i < cookieArray.length;i++) { 
		var pair = cookieArray[i]; 
		while (pair.charAt(0)==' ') { 
			pair = pair.substring(1, pair.length); 
		} 
		if (pair.indexOf(needle) == 0) { 
			return pair.substring(needle.length, pair.length); 
		} 
	} 
	return null; 
}

//Adds Date and Time Picking functionality to form inputs with the classes:
//datepicker and timepicker 
function createPickers() {
	var dateInputs = $$('label.datepicker input');
	
	dateInputs.each( function(dateInput) { 
		new Control.DatePicker(dateInput); 
	});
	
	var timeInputs = $$('label.timepicker input');
	
	timeInputs.each( function(timeInput) { 
		new Control.DatePicker(timeInput, {datePicker: false, timePicker: true, use24hrs: false}); 
	});
}	

//Handles pre-populating of the Stay Connected field.
function stayConnectedHint(){
	//find the fieldset for this module
	var stayConnectedFields = $$('fieldset.stayConnected');
	if(!stayConnectedFields) return false;
	
	stayConnectedFields.each(function(fieldset){
		//find the text input
		var textInput = fieldset.down('input[type=text]');
		
		//set its value as requested and prettify.
		textInput.value = 'Email Address';
	
		textInput.setStyle({
			color: '#999'
		});
		
		
		//handle input clearing
		textInput.initialValue = textInput.value;
		textInput.observe('focus', function(event) {
			if(textInput.value == textInput.initialValue){
				textInput.clear();
				textInput.setStyle({
					color: '#000'
				});
			}
		});
		textInput.observe('blur', function(event){
			if(textInput.value.blank() == true) {
				textInput.value = textInput.initialValue;
			}
		});
	});
}


//Web Forms for Maketers Required Label Selector (Labels are used how we usually use dfn's)
//Note: Prototype Driven
function requiredLabels() {
	var spans = $$('span.scfRequired', 'span.scfValidatorRequired');
	
	spans.each(function(span){
		var requiredLabels = span.adjacent('label');
		
		requiredLabels.each(function(requiredLabel) {
			requiredLabel.addClassName('required');
		});
	});
}

function chalkEULA(){
	//console.log('Entering EULA Form Handler');
	var eulaWraps = $$('div.eulaWrap');
	//console.log(eulaWraps);
	if(!eulaWraps[0]) return false;
	
	eulaWraps.each(function(eulaWrap){
		var checkbox = $('acceptEULA');
		var checkStatus = 'unchecked';
		var eulaForm = eulaWrap.previous('div.scfForm');
		var eulaSubmitTable = eulaForm.down('div.scfSubmitButtonBorder');
		var eulaSubmitButton = eulaForm.down('div.scfSubmitButtonBorder').down('input');
		eulaSubmitButton.disabled = true;
		
		eulaSubmitTable.insert({
			before: eulaWrap
		});
		
		checkbox.observe('click', function(event){
			if(checkStatus == 'unchecked'){
				checkbox.checked = true;
				//console.log('checked');
				checkStatus = 'checked';
				eulaSubmitButton.disabled = false;
			} else {
				checkbox.checked = false;
				//console.log('unchecked');
				checkStatus = 'unchecked';	
				eulaSubmitButton.disabled = true;		
			}
		});
		
	});
	
}


//Replacement for Window Onload - Loads before images, cross-browser
document.observe("dom:loaded", function() {
    //dynamicShadow('/images/global/shadow.png', 'page-container', 16, 0);
	chalkEULA();
	requiredLabels();
    printLogo();
    printPage(); // Adds print functionality
    navHandler();
    carousel();
    newsCarousel();
	carouselTracking();
    liFirstLast(); // Adds classes 'first' and 'last' to respective LIs
    hoverFix();
    mediahoverFix();
    googleMapReplacement();
    inputClear();
    searchClear();
    headerHelper();
    categoryAssist();
	signatureAssist();
    ratingList();
    positionElements();
    createPickers();
    externalLinks();
    jsonFeed();
    globalSearch();
    Event.observe(document.onresize ? document : window, "resize", function() {
        positionElements();
    });
	stayConnectedHint();
	switchViews();
});
