$(function() {

	$(".sf-menu").superfish();

	$("body").pngFix();

	// enable the show hide feature for the front page
	BoxToggle(".event-description");
	$(".event-description h4").css("display", "inline");

	$(".accordion").accordion({
		autoHeight: false,
		event: null,
		header: 'h2',
		navigation: true
	});

	// registering page
	$(".edit-step").addClass("hide");
	$(".edit-step1").click(function() {
		$(".edit-step").addClass("hide");
		$(".accordion").accordion('activate', 0);

		return false;
	});
	$(".edit-step2").click(function() {
		$(".edit-step2").addClass("hide");
		$(".accordion").accordion('activate', 1);

		return false;
	});


	$(".step1-continue").click(function() {
		if (Page_ClientValidate("UserInfo")) {
			$(".edit-step1").removeClass("hide");
			$(".accordion").accordion('activate', 1);
		}

		return false;
	});
	$(".step2-continue").click(function() {
		if ($(".user-is-registrant input[type=checkbox]").is(":checked") || $(".previous-registrants").val() != "0" || Page_ClientValidate("RegistrantInfo")) {

			// grab the quantity of tickets
			// and send to service to validate availability
			var isGroupOption = $(".group input[type = radio]").is(":checked");

			var singleTicketQuantity = $(".singleticket-quantity option:selected").val();
			var numberOfRegistrants = $(".registrant").size();

			var quantity = (singleTicketQuantity ? singleTicketQuantity : numberOfRegistrants);
			quantity += $(".user-is-registrant input[type=checkbox]").is(":checked") ? 1 : 0;

			if (isGroupOption) {
				quantity = GetQuantity($(".group-quantity option:selected").val());
			}
			else {
				quantity = GetQuantity(quantity);
			}

			ValidateAvailability(sessionId, quantity, isGroupOption);
		}

		return false;
	});


	// ensure correct view
	TogglePreviousRegistrant();
	$(".previous-registrants").change(function(val) {
		TogglePreviousRegistrant();
	});


	// time and date controls
	$(".datepicker").datepicker();
	$(".datepicker.start, .datepicker.end").datepicker({ minDate: 0 });
	$("input.timepicker").timepickr({ convention: 12 });

	$(".TB_closeWindowButton").click(function() {
		tb_remove();
		location.reload();
	});

	$(".TB_internalCloseWindow").click(function() { // called when you click ok or something
		parent.tb_remove();
		parent.location.reload();
	});

	// registrant list control
	registrantCount = $(".registrant").size();

	$("#add").click(function() {
		registrant.cloneAndAddTo($("#registrants"));
		$(".registrant:last").find("input:first").focus();
	});

	$("a.remove-registrant:gt(0)").live("click", function() {
		$(this).parent("div.registrant").animate({
			opacity: "toggle",
			height: "toggle"
		}, 200,
		function() {
			$(this).remove();
		});
		return false;
	});
});


function TogglePreviousRegistrant() // make this work
{
    var selectedVal = $(".previous-registrants").val();

    if (selectedVal == "0" || selectedVal == undefined) {
        $("#new-registrant").show();
    }
    else {
        $("#new-registrant").hide();
    }
}

function ShowPrice()
{
	var price = $(".single-price").html();
	var priceMember = $(".single-price-member").html();
	var priceGroup = $(".group-price").html();
	var priceGroupMember = $(".group-price-member").html();
	
	var isMember = $(".is-member input[type=checkbox]").is(":checked");
	var isGroupOption = $(".group input[type = radio]").is(":checked");

	var singleTicketQuantity = $(".singleticket-quantity option:selected").val();
	var numberOfRegistrants = GetRegistrantCount();

	var quantity = (singleTicketQuantity ? singleTicketQuantity : numberOfRegistrants);
	quantity += $(".user-is-registrant input[type=checkbox]").is(":checked") ? 1 : 0;
	var total;
	
	if (isMember) {
		if (isGroupOption) {
			quantity = GetQuantity($(".group-quantity option:selected").val());
			total = priceGroupMember * quantity;
		}
		else {
			quantity = GetQuantity(quantity);
			total = priceMember * quantity;
		}
	}
	
	else {
		if (isGroupOption) {
			quantity = GetQuantity($(".group-quantity option:selected").val());
			total = priceGroup * quantity;
		}
		else {
			quantity = GetQuantity(quantity);
			total = price * quantity;
		}
	}
	
	$("#total-cost").html(total);
}


function GetQuantity(quantity)
{
    if (!quantity) return 1;
    else return quantity;
}


function ValidateAvailability(sessionId, quantity, group)
{
    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "/OCA.User/CheckRegistrationAvailability.asmx/Check",
        data: "{sessionId: " + sessionId + ",quantity: " + quantity + ",group: " + group + "}",
        dataType: "json",
        success: function (result) {
            if (result.d == true) {
                ShowFinalRegistrationStep();
                $(".registrations-full").hide(100);
            }
            else {
                $(".registrations-full").hide(100);
                $(".registrations-full").show(100);
            }
        }
    });
}


function GetRegistrantCount() {
	return $(".registrant").filter(function() {
		var obj = $(this);
		var firstname = obj.children("input.firstname").val();
		var lastname = obj.children("input.lastname").val();
		return firstname.length > 0 && lastname.length > 0;
	}).size();
}


function ShowFinalRegistrationStep() {
	var registrantsCount = GetRegistrantCount();

	if (registrantsCount > 0 || $(".user-is-registrant input[type=checkbox]").is(":checked")) {

		$(".edit-step2").removeClass("hide");
		$(".accordion").accordion("activate", 2);

		var isMember = $(".is-member input[type=checkbox]").is(":checked");

		if (isMember) {
			$("#invoice-option").show();
		}

		else {
			$("#invoice-option").hide();
		}

		$(".registrants-error").hide();
		ShowPrice();
	}

	else {
		$(".registrants-error").show();
	}
}


tinyMCE.init({
    // General options
    mode: "textareas",
    editor_deselector : "mceNoEditor",

    theme : "advanced",
    plugins : "safari,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template",

    // Theme options
    theme_advanced_buttons1 : "bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,formatselect,fontselect,fontsizeselect,|,sub,sup,|",
    theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,|,forecolor,backcolor",
    theme_advanced_buttons3 : "hr,removeformat,|,ltr,rtl",
    //theme_advanced_buttons4 : "insertlayer,moveforward,movebackward,absolute,|,styleprops,|,cite,abbr,acronym,del,ins,attribs,|,visualchars,nonbreaking,template,pagebreak",
    theme_advanced_toolbar_location : "top",
    theme_advanced_toolbar_align : "left",
    theme_advanced_statusbar_location : "bottom",
    theme_advanced_resizing : true,

    // Example content CSS (should be your site CSS)
    content_css : "/_Styles/prototype.css",

    // Drop lists for link/image/media/template dialogs
    template_external_list_url : "lists/template_list.js",
    external_link_list_url : "lists/link_list.js",
    external_image_list_url : "lists/image_list.js",
    media_external_list_url : "lists/media_list.js",

    // Replace values for the template plugin
    template_replace_values : {
        username : "Some User",
        staffid : "991234"
    }
   });

   /** BoxToggle */

function BoxToggle(selector) {

	$(selector).each(function() {

		var box = $(this);
		// Get the first ahd highest heading (prioritising highest over first)
		var firstHeading = box.find("h1, h2, h3, h4, h5")[0];
		// Select the heading's ancestors
		var headingAncestors = $(firstHeading).parents();
		// Add in the heading
		var headingAncestors = headingAncestors.add(firstHeading);
		// Restrict the ancestors to the box
		headingAncestors = headingAncestors.not(box.parents());
		headingAncestors = headingAncestors.not(box);
		// Get the siblings of ancestors (uncle, great uncle, ...)
		var boxContents = headingAncestors.siblings();


		// *** HIDE/SHOW LINK ***

		var toggleLink = $("<div style=\"float:right\"><a href='#'></a></div>");
		toggleLink.insertAfter(firstHeading);


		// *** TOGGLE FUNCTIONS ***

		var hideBox = function() {
			toggleLink.one("click", function() {
				showBox();
				return false;
			})
			toggleLink.children("a").text("Show Details")
			toggleLink.attr("class", "box-toggle-show");

			boxContents.attr("style", "display:none");
		}

		var showBox = function() {
			toggleLink.one("click", function() {
				hideBox();
				return false;
			});
			toggleLink.children("a").text("Hide Details");
			toggleLink.attr("class", "box-toggle-hide");

			boxContents.removeAttr("style");
		}

		// Initiate
		hideBox();
	});

}

var registrantCount = 1;

var registrant = {
	cloneAndAddTo: function(container) {
		var clonedItem = $(".registrant:first").clone();
		clonedItem.find("label.firstname").attr("for", "tbFirstName-" + registrantCount);
		clonedItem.find("label.lastname").attr("for", "tbLastName-" + registrantCount);
		clonedItem.find("input.firstname")
			.attr("id", "tbFirstName-" + registrantCount)
			.attr("name", "FirstName[" + registrantCount + "]")
			.val('');
		clonedItem.find("input.lastname")
			.attr("id", "tbLastName-" + registrantCount)
			.attr("name", "LastName[" + registrantCount + "]")
			.val('');
		registrantCount++;
		clonedItem.appendTo(container)
			.hide()
			.animate({
				opacity: "toggle",
				height: "toggle"
			}, 200);
	},
	addRegistrant: function(firstName, lastName) {
		registrant.cloneAndAddTo($("#registrants"));
		$("#registrants .registrant:last").find("input.firstname").val(firstName);
		$("#registrants .registrant:last").find("input.lastname").val(lastName);
	}
}
