$(document).ready(function(){
	
	bindMiniContactFormEvents();
	bindSiteCredits();
	initTwitter();
	setSketchBG();
	
	
	bindHomePageEvents();
	
	bindEventsPageEvents();
	
	bindBlogDetailsPageEvents();
	//loadMaps();
	//$('#bottleLocations').bind('click', loadMaps);
	//$('.bottleLocations').bind('click', loadMaps);

});
/*function loadMaps(){
	$('#container').hide();
	//test
	//$('#mapContainer').width($(window).width())
	//$('#mapContainer').height($(window).height())
	$('#mapContainer').show();
	//$('#mapContainer').center().show();
	googleMapInit();
}*/
function setSketchBG(){
	//plus 45 here because it's 45 pixels from top of the page.
	var subpageHeight = $('#subContentContainer').height() + 45;
	
	if(subpageHeight > 1020){
		var docHeight = $(document).height();
		var sketchHeight = docHeight - 725 -85;
		$('#sketchImageContainer').css('display', 'block');
		$('#sketchImageContainer').height(sketchHeight);
		
	}
	else{
		$('#sketchImageContainer').remove();	
	}	
}


function bindMiniContactFormEvents(){
	$('#miniContactEmail').bind('focus', clearEmailValue);
	$('#miniContactEmail').bind('blur', restoreEmailValue);
	$('#miniContactMessage').bind('focus', clearMessageValue);
	$('#miniContactMessage').bind('blur', restoreMessageValue);
	$('#miniContactName').bind('focus', clearNameValue);
	$('#miniContactName').bind('blur', restoreNameValue);	
	
	$('#contactFormSubmit').click(submitGuestbookForm);
}

function submitGuestbookForm(){
	var name = $('#miniContactName').val();
	var email = $('#miniContactEmail').val();
	var message = $('#miniContactMessage').val();
	var newsletter = 0;
	if($('#newsletterCheck .customCheckboxHolder').hasClass('selected'))
		newsletter = 1;
	
	if(name !== 'your name' && email !== 'your_name@email.com' && message !== 'your message'){
		
		$.ajax({
			type: "POST",
			url: "/_commongoal/api/ContactFormFacade.cfc",
			dataType: "text",
			data: {
			   method: 'submitGuestbookEntry',
			   name: name,
			   message: message,
			   email: email,
			   newsletter: newsletter
			   
			},
			success: guestBookSuccess
		});	
	}
	else{
		alert('Please enter your name, email, and a message.');	
	}
}
function guestBookSuccess(){
	$('#navContactForm').html("<h2>Leave Us a Note</h2><br/><span class='thankYouMsg'>Thanks for dropping us a line! If you're looking for store locations check out: <a href='javascript:;' class='bottleLocations'>Bottle Locations</a></span>");
	//Look for it on the <a href="/Guestbook">guestbook page.
}

function clearEmailValue(){
	if($(this).val() == 'your_name@email.com')
		$(this).val('');
}
function restoreEmailValue(){
	if($(this).val() == '')
		$(this).val('your_name@email.com');
}
function clearMessageValue(){
	if($(this).html() == 'your message')
		$(this).html('');
}
function restoreMessageValue(){
	if($(this).html() == '')
		$(this).html('your message');
}
function clearNameValue(){
	if($(this).val() == 'your name')
		$(this).val('');
}
function restoreNameValue(){
	if($(this).val() == '')
		$(this).val('your name');
}



function bindSiteCredits(){
	$('#initLink #siteCreditsLink').bind('mouseover', initSiteCredit);		
}

function initSiteCredit(){
	$("#initLink").fadeOut("normal");
	$("#CreditsLink").animate( { left:"0" }, { duration:1000 } );
	setTimeout("revertSiteCredit()",7000);
}

function revertSiteCredit(){
	$("#CreditsLink").animate( { left:"-320" }, 1000, "linear", function(){$("#initLink").fadeIn("normal");} );
}


/*function initTwitter(){
	var feedUrl =  'http://twitter.com/statuses/user_timeline/slumbrew.json?count=1&callback=?';
	$.getJSON(feedUrl, 
		function(data){
			var TwitterTab_p = $("#twitterCallout #postContent");
			var date = data[0].created_at;
			date = date.replace(/\+0000/g, ' ')
			$('#postDate').prepend(dateFormat(date, "hh:MM TT mmm dd") + ' |');
			TwitterTab_p.html(data[0].text.linkText());
			if(TwitterTab_p.html().length > 1)
				var fullText = TwitterTab_p.html();
			else
				var fullText = 'Sorry, Twitter cannot be accessed right now.';
			TwitterTab_p.html(fullText.replace(/href/g, 'target="_blank" href'));
			TwitterTab_p.fadeIn(1000);
			$('#postDate').fadeIn(1000);
			
			
		});
		
		String.prototype.linkText = function() {																		 
			return this.replace(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&\?\/.=]+/, function(m) {
				return m.link(m);
			});
		}	
}*/
function initTwitter(){
	/*var twitterUserName = "slumbrew";
	var url = "http://api.twitter.com/1/statuses/user_timeline.json?screen_name="+twitterUserName+"&include_rts=flase&count=1&callback=?"
	
	var urirex = /(https?):\/\/+([\w\d:#@%\/;$()~_?\+-=\\\.&]*)/g;
	
	var thashuri = "http://search.twitter.com/search?q=%23";
	var display = "";
	var ttext = "";
	
	var TwitterTab_p = $("#twitterCallout #postContent");
	 $.getJSON(url,function(json){
		 	$.each(json, function(i,tweet){
				ttext = tweet.text.replace(urirex, '<a target="_blank" href="$1://$2" title="">$2</a>');
				ttext = ttext.replace(/(^|\s)@(\w+)/g, '$1@<a target="_blank" href="http://www.twitter.com/$2">$2</a>');
				ttext = ttext.replace(/(^|\s)#(\w+)/g, '$1#<a target="_blank" href="http://search.twitter.com/search?q=%23$2">$2</a>')
				
				display += ttext
			});
		TwitterTab_p.html(display);
	});
	TwitterTab_p.fadeIn(1000);
	$('#postDate').fadeIn(1000);*/
}

/*
============
HOMEPAGE
============
*/
function bindHomePageEvents(){
	$('#getInTheKnowEmail').bind('focus', clearEmailValue);	
	$('#getInTheKnowEmail').bind('blur', restoreEmailValue);
	$('#getInTheKnowSignUp').click(submitNewsletterSignup);
}

function submitNewsletterSignup(){
	var email = $('#getInTheKnowEmail').val();
	if(email !== 'your_name@email.com'){
		
		$.ajax({
			type: "POST",
			url: "/_commongoal/api/ContactFormFacade.cfc",
			dataType: "text",
			data: {
			   method: 'submitNewsletter',
			   email: email
			},
			success: newsletterSuccess
		});	
	}
	else
		alert('Please enter your email address.');
}
function newsletterSuccess(){
	//Thanks! Now you're in the know.
	$('#homeGetInTheKnowCallout').html('<h2>Get In the Know</h2><p>Get Slumbrew updates as they happen!</p><p class="thankYouMsg">Thanks! Now you\'re in the know.');
}
	

/*
============
EVENTS PAGE
============
*/
function bindEventsPageEvents(){
	$('#showMoreEvents').click(showMoreEvents);	
	$('.illBeThereBtn').click(showRSVPForm);
	
	$('.rsvpemail').bind('focus', clearEmailEventRSVPValue);	
	$('.rsvpemail').bind('blur', restoreEmailEventRSVPValue);
	
	
	$('.rsvpSubmit').click(submitEventRSVP);
}

function showMoreEvents(){
	$.each($('.passedEvent.hidden'), function(i){
		if(i < 4){
			$(this).slideDown('fast', hideShowEventsButton);	
			$(this).removeClass('hidden');
		}
	});
}
function hideShowEventsButton(){
	if($('.passedEvent.hidden').length == 0)
		$('#showMoreEvents').fadeOut('fast');	
}
function showRSVPForm(){
	sender = $(this);
	sender.fadeOut('fast', function(){sender.next('.rsvpForm').fadeIn('fast');});
}

function clearEmailEventRSVPValue(){
	if($(this).val() == 'enter your email')
		$(this).val('');
}
function restoreEmailEventRSVPValue(){
	if($(this).val() == '')
		$(this).val('enter your email');
}



function submitEventRSVP(){
	sender = $(this);
	var eventID = sender.parent().children('.eventID').val();
	var email = sender.parent().children('.rsvpemail').val();
	if(email !== 'enter your email'){
		$.ajax({
			type: "POST",
			url: "/_commongoal/api/ContactFormFacade.cfc",
			dataType: "text",
			data: {
			   method: 'submitEventRSVP',
			   eventID: eventID,
			   email: email
			},
			success: function(){
				sender.parent().html('<span style="float:right; font-weight:bold;">See you there!</span>');
			}
		});
	}
	else{
		alert('Please enter your email address to RSVP.');	
	}
}


/*
============
BLOG LADNING
============
*/
function bindBeerTalkPageEvents(){
	
	initPagination('blogEntries','blogPaginatorTop', {
		pageInput:"currentPageNumberInput", 
		nextBtn: "nextBtn", 
		previousBtn: "prevBtn",
		itemsPerPage: 3
     });
	 
	initPagination('blogEntries','blogPaginatorBottom', {
		pageInput:"currentPageNumberInput", 
		nextBtn: "nextBtn", 
		previousBtn: "prevBtn",
		itemsPerPage: 3
     });
}

/*
============
BLOG DETAILS
============
*/
function bindBlogDetailsPageEvents(){
	$('#commentEmail').bind('focus', clearCommentEmailValue);
	$('#commentEmail').bind('blur', restoreCommentEmailValue);
	$('#commentURL').bind('focus', clearURLValue);
	$('#commentURL').bind('blur', restoreURLValue);
	$('#commentComment').bind('focus', clearLeaveCommentValue);
	$('#commentComment').bind('blur', restoreLeaveCommentValue);
	$('#commentName').bind('focus', clearNameValue);
	$('#commentName').bind('blur', restoreNameValue);	
	
	initBlogArchiveNav();
	
}

function clearCommentEmailValue(){
	if($(this).val() == 'email')
		$(this).val('');
}
function restoreCommentEmailValue(){
	if($(this).val() == '')
		$(this).val('email');
}
function clearURLValue(){
	if($(this).val() == 'url')
		$(this).val('');
}
function restoreURLValue(){
	if($(this).val() == '')
		$(this).val('url');
}
function clearLeaveCommentValue(){
	if($(this).html() == 'leave your comment')
		$(this).html('');
}
function restoreLeaveCommentValue(){
	if($(this).html() == '')
		$(this).html('leave your comment');
}

function initBlogArchiveNav(){
	var Blog_MainContainer = $('#Blog_MainContainer');
	var BlogUL_Lv1 = $('a[open="MonthOptions"]');
	
	var openMonthLinks = $('a[open="MonthLinks"]');
	
	BlogUL_Lv1.click(function(e){
		var setThis = $(this);
		if(setThis.parent().find('.monthUL').css('display') != 'block'){
			setThis.parent().find('.monthUL').show(200);
			setThis.parent().addClass('open');
		}
		else{
			setThis.parent().find('.monthUL').hide(200);
			setThis.parent().removeClass('open');
		}
		
	});
	
	openMonthLinks.click(function(e){
		var setThis = $(this);
		
		if(setThis.parent().find('div').css('display') == 'block'){
			setThis.parent().find('div').hide(200);
			setThis.parent().removeClass('open');
		}
		else{
			setThis.parent().find('div').show(200);
			setThis.parent().addClass('open');
		}
	});
	
	// finds current blog entry and shows all parents until blog archive container to expand them
	$("a[IsCurrentBlogEntry='true']").parentsUntil("div.Blog_Archive").show().addClass('open');	
}


/*
============
BREW LOG
============
*/
function bindBrewLogPageEvents(){
	$('#keywordSearch').bind('focus', clearKeywordValue);
	$('#keywordSearch').bind('blur', restoreKeywordValue);	
	
	$('#experimentSearch').bind('change', submitExperimentSearch);
	
	$('#keywordSearch').keypress(function(e){submitBrewLogSearchKeyUp(e);});
	$('#brewLogSearchBtn').click(submitBrewLogKeyWordSearch);
	
	
	initPagination('brewLogContainer','brewLogPaginatorTop', {
		pageInput:"currentPageNumberInput", 
		nextBtn: "nextBtn", 
		previousBtn: "prevBtn",
		itemsPerPage: 3
     });
	
	initPagination('brewLogContainer','brewLogPaginatorBottom', {
		pageInput:"currentPageNumberInput", 
		nextBtn: "nextBtn", 
		previousBtn: "prevBtn",
		itemsPerPage: 3
     });
	
}
function clearKeywordValue(){
	if($(this).val() == 'keyword')
		$(this).val('');
}
function restoreKeywordValue(){
	if($(this).val() == '')
		$(this).val('keyword');
}


function submitExperimentSearch(){
	updateBrewLogList($(this).val(), '');
	$('#keywordSearch').val('keyword');
}

function submitBrewLogSearchKeyUp(e){
	if(e.which == 13)
		submitBrewLogKeyWordSearch();
	return false;
}
function submitBrewLogKeyWordSearch(){
	if($('#keywordSearch').val() !== 'keyword'){
		$('#experimentSearch option:first-child').attr('selected','selected');
		updateBrewLogList('', $('#keywordSearch').val());
	}
}
function updateBrewLogList(experimentID, keyword){
	$.ajax({
		type: "POST",
		url: "/_commongoal/api/BrewLogFacade.cfc",
		dataType: "text",
		data: {
		   method: 'getBrewLogs',
		   experimentID: experimentID,
		   keyword: keyword
		},
		success: getBrewLogsSuccess
	});	
}
var getBrewLogsSuccess = function(results){
	var html = '';
	results = eval(results);
	$.each(results, function(i, retItem){
		html +='<div class="batchContainer" pageitem="true"><div class="header"><h4>'+retItem.NAME+' - '+retItem.ENTRYDATE+'</h4></div><div class="batchContent"><div class="description">'+retItem.CONTENT+'</div><h4 class="statsHeader">Stats</h4><table class="logTable" cellpadding="0" cellspacing="0" border="0" width="100%"><tr><td><strong>OG:</strong> '+retItem.OG+'</td><td><strong>Est FG:</strong> '+retItem.ESTFG+'</td><td><strong>FG:</strong> '+retItem.FG+'</td><tr><td><strong>IBU:</strong> '+retItem.IBU+'</td><td><strong>Color:</strong> '+retItem.COLOR+'</td><td><strong>ABV:</strong> '+retItem.ABV+'</td></tr><tr><td colspan="2"><strong>Total Grains:</strong> '+retItem.TOTALGRAINS+'</td> <td><strong>Hops:</strong> '+retItem.HOPS+'</td></tr><tr><td colspan="3"><strong>Mash Profile:</strong> '+retItem.MASHPROFILE+'</td></tr></table></div><!--batchContent--></div><!--batchContainer-->';					 					
	});
	$('#brewLogContainer').html(html);	
	
                                               
     initPagination('brewLogContainer','brewLogPaginatorTop', {
		pageInput:"currentPageNumberInput", 
		nextBtn: "nextBtn", 
		previousBtn: "prevBtn",
		itemsPerPage: 3
     });
	
	initPagination('brewLogContainer','brewLogPaginatorBottom', {
		pageInput:"currentPageNumberInput", 
		nextBtn: "nextBtn", 
		previousBtn: "prevBtn",
		itemsPerPage: 3
     });
}



/*
============
GUESTBOOK
============
*/
function bindGuestbookPageEvents(){
	initPagination('guestbookContainer','guestbookPaginatorTop', {
		pageInput:"currentPageNumberInput", 
		nextBtn: "nextBtn", 
		previousBtn: "prevBtn",
		itemsPerPage: 5
     });
	
	initPagination('guestbookContainer','guestbookPaginatorBottom', {
		pageInput:"currentPageNumberInput", 
		nextBtn: "nextBtn", 
		previousBtn: "prevBtn",
		itemsPerPage: 5
     });
}


	
function loadjsfile(filename, filetype){
	alert(1);
	var fileref=document.createElement('script');
	fileref.setAttribute("type","text/javascript");
	fileref.setAttribute("src", filename);
	
	if (typeof fileref!="undefined")
		document.getElementsByTagName("head")[0].appendChild(fileref);
}



