//JSON Ajax Reader
function jsonFeed(){
	var twitterContainer = $('socialMedia');
	var speed = 15;
	var currentTweet = 0;
	var followURL = "https://twitter.com/signup?follow=innovateenergy&commit=Join+Today";
	if(!twitterContainer) return false;
	
	var url = '/modules/requestProxy.aspx?req=http://api.twitter.com/1/statuses/user_timeline.json?user=innovateenergy';
	
	
	//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 > 0){
					tweet.remove();
				} 
					
				currentTweet = tweet.text;
				
				var username = tweet.user.screen_name

				var tweetID = tweet.id
				var tweetURL = "http://www.twitter.com/" + username + "/status/" + tweetID + ""
				var profileURL = "http://www.twitter.com/" + username + "/"
				var tweetTemplate = new Template('<p>#{text}</p>');
				
				
				tweet.text = tweet.text.sub(/(http?:\/\/[^\s]+)/, function(match){
				  return '<a alt="' + match[1] + '" href="' + match[1] + '" target="_blank">' + match[1] + '</a>';
				});
				
				var tweetAnchor = new Element('a', { href: tweetURL}).update("Latest Tweet");
				var tweetLinkHeader = new Element('h2');
				var viewAllLink = new Element('a', { href: profileURL, target: '_blank'}).update("View All ");
				var followLink = new Element('a', { href: followURL, target: '_blank'}).update("Follow Us");
				var secondaryLinks = new Element('p');
								
				twitterContainer.insert({
					top: tweetTemplate.evaluate(tweet)
				});
				
				twitterContainer.insert({
					top: tweetLinkHeader
				});
				
				tweetLinkHeader.insert({
					top: tweetAnchor
				});
				
				secondaryLinks.insert({
					bottom: viewAllLink
				});
				
				secondaryLinks.insert({
					bottom: ' | '
				});
				
				secondaryLinks.insert({
					bottom: followLink
				});
				
				twitterContainer.insert({
					bottom: secondaryLinks
				});	
				//console.log('on page load this is currentTweet: ' + currentTweet);	

			});
		
	  }

	});
	
	twitterUpdater = new PeriodicalExecuter(function(){
		//console.log(twitterUpdater);
		
		new Ajax.Request(url, {
		  method: 'get',
		  onSuccess: function(transport) {
			var json = transport.responseText.evalJSON();
			
			json.each(function(tweet, index){
				if(index > 0){
					tweet.remove();
				} 
				
				//console.log('at the top of the executer the currentTweet: ' + currentTweet);
				//console.log(tweet.text);
				
				if(currentTweet == tweet.text){
					twitterUpdater.stop();
					twitterUpdater.frequency = speed + 10 * 2;
					speed = speed + 10 * 2;
					twitterUpdater.registerCallback();
					//console.log('tweet is the same and speed is now increased to ' + speed);
				} else {
					twitterUpdater.stop();
					twitterUpdater.frequency = 10;
					speed = 10;
					twitterUpdater.registerCallback(); 
					//console.log('tweet was different so speed is now ' + speed);
					
					currentTweet = tweet.text;
					
					twitterContainer.update('');
				
					var username = tweet.user.screen_name
					var tweetID = tweet.id
					
					var tweetURL = "http://www.twitter.com/" + username + "/status/" + tweetID + ""
					
					var profileURL = "http://www.twitter.com/" + username + "/"
					var tweetTemplate = new Template('<p>#{text}</p>');
					
					tweet.text = tweet.text.sub(/(http?:\/\/[^\s]+)/, function(match){
					  return '<a alt="' + match[1] + '" href="' + match[1] + '">' + match[1] + '</a>';
					});
					
					var tweetAnchor = new Element('a', { href: tweetURL}).update("Latest Tweet");
					var tweetLinkHeader = new Element('h2');
					var viewAllLink = new Element('a', { href: profileURL}).update("View All");
					var followLink = new Element('a', { href: profileURL}).update("FollowUs");
					var secondaryLinks = new Element('p');
					
					
					twitterContainer.insert({
						top: tweetTemplate.evaluate(tweet)
					});
					
					twitterContainer.insert({
						top: tweetLinkHeader
					});
					
					tweetLinkHeader.insert({
						top: tweetAnchor
					});
					
					secondaryLinks.insert({
						bottom: viewAllLink
					});
					
					secondaryLinks.insert({
						bottom: ' | '
					});
					
					secondaryLinks.insert({
						bottom: followLink
					});
					
					twitterContainer.insert({
						bottom: secondaryLinks
					});
					
				}
				
				
				//console.log('at the end of the executer the currentTweet: ' + currentTweet);

			});
			
		  }

		});
	}, speed);
}


//Insert Logo and Hide it specifically for Print Stylesheet
function printLogo(){
	var logoHeader = $('header');
	var imgSrc = ('http://www.entrepreneurship.org/images/KauffmanLogo.gif');
	var imgWidth = 164;
	var imgHeight = 62;
	var imgAlt = ('Kauffman');
	
	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});
}


//First and Last LI Selector
//Note: Prototype Driven
function liFirstLast() {
	var firstLIs =	$$('ul > li:first-child');
	var lastLIs = $$('ul > li:last-child');
	
	firstLIs.each(function(liFirst) {
		liFirst.addClassName('first');
		});
		
	lastLIs.each(function(liLast) {
		liLast.addClassName('last');
	});
}
//First and Last DT Selector
//Note: Prototype Driven
function dtFirstLast() {
	var firstDTs =	$$('dl > dt:first-child');
	var lastDTs = $$('dl > dt:last-child');
	
	firstDTs.each(function(dtFirst) {
		dtFirst.addClassName('first');
		});
		
	lastDTs.each(function(dtLast) {
		dtLast.addClassName('last');
	});
}

//Input Clear
//Clears text inputs on a page on focus
//Note: Prototype driven
function inputClear() {
	var textInputs = $$('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;
			}
		});
	});
}

//Input Class Add
//Clears text inputs on a page on focus
//Note: Prototype driven
function inputFocus() {
	var textInputs = $$('input[type="text"]');
	
	textInputs.each(function(textInput){
		textInput.observe('focus', function(event) {
			textInput.addClassName('focus');
		});
		textInput.observe('blur', function(event){
			textInput.removeClassName('focus');
		});
	});
}
// Cookie Functions
// Set the cookie 
function setCookie(name,value,days) { 
	if (days) { 
		var date = new Date(); 
		date.setTime(date.getTime()+(days*24*60*60*1000)); 
		var expires = ";expires="+date.toGMTString(); 
	} else { 
		expires = ""; 
	} 
	document.cookie = name+"="+value+expires+";"; 
}

// 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; 
}

//Form Error Bottom Anchor Fixes
//Makes it so whenever there is a form response the page should scroll to it, despite it's length.
function formResultHandler(){
	var errorContainer = $('content_2_vsComment');
	var errorCaptcha = $('captchaError');
	var submitButton = $('content_2_btnSubmitComment');
	
	if(errorContainer.empty()) return false;
	
	$('footer').scrollTo();
	
	if(!errorCaptcha) return false;
	
	$('footer').scrollTo();

}

function thankyouHelper(){	
	var thankyouText = $('thankyou');
	
	if(!thankyouText) return false;
	$('footer').scrollTo();
}

function reloadHelper(){	
	var reloadButtons = $$('a.reloaded');
	
	if(!reloadButtons[0]) return false;
	
	$('footer').scrollTo();
}

/* This function takes the feedblitz url and an email address  
 * and opens a new window allowing the visitor to the site to sign up for 
 * newsletter emails
 */
function feedblitz(urlVal, eaCtl)
{
    var emailVal = document.getElementById(eaCtl).value;
    var openURL = urlVal + emailVal;
    window.open(openURL, 'Newsletter Signup');

}


//Replacement for Window Onload - Loads before images, cross-browser
document.observe("dom:loaded", function() {
	//dynamicShadow('/images/global/shadow.png', 'page-container', 16, 0);
	liFirstLast(); // Adds classes 'first' and 'last' to respective LIs
	dtFirstLast(); // Adds classes 'first' and 'last' to respective LIs
	inputFocus();
	printLogo();
	jsonFeed();
	thankyouHelper();
	formResultHandler();
	reloadHelper();
});