$(document).ready(function(){
	/*
	* CONTEST PLUGIN STYLING
	*
	* Everything that has to do with the contest plugin.
	*
	* @author Sverri M. Olsen <sverri@moc.net>
	*
	*/
	/*------------------------------------------------------------------------------------------------
	*
	* If the contest form is not present then it means that it has already been submitted by the
	* user. In this case we will just show the confirmation page instead.
	*
	*/
	if ($("#contest-plugin form").attr("method") === undefined)
	{
		// Show the confirmation page
		$("#contest-plugin .success").show();
	}
	/*------------------------------------------------------------------------------------------------
	*
	* The contest form is present which means that the user has not submitted it yet. In this case
	* the form will be shown. When the form is successfully submitted the confirmation page will be
	* displayed. Next time the user visits this page the above IF expression will evaluate to TRUE
	* and this ELSE clause will be ignored.
	*
	* In this block we handle the:
	*
	*  1. checkbox overlay (an orange tick)
	*  2. form submission through AJAX, validation and report any errors
	*
	*/
	else
	{
		// The DIV element that holds the checkbox and label
		var subscribe = $("#contest-plugin .subscribe");

		// The checkbox's state (true=checked | false=unchecked)
		var state = (subscribe.find("#tick").attr("checked") === "checked");

		/*---------------------------------------
		*
		* 1. CHECKBOX
		*
		* Handle the checkbox overlay. This is slightly tricky because we have
		* to hide the actual INPUT element and recreate it, and then make it
		* interactive. This is done using a few SPAN elements that are styled
		* to mimic a box and a custom tick. When then box is clicked the tick
		* is toggle on and off.
		*
		* <div class="subscribe">
		*    <input id="tick" type="checkbox" name="tick" value="0" />
		*    <span class="dummy">
		*      <span class="box"></span>
		*      <span class="flueben"></span>
		*    </span>
		*    <label for="tick">Ja tak, jeg ønsker...</label>
		*  </div>
		*
		*/
		// If the checkbox is checked then make sure the tick and label color
		// is shown correctly
		if (state === true) {
			subscribe.find(".flueben").show();
			subscribe.find("label").css("color", "#222");
		}
		// Checkbox is not checked, hide the tick and dim the label color
		else {
			subscribe.find(".flueben").hide();
			subscribe.find("label").css("color", "#666");
		}
		// When either the dummy checkbox or the label is clicked
		subscribe.find(".dummy,label").click(function(){

			// Convenience
			var self = $(this).parent();

			// If the checkbox is checked then inactivate it
			if (state == true)
			{
				// Only if the actual input element was clicked, uncheck checkbox
				// Clicking on the label will do this for us automatically...
				if ($(this).attr("for") === undefined)
				self.find("#tick").removeAttr("checked");

				// Set the checkbox's value
				self.find("#tick").attr("value", "0");

				// Remove the tick and dim the label color
				self.find(".flueben").fadeOut(100);
				self.find("label").css("color", "#666");
			}
			else // If the checkbox is NOT checked then activate it
			{
				// Only if the actual input element was clicked, show checkbox
				// Clicking on the label will do this for us automatically...
				if ($(this).attr("for") === undefined)
				self.find("#tick").attr("checked", "checked");

				// Set the checkbox's value
				self.find("#tick").attr("value", "1");

				// Show the tick and undim the label color
				self.find(".flueben").fadeIn(100);
				self.find("label").css("color", "#222");
			}
			// Revert the checkbox's state
			state =! state;
		});

		/*---------------------------------------
		*
		* 2. FORM SUBMISSION
		*
		* Instead of submitting the form the usual way we will do an AJAX call
		* here. Before that we validate the form content.
		*
		*/
		// When an input field is not filled in properly it will turn red
		// This reverts it back to normal when focussed
		$("#contest-plugin form input#navn").focus();

		// When an input field is not filled in properly it will turn red
		// This reverts it back to normal when focussed
		$("#contest-plugin form :text").focus(function(){
			$(this).css({ backgroundColor:"#FFF", border:"1px #AAA solid" });
		});
		// When the form is submitted
		$("#contest-plugin form").submit(function(){

			// For when we send the AJAX call
			var formURL = $(this).attr("action");

			// The form
			var form = {
				// Name input field
				navn: {
					obj:   $(this).find("#navn"),
					value: jQuery.trim($(this).find("#navn").val()),
					valid: /^.{2,}/i.test( jQuery.trim($(this).find("#navn").val()) )
				},
				// Email input field
				email: {
					obj:   $(this).find("#email"),
					value: jQuery.trim($(this).find("#email").val()),
					valid: /(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])/i.test( jQuery.trim($(this).find("#email").val()) )
				},
				// Registration number input field
				regnr: {
					obj:   $(this).find("#regnr"),
					value: jQuery.trim($(this).find("#regnr").val()),
					// Jesper bad mig om at fjerne regnr validation (Sverri)
					//valid: /^[a-zæøå]{2}\s?[\d]{5}$/i.test( jQuery.trim($(this).find("#regnr").val()) )
					valid: true
				},
				// Subscription checkbox
				subsc: {
					obj:   $(this).find("#tick"),
					value: jQuery.trim($(this).find("#tick").val()),
					valid: /^[1|0]$/.test(jQuery.trim($(this).find("#tick").val()) )
				}
			};
			// If the form does not validate
			if ( ! (form.navn.valid && form.email.valid && form.subsc.valid)) // && form.regnr.valid
			{
				// Color in the input fields that are incorrect
				if ( ! form.navn.valid)  form.navn.obj.css({ backgroundColor:"#FFE2DB", border:"1px #F46725 solid" });
				if ( ! form.email.valid) form.email.obj.css({ backgroundColor:"#FFE2DB", border:"1px #F46725 solid" });
				//if ( ! form.regnr.valid) form.regnr.obj.css({ backgroundColor:"#FFE2DB", border:"1px #F46725 solid" });

				// Halt the form submissions
				return false;
			}
			// Convenience
			var self = $("#contest-plugin");

			// Hide the form, cnt...
			self.find("form").fadeOut(250, function(){

				// GET query string
				var theData = 'tx_appluscontest_contest[data][navn]='+form.navn.value
				+ '&tx_appluscontest_contest[data][email]='+form.email.value
				+ '&tx_appluscontest_contest[data][regnr]='+form.regnr.value
				+ '&tx_appluscontest_contest[data][subsc]='+form.subsc.value;

				// Send an AJAX request
				$.ajax({
					type:"POST",
					url:"/?eID=Tx_ApplusContest_Ajax",
					cache: false, // IE caches this request...
					data: theData, dataType: "json",

					// On success
					success: function(msg){

						// Replace the "[NAVN]" part of the first paragraph of the confirmation
						// page with the name value from the previous form.
						var firstp = self.find(".success p:first");
						firstp.text( firstp.text().replace(/\[NAVN\]/, form.navn.value) );

						self.css('background', '#fff url(/typo3conf/ext/applus_contest/Resources/Public/Images/success.png) 100% 0 no-repeat');

						// Show the confirmation page
						self.find(".success").fadeIn(500);

						// Remove the form from the DOM
						self.find("form").remove();
					},
					// On error
					error: function(x){

						// Show the confirmation page
						self.find(".failure").fadeIn(500);

						// Return back to form
						$(".failure a").click(function(){
							$(".failure").fadeOut(function(){
								$("#contest-plugin form").fadeIn();
							});
							return false;
						});
					}
				});

			});
			// Prevent default behaviour
			return false;
		});
		//---------------------------------------
	}
	/*
	* END OF CONTEST PLUGIN
	*
	------------------------------------------------------------------------------------------------*/
});
