(function ($) {
	
	$.fn.v1EventsPH = function (opts) {
		
		var settings = $.extend({
					handler: "handlers/events_ph.cfm"
				}, opts)
			,	selector = this.selector;
		
		var getTabSection = function (href) {
			var params = {}
				,	ret = "eventBookingForm";
			try {
		  	var tokens = href.split("?")[1].split("&");
		  	$.each(tokens, function(i, p){
		  		var keyVal = p.split("=");
		  		params[keyVal[0]] = keyVal[1];
		  	});
		  } catch (ex) {}
			if (params.evetab) ret = params.evetab;
			return ret;
		}
		
		var makeBooking = function (ev) {
			ev.preventDefault();
			ev.stopPropagation();
			var $this = $(this)
				,	$name = $this.find("#bookingName")
				,	$email = $this.find("#bookingEmail")
				,	errors = false;
			$this.find(".error").remove();
			if (!$name.val().replace(/\s/g, "").length) {
				$("<p class=\"error\">Please enter your name</p>")
					.insertAfter($name);
					errors = true;
			}
			if (!$email.val().replace(/\s/g, "").length) {
				$("<p class=\"error\">Please enter a valid email</p>")
					.insertAfter($email);
					errors = true;
			}
			if (!errors) {
				$.ajax({
						url: settings.handler + "ffsaf?evetab=eventBookingForm"
					, data: $this.serialize()
					,	success: function (html) {
							if (html) {
								var $eventsPH = $this.closest(selector);
								$this.parent().remove();
								$eventsPH
									.append(html)
									.find("form")
									.submit(makeBooking);
							}
						}
					, error: function () {
								$this.unbind("submit", makeBooking);
								$this.submit();
						}
					,	dataType: "html"
					, type: "POST"
				});
			}
		}
		
		this.each(function (i, el) {
			var $this = $(el)
				,	$tabs = $this.first(".eventTabs").find("a")
				,	$sections = $this.find(".eventSection");
			$tabs.bind("click", function (ev) {
				ev.preventDefault();
				var sectionId = getTabSection(this.href)
					,	$section = $("#" + sectionId)
					, $tab = $(this);
				$tabs.removeClass("selected");
				$tab.addClass("selected");
				if (!$section[0]) {
					$.ajax({
							url: settings.handler
						, data: {evetab: sectionId}
						,	success: function (html) {
								if (html) {
									$sections.css("display", "none");
									$this.append(html);
									$sections = $this.find(".eventSection");
									$this.find("form").submit(makeBooking);
								}
							}
						,	dataType: "html"
						, type: "GET"
					});
				} else {
					$sections.css("display", "none");
					$section.css("display", "block");
				}
			});
			$this.css("min-height", $this.height());
		});
		
		return this;
	}
	
})(jQuery);
