$(document).ready(function() {

	/* initially redirect the site for mobile devices */
  try {
          // This is the URL where mobile
          detectmobile.defaultMobileURL = "http://youth.opendoorsuk.org/mobile/";
          detectmobile.process();
  } catch(e) {
          // Make sure that in the fault modes
          // we do not interrupt execution of other Javascript code
  }	

	/* Invoke youtube playlist */
	$("ul#thumbs").ytplaylist();
	
	/* Invoke flex sliders on homepage/elsewhere */
	$('#feature-slider').flexslider({
		slideshow: false,
		directionNav: false
	});
	$('#banner-slider').flexslider({
		directionNav: false,
		controlNav: false
	});
	$('#story-slider').flexslider({
			directionNav: true,
			controlNav: false,
			slideshow: false
	});	
	$('#video-slider').flexslider({
			directionNav: true,
			controlNav: false,
			slideshow: false
	});		
		
	/* Social media button image rollovers */
		$('#fblink img').hover(function () {
      this.src = '/img/btn-fb-s.png';
  }, function () {
      this.src = '/img/btn-fb.png';
  });  
	$('#twitterlink img').hover(function () {
      this.src = '/img/btn-twitter-s.png';
  }, function () {
      this.src = '/img/btn-twitter.png';
  });   
	$('#ytlink img').hover(function () {
      this.src = '/img/btn-youtube-s.png';
  }, function () {
      this.src = '/img/btn-youtube.png';
  });    

	/* Resources page - downloads, expandable sections */
  $('section.resource-list').click(function () {
      var downloads = $(this).children('ul.downloads');
      if (downloads.is(':hidden')) {
          downloads.slideDown('200');
					$(this).addClass("opened");
      } else {
          downloads.slideUp('200');
					$(this).removeClass("opened");            
      }
  });
  
	/*	Our Story - OD History Timeline */
	$("#timeline article:gt(8)").toggle(); //show/hide layers
	$("#more-dates").click(function(e){	//handle show more click
		$("#timeline article:gt(8)").toggle(); //show/hide layers
		e.preventDefault(); //no link action needed
	});
	
	
	$("#more-dates").toggle(function (){
	    $("#more-dates h3").text("Show Less Dates")
	    .stop();
	}, function(){
	    $("#more-dates h3").text("Show More Dates")
	    .stop();
	});
	
	/* invoke get latest tweet */
	// $('#tweet').jtwt({image_size : 0, count : 1, username: 'opendoorsyouth', convert_links : 1, loader_text : 'Tweet Loading!'});	
	
	// Privacy policy - hide all paragraphs just leave questions 
	$('#privacy-policies a').show();
	$('div.more').hide();
	// when hovering over show more link
	$("li a").click(function () { 
		var moretext = $(this).parent().parent().find("div.more");
		//  hide more link
		$(this).parent().parent().find("div.more:visible").slideUp("slow");
		// show more link
		$(this).parent().parent().find("div.more:hidden").slideDown("slow");	
	});
	
	/* Donation Form */

	/* Called to format final donation amount for secure trading */
	function cent(amount) {
		// returns the amount in the .99 format
		amount -= 0;
		return (amount == Math.floor(amount)) ?	
			amount + '.00' :
			(  (amount*10 == Math.floor(amount*10)) ? amount + '0' : amount);
	}
	
	/* filter input to numbers only */
	$("input.donation-field").keydown(function(event) {
		// Allow only backspace, delete and decimal points (and tabbing allows to move to next field)
		if ( event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 190 || event.keyCode == 9) {
			// let it happen, don't do anything
			if ($("#message").html().length > 0) $("#message").html("");
		}
		else {
			if ($("#message").html().length > 0) $("#message").html("");
			// Ensure that it is a number and stop the keypress
			if (event.keyCode < 48 || event.keyCode > 57 ) {
				event.preventDefault(); 
				$("#message").html("Please enter numeric values");	
			}       
		}
	});

	$("#currency").change(function () {
		var str = "";
		$("select option:selected").each(function () {
			$("#currency-icon").html($(this).text());
		});
	})
	.change();



	/* handle calculate button - on donate form */
	$('#calculate').click(function() {

		var total = 0;
		var donation_prefs = "";

		/* add up all of the entries */
		$("ul li.category").each(function() {
			var this_amount = parseFloat($("input", this).val());
			if (this_amount > 0) {
				total = total + parseFloat(this_amount);
				donation_prefs += $("label", this).html() + ": " + $("input", this).val() + "\n";
			}
		});
		$("#donationprefs").val(donation_prefs);
			
		/* format fields for totals */
		$('#total').val(cent(total));
		var amountArray = ($('#total').val() * 100).toString().split(".");
		$('#amount').val(amountArray[0]);
		return false;
	});
	
	/* validate donation form 1 - donation values */
	if ($('#donate1').length > 0) {
	
	var validator = $("#donate1").validate({
		rules: {
			total: {
				required: true,
				number: true,
				min: 1					
			}
		},
		messages: {
			total: {
				required: "First enter your donation amounts, then click calculate",
				number: "Not numeric",
				min: "Minimum total 1.00"
			}
		},
		errorPlacement: function(error, element) {
			error.insertAfter(element);
		}
	});
	
	// perform tasks on submit of donate form 1
	$('#donate1').submit(function() {	
		$('#donationprefs').val("I would like my donation to go towards:\n\n " + $('#donationprefs').val());
	});
	
	}
			
	/* validate donation form 2 - personal details */
	if ($('#donate2').length > 0) {
	var validator = $("#donate2").validate({
		rules: {
			forename: "required",
			surname: "required",
			address1: "required",
			town: "required",
			county: "required",
			postcode: "required",
			country: "required",
			email: {
				required: true,
				email: true
			},
			supporter: "required",
			Dob_Day: {
				number: true,
				range: [1, 31]
			},
			Dob_Month: {
				number: true,
				range: [1, 12]
			},
			Dob_Year: {
				number: true,
				range: [1950, 2080]
			}										
		},
		messages: {
			forename: "Required",
			surname: "Required",
			address1: "Required",
			town: "Required",
			county: "Required",
			postcode: "Required",
			country: "Required",
			email: {
				required: "Required", 
				email: "Invalid Email Address"
			},
			supporter: "Required",
			Dob_Day: {
				number: "Day Numeric only",
				range: "Day must be in range 1-31"
			},
			Dob_Month: {
				number: "Month Numeric only",
				range: "Month must be in range 1-12"
			},
			Dob_Year: {
				number: "Year Numeric only",
				range: "Year not valid"
			}
		},
		errorPlacement: function(error, element) {
			error.insertAfter(element.parent());
		}
	});		
	// perform tasks on submit of donate form 2
	$('#donate2').submit(function() {

		// Bring all DOB values into one field
		$('#dob').val($('#Dob_Day').val() + '/' + $('#Dob_Month').val() + '/' + $('#Dob_Year').val());  
		
		// Combine first name and last name
		$('#name').val($('#forename').val() + ' ' + $('#surname').val());
		
		// Combine address fields
		$('#address').val($('#address1').val());
		if ($('#address2').val() != '')
		{
			$('#address').val($('#address').val() + ',\n' + $('#address2').val());
		}
		if ($('#address3').val() != '')
		{
			$('#address').val($('#address').val() + ',\n' + $('#address3').val());
		}				

	});
	}
		
	/*	From donate form 3 you can either confirm that you are a taxpayer which 
		amends a couple of form values and presents a thank you message, OR
		click Next button, submitting immediately to Secure Trading to handle actual donation */
		
	// Handle confirmation of gift aid for tax payer users	
	$('#giftaid_button').click(function() {
		// Set hidden value on form
		$('#giftaiddonation').val("Yes");
		// Append gift aid declaration text to form input, it will be appended to merchant notification email
		$('#giftaidtext').val($('#giftaidtext_temp').val());
		// Replace contents of gift aid form with a Thank you message
		$('#gift_aid_declaration').html("<p>Thanks for your Gift Aid declaration. Click 'Next' to continue.</p>");
		$('#gift-aid-next-text').hide();
		return false;
	});
	
	// Submit donate 3 form
	$('#donate3').submit(function() {
		
		if ($('#giftaiddonation').val() == "Yes") {
			$('#orderinfo').val($('#orderinfo').val() + "Gift Aid Declaration - completed - I agree with the tax declaration. \n\n ");
		} else {
			$('#orderinfo').val($('#orderinfo').val() + "Gift Aid Declaration - Gift Aid NOT selected. \n\n ");
		}
		// Add donation prefs from the first form to the order info
		$('#orderinfo').val($('#donationprefs').val() + "\n" + $('#orderinfo').val());
		
		// Append to front, Open Doors Youth Classification
		$('#orderinfo').val("** OPEN DOORS YOUTH WEBSITE DONATION **\n\n" + $('#orderinfo').val()); 
		
	});
	
});





