$(document).ready(function() {
	
	// when document is ready, clear the picks list, remove select lists, and create hidden inputs
	var $picks = $('#picks').show().empty();
	$('#ballot_inner div.vis').removeClass().addClass('hidden');

	// create message to display when user tries to select more than 5 presidents
	var $msg = $('<div id="msg"><p>Sorry, but you have already selected 5 Presidents for your ballot.</p><p style="margin-bottom: 0;">Either deselect a selected President to make a new selection or complete your ballot by casting your vote on the right.</p></div>').appendTo('body').hide().css({position: 'absolute'});

	var msgClose, pickCount = 0;
	
	// add or remove presidents when they are selected.
	$('#pres_list div.select').show().click(function(event) {
		var $this = $(this);
		var pres = $this.prev().prev().text();
		var removePres = function() {
			$this.css({backgroundPosition: '0 0'});
			$picks.removeClass('complete')
				.children('li:contains(' + pres + ')').fadeOut(500,function() {$(this).remove();});
			pickCount--;
		};

		if (pickCount < 5) {
			$this.toggleClass('selected');
			if ($this.is('.selected')) {
				$this.css({backgroundPosition: '0 -34px'});
				$picks.append(['<li>', pres, '</li>'].join(''));
				pickCount++;
				$picks[pickCount == 5 ? 'addClass' : 'removeClass']('complete');
			} else {removePres();}
		} else {
			if ($this.is('.selected')) {
				removePres();
				$this.removeClass('selected');
				clearTimeout(msgClose);
					$msg.fadeOut(300);
			} else {
				$picks.addClass('complete');
				$msg.show().css({top: event.pageY-125, left: event.pageX-100});
				msgClose = setTimeout(function() {$msg.fadeOut(300);}, 6500);
			}
		}
		$('li', $picks).each(function(index) {
			var vote = $(this).text();
			$('#ballot_inner div.hidden').find('select:eq(' + index + ')').val(vote);
		});
		
	})
	.hover(function() {
	var $this = $(this);
		if ($this.is('.selected')) {
			$this.css({backgroundPosition: '0 -68px'});
		}
	}, function() {
	var $this = $(this);
		if ($this.is('.selected')) {
			$this.css({backgroundPosition: '0 -34px'});
		}
	});

// make sure form fields are cleared when page loads
	$('#freeform').resetForm();

// create the tell-a-friend dialog and overlay, hiding them off to the left of the window
var thanks = [
	'<div id="thanks">',
	'<h1>Thank you for helping us select the first 5 Presidents to be featured in The Presidential Park & Gardens&trade; logo</h1>',
	'<p><a href="/">Click here to go back to the homepage, or...</a></p>',
	'<p class="big_button"><a href="/tellafriend">Click here to forward this to a friend!</a></p>',
	'</div>'
].join('');
$(thanks).css({left: '-9000em'}).appendTo('body');

// validate form before submit

	var preparePresidents = function() {
		var errorCount = 0;
		var errorMsg = '<ol>';
		$('#error').remove();
		var tName = $('#name').val().replace(/^\s+/,'').replace(/\s+$/,'');
		var tEmail = $('#email').val().replace(/^\s+/,'').replace(/\s+$/,'');    
		if ($('#picks li').length==5) {
      
		} else {
			errorMsg += '<li>Five Presidents must be selected.</li>';
			errorCount++;
		}
		if (!tName) {
			errorMsg += '<li>Name is a required field.</li>';
			errorCount++;
		}
		if (!tEmail) {
			errorMsg += '<li>Email Address is a required field.</li>';
			errorCount++;      
		} else if (!(/.+@.+\.[a-zA-Z]{2,4}$/).test(tEmail)) {
			errorMsg += '<li>Email Address needs to be in the proper format (for example, name@example.com).</li>';
			errorCount++;
		}
		if (errorCount) {
			var plural = errorCount > 1 ? errorCount + ' errors' : 'error';	  
			var preMsg = '<div id="error"><p>Please correct the following ' + plural + ' before casting your vote:</p>';
			errorMsg = preMsg + errorMsg + '</ol></div>';
			$('#ballot_inner').append(errorMsg);
			return false;
		}
	};
	
// on successful form submission, clear out a bunch of stuff and then, 
// if person hasn't cast a ballot before, do the lightbox thing.
	var formResponse = function(responseText) {
		$('#error').remove();
		$('#pres_list div.selected').css({backgroundPosition: '0 0'}).removeClass('selected');
		$('#freeform').resetForm();
		pickCount = 0;
		
		if ( (/No duplicate postings/).test(responseText) ) {
			$('<div id="error"><p>Sorry! You may only vote once.</p><p><a href="/">Click here to go back to the homepage.</a></p></div>').appendTo('#ballot_inner');
			$('#pres_list div.select').unbind('click');
		} else {
			var $thanks = $('#thanks');
			var docWidth = $(document).width(), docHeight = $(document).height(), 
				winWidth = $(window).width(), 
				//winHeight = $(window).height(),
				winHeight = window.innerHeight || document.documentElement && document.documentElement.clientHeight || document.body.clientHeight,
				sTop = $(window).scrollTop(), tHeight = $thanks.height() + parseInt($thanks.css('paddingTop')) + parseInt($thanks.css('paddingBottom')) + parseInt($thanks.css('marginTop')) + parseInt($thanks.css('marginBottom'));
				$('<div id="overlay"></div>').appendTo('body').css({position: ($.browser.msie && $.browser.version < 7) ? 'absolute' : 'fixed', width: docWidth, height: docHeight, opacity: '0.5' });

			$thanks.css({
				top: ((sTop + winHeight/2) - tHeight/2) + 'px', 
				left: winWidth/2 - 325
			});
			$('<div id="overlay"></div>').css({position: ($.browser.msie && $.browser.version < 7) ? 'absolute' : 'fixed', width: docWidth, height: docHeight, opacity: '0.5' }).appendTo('body').click(function() {
				$(this).add('#thanks').fadeOut('slow', function() {
					window.location = 'http://www.presidentialpark.com/';
				});
			});
		}

	};
 
//set options and submit the form 
	var formOptions = {
	beforeSubmit: preparePresidents,
		success: formResponse
	};
	$('#freeform').ajaxForm(formOptions);
 
// utility function for getting the scrollTop position
	$.fn.extend({ 
		scrollTop: function(val) {
			if (!this[0]) error();
			if ( val != undefined )
				// set the scroll top
				return this.each(function() {
					if (this == window || this == document)
						window.scrollTo( $(window).scrollLeft(), val );
					else
						this.scrollTop = val;
				});
		
			// return the scroll top offset in pixels
			if ( this[0] == window || this[0] == document )
				return self.pageYOffset ||
					$.boxModel && document.documentElement.scrollTop ||
					document.body.scrollTop;

			return this[0].scrollTop;
		}
	});
});

