function validate_form(form) {
	var submit = true;
	form.find('input.required, textarea.required, select.required').each(function() {
		var field = $(this), 
			value = field.val(),
			parent, error_message;
		
		if (value == '' || value == field.data('default-value')) {
			submit = false;
			parent = field.parent('div.fieldWithErrors');
			if (parent.length == 0) {
				field.wrap('<div class="fieldWithErrors" />');
				parent = field.parent('div.fieldWithErrors');
			}
			error_message = parent.next('div.formError');
			if (error_message.length == 0) {
				parent.after('<div class="formError">* required</div>');
			}
		}
	});
	
	setTimeout(function() {
		// Fade them all out
		$('.fieldWithErrors').removeClass('fieldWithErrors');
		$('.formError').remove();
	}, 5000);
	
	return submit;
}

function show_confirmation(message, form) {
	var html = $('<div class="confirmation">\
		<h4><img src="../images/confirm.png" width="30" />'+message+'</h4>\
	</div>');
	form.after(html);
	setTimeout(function() {
		html.remove();
	}, 5000);
}


var ShareForm = {
	
	/**
	 * Show the share popup
	 */
	show: function(theLink) {
		var old_box = $('#popoverWrap');
		if (old_box) ShareForm.hide();
		
		var href	= encodeURIComponent(theLink.href);
		var title	= encodeURIComponent(theLink.title);
		var html = '<div id="popoverWrap"> \
			<div id="popoverFront"> \
				<div class="popoverTL"></div> \
				<div class="popoverTR"><a onclick="ShareForm.hide(); return false;" class="close-button"></a></div> \
				<div class="popoverMiddle-top"><div class="popoverMiddleInside"></div></div> \
				<div class="popoverLeft"> \
					<div class="popoverRight"> \
						<div class="popoverContentwrap clearfix"> \
							<div class="popoverContent" style="opacity: 1;"> \
								<div id="popnav"> \
									<ul> \
										<li><a href="#" onclick="ShareForm.showTab(0); return false;" class="shareLink active">Share</a></li> \
										<li><a href="#" onclick="ShareForm.showTab(1); return false;" class="shareLink">Email</a></li> \
									</ul> \
								</div> \
								<div id="shareContent-social" class="shareContent clearfix"> \
									<div class="solvr-box-1"> \
										<div class="modulebox"> \
											<ul class="linkItem"> \
												<li><a href="http://del.icio.us/post?url='+href+'&amp;title='+title+'" target="_blank"><img align="top" src="../images/icons/delicious.png" alt="Del.icio.us" /> Del.icio.us</a></li> \
												<li><a href="http://digg.com/submit?phase=2&amp;url='+href+'&amp;title='+title+'" target="_blank"><img align="top" src="../images/icons/digg.png" alt="Digg" /> Digg</a></li> \
												<li><a href="http://www.google.com/bookmarks/mark?op=edit&amp;bkmk='+href+'&amp;title='+title+'" target="_blank"><img align="top" src="../images/icons/goog.png" alt="Google" /> Google</a></li> \
												<li><a href="http://myweb2.search.yahoo.com/myresults/bookmarklet?u='+href+'&amp;t='+title+'" target="_blank"><img align="top" src="../images/icons/yahoo-myweb.png" alt="Yahoo MyWeb" /> Yahoo MyWeb</a></li> \
												<li><a href="http://www.stumbleupon.com/submit?url='+href+'&amp;title='+title+'" target="_blank"><img align="top" src="../images/icons/su.png" alt="StumbleUpon" /> StumbleUpon</a></li> \
												<li><a href="http://technorati.com/faves?add='+href+'" target="_blank"><img align="top" src="../images/icons/technorati.png" alt="Technorati" /> Technorati</a></li> \
											</ul> \
										</div> \
									</div> \
									<div class="solvr-box-2"> \
										<div class="modulebox"> \
											<ul class="linkItem"> \
												<li><a href="http://www.facebook.com/sharer.php?u='+href+'&amp;t='+title+'" target="_blank"><img align="top" src="../images/icons/facebook.gif" alt="Facebook" /> Facebook</a></li> \
												<li><a href="http://twitter.com/home?status='+title+': '+href+'" target="_blank"><img align="top" src="../images/icons/twitter.jpg" alt="Twitter" /> Twitter</a></li> \
												<li><a href="http://www.newsvine.com/_tools/seed&amp;save?u='+href+'&amp;h='+title+'" target="_blank"><img align="top" src="../images/icons/newsvine.png" alt="Newsvine" /> Newsvine</a></li> \
												<li><a href="http://reddit.com/submit?url='+href+'&amp;title='+title+'" target="_blank"><img align="top" src="../images/icons/reddit.gif" alt="Reddit" /> Reddit</a></li> \
												<li><a href="https://favorites.live.com/quickadd.aspx?marklet=1&amp;mkt=en-us&amp;url='+href+'&amp;title='+title+'&amp;top=1" target="_blank"><img align="top" src="../images/icons/live.gif" alt="Windows Live" /> Windows Live</a></li> \
											</ul> \
										</div> \
									</div> \
								</div> \
								<div id="shareContent-email" class="shareContent" style="display: none;"> \
									<form method="post" action="../share.php" class="formBox" id="shareForm"> \
										<input type="hidden" value="'+theLink.href+'" name="url"/> \
										<p><label>To Email:</label> <input type="text" name="to_email" class="inputbox"/></p> \
										<p><label>From Email:</label> <input type="text" name="from_email" class="inputbox"/></p> \
										<p><label>Your Name:</label> <input type="text" name="from_name" class="inputbox"/></p> \
										<p> \
											<label>Message:</label> \
											<textarea name="message" class="inputbox" cols="35" rows="5">Take a look at this...\n\nTitle: '+theLink.title+'\nURL: '+theLink.href+'</textarea> \
										</p> \
									</form> \
									<div class="clearfix" id="form-buttonset"> \
										<div style="margin: 5px auto; width: 150px;" class="clearfix"> \
											<div style="margin: 0pt 1px; line-height: 22px;" class="solvr-box-1 clearfix"> \
												<a onclick="ShareForm.submit(); return false;" href="#" class="button"><span><span>Send</span></span></a> \
											</div> \
											<div style="margin: 0pt 1px; line-height: 22px;" class="solvr-box-2"> \
												<a onclick="ShareForm.hide(); return false;" href="#" class="button"><span><span>Cancel</span></span></a> \
											</div> \
										</div> \
									</div> \
								</div> \
							</div> \
						</div> \
					</div> \
				</div> \
				<div class="popoverBR"></div> \
				<div class="popoverBL"></div> \
				<div class="popoverMiddle-bottom"><div class="popoverBottomInside"></div></div> \
			</div> \
		</div>';
		$('body').append(html);

		// add the social bookmarking link functions
		$('#shareContent-social a').click(function(event) {
			window.open(this.href, 'bookmarkWindow', 'width=700,height=400');
			event.preventDefault();
		});
		
		// Position the Form
		var link = $(theLink),
			container = $('#popoverWrap')
			offset = link.offset(),
			top = offset.top - container.height(),
			left = offset.left - 70;
		container.css({top: top, left: left}).show();
	},
	
	hide: function() {
		$('#popoverWrap').remove();
	},
	
	showTab: function(activeIndex) {
		var container = $('#popoverWrap');
		
		container.find('.shareLink').each(function(index) {
			if (index == activeIndex)
				$(this).addClass('active');
			else
				$(this).removeClass('active');
		});
		container.find('.shareContent').each(function(index) {
			if (index == activeIndex)
				$(this).show();
			else
				$(this).hide();
		});
	},
	
	submit: function() {
		var form = $('#shareForm');
		$.post(form.attr('action'), form.serialize(), function(data) {
			if (data.status == 'SUCCESS') {
				form.hide();
				show_confirmation(data.message, form);
				setTimeout("ShareForm.hide()", 5000);
			}
			else {
				show_confirmation(data.message, form);
			}
		});
	}

};


$(document).ready(function() {
	$('.btn_reserve').click(function(event) {
		var container = $(this).closest('.coming_event');
		var form = $('#reserve');
		var date = container.find('h2').text();
		
		form.find('h2').text(date);
		form.find('input[name=EventDate]').val(date);
		
		container.hide();
		form.show();
		event.preventDefault();
	});
	
	$('#reserve_back_link').click(function(event) {
		$('.coming_event').first().show();
		
		$('#reserve').hide();
		event.preventDefault();
	});
		
	$('input.default-value, textarea.default-value').each(function() {
		var input = $(this);
		
		// Save the default value
		input.data('default-value', input.val());
		
		input.focus(function() {
			var e = $(this);
			if (e.val() == e.data('default-value'))
				e.val('');
		}).blur(function() {
			var e = $(this);
			if (e.val() == '')
				e.val(e.data('default-value'));
		});
		input.removeClass('default-value');
	});
	
	// Setup link behaviours
	$('a').click(function(event) {
		var e = $(this);

		if (e.hasClass('show')) {
			var id = e.attr('href'),
				target = $(id);
			
			$.each(target[0].className.split(/\s+/), function() {
				// Index 1 because the first char is a #
				if (id.indexOf(this) == 1)
					$('.'+this).hide();
			});
			
			target.show();
			event.preventDefault();
		}
		if (e.hasClass('hide')) {
			$(e.attr('href')).hide();
			event.preventDefault();
		}
		if (e.hasClass('toggle')) {
			var target = $(e.attr('href'));
			if (target.css('display') == 'none') {
				target.show();
				if (e.hasClass('collapsed'))
					e.removeClass('collapsed').addClass('expanded');
			}
			else {
				target.hide();
				if (e.hasClass('expanded'))
					e.removeClass('expanded').addClass('collapsed');
			}
			event.preventDefault();
		}
		if (e.hasClass('self-destruct')) {
			e.remove();
			event.preventDefault();
		}
		if (e.hasClass('submit-form')) {
			var form = e.closest('form'),
				action = form.attr('action');

			event.preventDefault();

			if (validate_form(form) == false)
				return;

			$.post(action, form.serialize(), function(data) {
				if (data.status == 'SUCCESS') {
					show_confirmation(data.message, form);
					form.hide();
					
					if (action == '../reserve.php') {
						setTimeout(function() {
							$('#coming_event').show();
							$('#btn_reserve').show();
						}, 5000);
					}	
				} else {
					show_confirmation(data.error, form);
				}
			});
		}
		if (e.hasClass('reset-form')) {
			// We need [0] here to access the actual element
			// because reset() is not a jQuery function
			e.closest('form')[0].reset();
			event.preventDefault();
		}
		if (e.hasClass('show-table-item-details')) {
			var details = e.closest('tr').next();
			if (e.hasClass('expanded')) {
				e.removeClass('expanded').addClass('collapsed');
				details.hide();
			}
			else {
				e.removeClass('collapsed').addClass('expanded');
				details.show();
			}
			event.preventDefault();
		}
		if (e.hasClass('edit-item-inline')) {
			var href = e.attr('href');
			$('#edit-item-tab').show().children('a').click();
			$('#edit-item-form').show().show_ajax_loader().load(href, function() {
				$(this).setup_pingsta_ui();
			});
			window.scrollTo(0, 0);
			event.preventDefault();
		}
		if (e.hasClass('reset-inline-form')) {
			// Use css('display', 'none') instead of hide().
			// It sets display: list-item; on restore, which would break the design
			$('#edit-item-tab').css('display', 'none').closest('ul')
				.find('li').removeClass('active')
				.find('a').removeClass('expanded').addClass('collapsed');
			$('div.inline-form').hide();
			$('#edit-item-form').empty();
			event.preventDefault();
		}
		if (e.hasClass('open-dialog')) {
			$.get(e.attr('href'), function(data) {
				var dialog = $(data).appendTo(BODY).dialog({
					width: 450
				});
				dialog.setup_pingsta_ui().find('a.cancel').click(function(event) {
					dialog.dialog('close');
					event.preventDefault();
				});
			});
			event.preventDefault();
		}
		if (e.hasClass('sharelink')) {
			ShareForm.show(this);
			event.preventDefault();
		}
		if (e.hasClass('zoom-image')) {
			var img = e.find('img');
			img.css('width', '430px');
			e.parent().find('img').not(img).css('width', '30px');
			event.preventDefault();
		}
	});
	
	// Language selection
	$('a.language').click(function(event) {
		$(this).addClass('active');
		$('ul.language').show();
		event.preventDefault();
	});
	$('body').click(function(event) {
		if (event.target.tagName != 'A') {
			$('a.language').removeClass('active');
			$('ul.language').hide();
		}
	});
	
	// Custom behaviour for speaker tabs
	$('ul.event_title').delegate('a', 'click', function() {
		$(this).closest('li').addClass('active').siblings().removeClass('active');
	});
	
	// (Fade-)Slideshow
	$('.fadeshow').each(function() {
		var items = $(this).children(),
			first = items.first(),
			visible = first;
		items.hide();
		first.show();
		
		setInterval(function() {
			var n = items.index(visible) + 1;
			if (n == items.length)
				n = 0;
			var next = items.slice(n, n + 1);
			visible.fadeOut();
			next.fadeIn();
			visible = next;
		}, 7000);
	});
	
	// Expand/collapse for news
	$('div.news h2 a').click(function(event) {
		$('div.news').removeClass('collapse');
		$('div.feed_entry').hide();
		$(this).closest('div.news').addClass('collapse').find('div.feed_entry').show();
	});
	
	// Fake a click on the news item if the URL points to it
	var m = location.hash.match(/\d+/);
	if (m != null)
		$('a[name='+m[0]+']').click();
	else if (location.hash.length > 0)
		$('a[href='+location.hash+']').click();
});

