//our sidebar is an absolutely-positioned div, meaning it won't affect the flow of content
//this can be bad if content has a smaller height than the sidebar (the sidebar will overflow into the footer)
//this function checks the height of the sidebar on page load and writes a height value to the css
function setMinHeightFromSidebar() {
	//before setting a new height for the sidebar background div, we should always re-set to
	//the absolute minimum we need, otherwise the td#mainContent value will just constantly grow
	//the absolute minimum is the sidebarContent div's height, minus it's margin
	$('div#sidebarBG').height($('div#sidebarContent').height() - 80);

	//the sidebarBG's height should be the height of the main content minus the logo's height, plus a little extra
	var mainLogoHeight = $('div#mainLogo').height();
	var mainContentHeight = $('td#mainContentContainer').height();
	var theNewHeight = (mainContentHeight - mainLogoHeight + 50);
	
	var sidebarHeight = $('div#sidebarContent').height();
	
	//if the new height smaller than absolutely floating sidebar itself, just use the sidebar's height
	//otherwise, use the computed height
	if (theNewHeight < sidebarHeight)
		theNewHeight = sidebarHeight - 80 + 30;		

	$('div#sidebarBG').height(theNewHeight);
	
	//$.log($('div#sidebarBG').height());

}



//counts all of the search results to give the user an idea of that
function countSearchResults(currentAction) {

	var i = 0;
	
	if (currentAction == "subtracting") {
		$('div.searchEntry:visible').each(function() {
			i++;
		});
	
		$('div.searchEntry:animated').each(function() {
			i--;
		});
	}
	
	else if (currentAction == "adding") {
		$('div.searchEntry:visible, div.searchEntry:animated').each(function() {
			i++;
		});
	}
	
	$('div#refineSearch div#numResults').html(i+" Results");

}


//Rotating images ala jCarousel
function mycarousel_itemLoadCallback(carousel, state)
{
	
	// Since we get all URLs in one file, we simply add all items
	// at once and set the size accordingly.
	if (state != 'init')
		return;
		
	// Disable autoscrolling if the user clicks the prev or next button.
	carousel.buttonNext.bind('click', function() {
		carousel.startAuto(0);
	});

	carousel.buttonPrev.bind('click', function() {
		carousel.startAuto(0);
	});
	
	//stop autoscrolling whenever ANYTHING is cliked!
	//this prevents errors when navigating away from the front page
	$(document).bind('click',function() {
		carousel.startAuto(0);		
	});

	// Pause autoscrolling if the user moves with the cursor over the clip.
	carousel.clip.hover(function() {
		carousel.stopAuto();
	}, function() {
		carousel.startAuto();
	});


	$.get('/includes/fpImages.txt', function(data) {
		mycarousel_itemAddCallback(carousel, carousel.first, carousel.last, data);
	});
};

function mycarousel_itemAddCallback(carousel, first, last, data)
{
	// Simply add all items at once and set the size accordingly.
	var items = data.split('\n');
	
	//the last item's bogus 'cause of me, here's a quick fix: subtract 1

	for (i = 0; i < items.length-1; i++) {
		carousel.add(i+1, mycarousel_getItemHTML(items[i]));
	}

	carousel.size(items.length-1);
};

/**
 * Item html creation helper.
 */
function mycarousel_getItemHTML(url)
{
	return '<img src="/img/rotating/' + url + '" alt="" />';
};

$(document).ready(function(){
	
	
	$.jGrowl.defaults.position = "bottom-right";
	$.debug(true);
	
	$("form").jssm('submit');
	//give the page links a rel value of "history" for jssm plugin
	$('#pageList a').attr("rel","history");
	
	//once the page list is loaded, the sidebar is complete and we can compute the required height
	setMinHeightFromSidebar();	
	
	$("a[rel='history']").jssm('click');
	
	//special case: hide the "Home" link from the wordpress page list
	$("a[title='Home']").hide();

	// set onlick event for buttons
	/*$("a[rel='history']").live('click',function(){

		var hash = this.href;
		hash = hash.replace(/^.*#/, '');
		
		// strip the domain out of the hash to make it more readable, it's added back in in the pageload() function
		hash = hash.replace(/(http)(:)(\/)(\/).*?(\/)/,'');
		 
		// moves to a new page. 
		// pageload is called at once. 
		$.historyLoad(hash);
		
		return false;
	});*/
	
	makeFancyButtons();
	
	//initialize texas map modal box
	$('#texasMap').jqm();
	
	//when the map button is clicked, show the texas map modal dialog and initialize google map
	$('.map').live('click', function() {

		//show modal dialog
		$('#texasMap').jqmShow();
		
		if (GBrowserIsCompatible()) {
			//create the Google map
			var map = new GMap2(document.getElementById("googleMap"));
			map.addControl(new GLargeMapControl());
			//relative center of Texas, zoom level large enough to see the whole state
			map.setCenter(new GLatLng(31.5, -99), 6);
			new GKeyboardHandler(map);
			map.enableScrollWheelZoom();
			
			//give reverse geocoding functionality
			var geocoder = new GClientGeocoder();
			//rings will later be an overlay object for radial data		
			var rings = 0;
			
		
			//when the map is clicked...
			GEvent.addListener(map,"click", function(overlay, latlng) {  
				if (latlng) { 
					//take any previous overlays off
					map.removeOverlay(rings);
					//add a new mile radius overlay
					rings = new BdccRangeRings(latlng, "#0000FF",3,0.5,null,5);
					map.addOverlay(rings);
					//and pop up a window with relative address proximity (reverse-geocoded)
					geocoder.getLocations(latlng, showAddress);
				}
			});
	
			//shows a popup with a reverse-geocoded address
			function showAddress(response) {
			  //map.clearOverlays();
			  if (!response || response.Status.code != 200) {
				alert("Status Code:" + response.Status.code);
			  } else {
				place = response.Placemark[0];
				point = new GLatLng(place.Point.coordinates[1],place.Point.coordinates[0]);
				$('#latLongCoords').attr({value: place.Point.coordinates[1]+','+place.Point.coordinates[0]});
				//marker = new GMarker(point);
				//map.addOverlay(marker);
				map.openInfoWindow(point, 'Near: ' + place.address);
				$('#latLngAddress').val(place.address);
			  }
			}
	
		}
		
	}); //close click function
	
	


	//run when the login submit button is clicked (when someone tries to login)
	$('#loginBox .submit').live('click',function() {
		//grab the email and password they entered
		var email = $('#loginEmail').val();
		var password = $('#loginPassword').val();
		
		//hide the login button while checking credentials
		$(this).hide();
		var thisButton = $(this);
		
		$('#loginLoading').show();
		
		//send the username and password to login.php for checking
		$.post('includes/ajax.php',
			{action: "setLogin", email: email, password: password},
			function (response) {
				$('#loginLoading').hide();
				
				// if login.php responds true, they've been logged in.
				// hide the login form and fade in the success div
				if (response == "True") {
				
					//log them in phpbb3 also, before proceeding
					$.post('/includes/ajax.php',{action: "getPhpbbLogin"},function(xml) {
	
						$(xml).find('PhpbbUser').each(function() {
							var username = $(this).find('Username').text();
							
							$.post('/phpbb3/ucp.php',{username: username ,password: password, autologin: 1, login: 1});
						});							
					});
					
					//try to log them into Wordpress, it'll succeed if they're an admin (valid user of WP)
					$.post('/wordpress/',{TEVloginUser: email, TEVloginPass: password});
					
					//get what to show next from ajax.php's loginMessage()
					$.post('/includes/ajax.php',{action: "loginMessage"},function(html) {
						$('#loginBox').fadeOut('fast',function() {
							$('#loginBox').html(html);
							makeFancyButtons();
						});
						$('#loginBox').fadeIn('slow');
						$.jGrowl('You have been successfully logged in!',{
							theme: "green"
						});
					});
				}
				
				//if login.php doesn't respond true, fade in the failure message div
				else {
					thisButton.show();
					$.jGrowl('Sorry, your login failed.  Try again.',{
						theme: "red"
					});
				}
					
		});// end post callback function		
			
		// return false so the form does not perofrm any actions outside of javascript
		return false;
	}); //end click function
	
	
	//logout link
	$('#logout').live('click',function() {

		tevLogout(function() {
			$.jGrowl('You have been successfully logged out!');
		});
		
	});
	
	
	$('.btn.getResultsByName, .btn.getResultsByZip, .btn.getResultsByCoords').click(function() {
		
		if ($(this).hasClass('getResultsByCoords')) {
			//close the modal window in this specific case
			$('#texasMap').jqmHide();
		}
		
		$(this).closest('form').submit();
	
	});
	

	//here's all of the functionality for sorting search results by attributes
	$('div.attrib').live('click',function() {
		var keyAttrib = $(this).attr('keyattrib');
		
		//if they clicked on an attribute that already was a filter, we need to re-show what was hidden
		if ($(this).hasClass('true')) {
			$(this).removeClass('true');
			
			//show all of the divs that DO NOT have this attribute
			//but we also have to make sure that divs without any other selected attributes are still hidden!
			
			//so find all of the current selected filters and store in an array
			var currFilters = new Array();
			var i = 0;
			
			$('div.attrib').each(function() {
				if ($(this).hasClass('true'))
					currFilters[i++] = $(this).attr('keyattrib');
			});
			
			//we'll determine whether to fade something in (it doesn't match any more filters) based on this boolean
			var fadeThisIn = false;
			
			$('div.searchEntry').each(function() {
			
				var attribList = $(this).attr('attrib');
				//it matches the current filter which was de-selected
				if (attribList.indexOf(keyAttrib) == -1)
					fadeThisIn = true;
				//but it also matches a filter which is active
				for(i=0; i<currFilters.length; i++)
					if (attribList.indexOf(currFilters[i]) == -1)
						fadeThisIn = false;
				//after those tests, if fadeThisIn is true, show that result
				if (fadeThisIn)
					$(this).fadeIn('slow');
			
			});
			
			countSearchResults("adding");
		}
		
		//add a filter and hide divs that don't match that filter
		else {
			$(this).addClass('true');
			
			$('div.searchEntry').each(function() {
			
				var attribList = $(this).attr('attrib');

				//if keyAttrib was not found in attribList
				//in English, if the attribute we clicked on is not part of the specific search result
				if (attribList.indexOf(keyAttrib) == -1) {
					//then fade that search result out
					$(this).fadeOut('slow');
				}
		
			});
			
			countSearchResults("subtracting");
		}
		
	});
	
	//and here's the sorting-by-attributes tooltips to help people know what they're clicking
	$('div.attrib').livequery(function() {
		$('div.attrib').each(function() {
			var dispText = "";
			if ($(this).attr('keyattrib') == "fee_free")
				dispText = "Only show destinations that are free";
			if ($(this).attr('keyattrib') == "fee_charge")
				dispText = "Only show destinations that charge a fee";
			if ($(this).attr('keyattrib') == "school_tours")
				dispText = "Only show destinations that offer school/group tours";
			if ($(this).attr('keyattrib') == "guide")
				dispText = "Only show destinations that offer docents/guides";
			if ($(this).attr('keyattrib') == "educational_materials")
				dispText = "Only show destinations that offer educational materials";
			if ($(this).attr('keyattrib') == "restaurant")
				dispText = "Only show destinations that have a restaurant";
			if ($(this).attr('keyattrib') == "handicap_accessible")
				dispText = "Only show destinations that are handicap accessible";
			if ($(this).attr('keyattrib') == "subject_history")
				dispText = "Only show destinations that deal with history";
			if ($(this).attr('keyattrib') == "subject_science")
				dispText = "Only show destinations that deal with science";
			if ($(this).attr('keyattrib') == "subject_geography")
				dispText = "Only show destinations that deal with geography";
			if ($(this).attr('keyattrib') == "subject_nature")
				dispText = "Only show destinations that deal with nature";
			if ($(this).attr('keyattrib') == "subject_arts")
				dispText = "Only show destinations that deal with the arts";
			if ($(this).attr('keyattrib') == "pre-k")
				dispText = "Only show destinations that are appropriate for pre-k students";
			if ($(this).attr('keyattrib') == "kindergarten")
				dispText = "Only show destinations that are appropriate for kindergarten students";
			if ($(this).attr('keyattrib') == "elementary_school")
				dispText = "Only show destinations that are appropriate for elementary school students";
			if ($(this).attr('keyattrib') == "middle_school")
				dispText = "Only show destinations that are appropriate for middle school students";
			if ($(this).attr('keyattrib') == "high_school")
				dispText = "Only show destinations that are appropriate for high school students";
				
			$(this).tooltip({
				delay: 0,
				bodyHandler: function() {
					return dispText;
				},
				showURL: false
			});
		});
	});
				
	
	$('#attraction').autocomplete('/includes/getNamesForAutocomplete.php');
	

	//for "submit your comment" in Wordpress pages
	$('div.submitComment').live('click',function() {
	
		var queryString = $('form#commentform').formSerialize();
		
		$.post('/wordpress/wp-comments-post.php',queryString);
		
		$('div#postPageComment').fadeOut('slow', function() {
			$.jGrowl('Your comment has been submitted for approval by our administrators!');
		});
	
	});
	
	//for comment links under blog posts, unfortunately we have to post-process them
	//since the only other way to remove the hash symbol from URLs would be modification of the Wordpress core
	$('a.wpCommentLink').livequery(function() {
		var commentHref = $(this).attr('href');
		commentHref = commentHref.replace(/#respond/,'');
		$.log(commentHref);
		$(this).attr('href',commentHref);
	});
	
	
	//for the signup form's submit button
	$('div.submitNewProfile').live('click',function() {
		
		$(this).hide();
		var thisButton = $(this);
		
		var queryString = $('form#createProfile').formSerialize() + '&action=makeNewProfile';
		$('div#signupLoading').show();
		
		if ($('form#createProfile').valid()) {
			$.post('/includes/ajax.php',queryString,function(response) {
				$('div#signupLoading').hide();
				thisButton.show();
				$.jGrowl('Success! Administrators will be reviewing your details shortly.');
			});
		}
		else {
			$('div#signupLoading').hide();
			thisButton.show();
		}
		
	});
	
	
	//update profile form
	$('div.updateProfile').live('click',function() {
												 
		var queryString = $('form#editProfile').formSerialize();
		
		queryString = queryString + "&action=updateProfile&approved=1";
		
		if ($('form#editProfile').valid()) {
			$.post('/includes/ajax.php', queryString, function(response){
				if (response == "Success")
					$.jGrowl('You successfully changed your profile',{
						theme: "green"
					});
				else
					$.jGrowl('There was an error changing your profile');
			});
		}
		else
			$.jGrowl('There were a few errors in the form.  Please correct them.');
	
	});
	
	//forgot password form
	$('div.forgotPassword').live('click',function() {
					
		var queryString = $(this).closest('form').formSerialize();
		queryString = queryString + "&action=resetPassword";
		
		$.post('/includes/ajax.php',queryString, function(response) {
		
			if (response == "Success")
				$.jGrowl('New password has been sent!',{
					theme: "green"
				});
			else if (response == "Nonexistant")
				$.jGrowl('That email does not exist as a login for TEV.  Try another?',{
					theme: "red"
				});
			else
				$.jGrowl('There was a problem changing your password.  Try it once more.');
		
		});
				
	});
	
	//Find Events
	
	$('form#manageEvents').livequery(function() {
		$('input#startdate').datepicker({
			changeMonth: true,
			prevText: '',
			nextText: '',
			dateFormat: 'yy-mm-dd'
		});
		$('input#enddate').datepicker({
			changeMonth: true,
			prevText: '',
			nextText: '',
			dateFormat: 'yy-mm-dd'
		});
	});
	
	$('div.findEvents').live('click',function() {

		$(this).closest("form").submit();

	});
	
	//Find events (nav bar)
	
	/*$('form#navEvents').livequery(function() {
		$('input#navEventStartDate').datepicker({
			changeMonth: true,
			prevText: '',
			nextText: '',
			dateFormat: 'yy-mm-dd'
		});
		$('input#navEventEndDate').datepicker({
			changeMonth: true,
			prevText: '',
			nextText: '',
			dateFormat: 'yy-mm-dd'
		});	
	});*/
	
	$('div.navSearchEvents').live('click',function() {
	
		/*var queryString = $(this).closest('form').formSerialize();
		
		$.post('/events.php',queryString,function(html) {
			$('#loadedContent').html(html);
			makeFancyButtons();
		});*/
		$(this).closest("form").submit();
	
	});

	
}); // close document.ready function