(function($){
	$(document).ready(function() {
		$('input[type=text], textarea').focus(function(){
			var currentVal = $(this).val();										// Read initial field value
			$(this).val('');														// Clear initial value

			$(this).blur(function(){
				var getNewVal = $(this).val();										// Read new input value
				if ( getNewVal == '' || getNewVal == ' ' ) {
					$(this).val(currentVal);										// Switch to initial value
				}
			});
		});
		
		// fix PNG for IE6
		if ( $.browser.msie && $.browser.version == '6.0' ) {
			$('.emailer div.inside p:last-child').css('margin-bottom','0');
			DD_belatedPNG.fix('div, a, img, li');
		}

		// remove any borders on last LI element
		$("ul").not('#navigator, .history, #ticker, .partnersList, #days, #colors, .boxes, #browse .col ul, .find-more ul, .xmas ul').each(function(){
			 $(this).children("li:last").css({borderRight:"0",borderBottom:"0",background:"none",padding:"0",margin:"0"});
		});

		// key
		if ( $('#timetableKey h3 a').length ){
			$('#timetableKey h3 a').click(function(){
				$(this).toggleClass('opened').parent().next().slideToggle();

				return false;
			});
		}

		$("ul.history").each(function(){
			 $(this).children("li:last").css({marginBottom:"0"});
		});
		
		if ( $('.emailer').length ){
			var countPara = $('.emailer').length;
			var name = [ "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten" ];			

			for ( var i = -1; i <= countPara; i++ ){
				$('.emailer:nth-child('+ i +')').prepend('<a href="?'+ name[i] +'"></a>');
				$('.emailer:nth-child('+ i +')').prepend('<a name="'+ name[i] +'"></a>');
			}
		}
		
		if ( $('.xmas').length ){
			var countLi = $('.xmas>ul>li').length;
			var nameHash = [ "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten" ];

			for ( var i = -1; i <= countLi; i++ ){
				$('.xmas>ul>li:nth-child('+ i +')').prepend('<a href="?'+ nameHash[i] +'"></a>');
				$('.xmas>ul>li:nth-child('+ i +')').prepend('<a name="'+ nameHash[i] +'"></a>');
			}
		}

		// google map for location page
		// http://maps.google.com/maps?f=q&source=s_q&hl=en&geocode=&q=EC2A+3HH&sll=37.0625,-95.677068&sspn=53.564699,111.09375&ie=UTF8&hq=&hnear=London+EC2A+3HH,+United+Kingdom&t=h&z=16
		if ( $('#displayMap').length ) {
			$('#displayMap').gMap({
				markers: [{
					address: 'EC2A 3HH',
					icon: { image: "images/buttons/mappointer.gif",
						  iconsize: [80, 51],
						  iconanchor: [65,28],
						  infowindowanchor: [40, 2] },
					html: "1-6 Bateman's Row<br />London<br />EC2A 3HH",
					popup: true
					}],
				zoom:17
				});
		}

		// run accordion

		if ( $('ul#days li').length > 1 ){
		    var date = new Date();
			var day  = date.getDay();
			document.getElementById('__day'+(day-1)).className="current";
			if ( $("ul#days").is(".no-auto-open") ){
				$("ul#days li").removeClass("current").eq(0).addClass("current");
			}

			$('ul#days').accordion();
		}

		// cycle ticker
		$('#ticker').cycle({
			fx: 'scrollHorz',
			speed:    300,
            timeout:  5000,
			pause:     1
		});

		// cycle masthead
		$('#masthead').cycle({
			fx: 'fade',
			speed:    500,
            timeout:  10000
		});

		// animation in A navigation
		$('#navigator li a')
		.not('.on')
		.css( {backgroundPosition: "0 0"} )
		.mouseover(function(){
			$(this).stop().animate({backgroundPosition:"-143px 0"}, {duration:500});			
		})
		.mouseout(function(){
			$(this).stop().animate({backgroundPosition:"1px 0"}, {duration:200, complete:function(){
				$(this).css({backgroundPosition: "0 0"});
			}})
		});

		// current year in footer
		if ( $('#currentYear').length ){
			var _year = new Date();
			$('#currentYear').text(_year.getFullYear());
		}

		$(".services .hoverable").hoverpopup({width: 909, height: 372, container: '#content'});

		// select box - other,please specify
		$("form select#goal").change(function(){
			if ( $(this).val() == 'other' ){
				$("#goal-specify").show();
			}else{
				$("#goal-specify").hide();
			}
		}).change();

		// select box on homepage
		$("form select#wantto").change(function(){
			if ( $(this).val() == 'comment' ){
				$("#commentRow").show();
				$("#moreRow").hide();
			} else if ( $(this).val() == 'you to tell me more about' ){
				$("#moreRow").show();
				$("#commentRow").hide();
			}else{
				$("#moreRow").hide();
				$("#commentRow").hide();
			}
		}).change();

		// timetble tooltips

		$("#days .schedule td").tooltip();


		$("form input[type=image]").click(function(){
			var submitButton = $(this);
			var name = jQuery.trim($('#membersLogin #name').val());
			var email = jQuery.trim($('#membersLogin #e-mail').val());

			if(name == '' || email == '' || name == 'name' || email == 'e-mail')
			{
				alert('Please fill in your name and email address.');
				return false;
			}
			
			if(!email.match(/^[a-z0-9._-]+@[a-z0-9._-]+.[a-z]+$/i))
			{
				alert('Please fill in your name and email address.');
				return false;
			}

				$.post("newsletterEmail.php",
				 {
					  "name":document.getElementById("membersLogin").name.value,
					  "email":document.getElementById("membersLogin").email.value			  
					  },
					  function(responseText)
					  {
						$('#membersLogin #name').val('name')
						$('#membersLogin #e-mail').val('e-mail')
					   submitButton.thankyou(responseText);					
					  }
				);	
		
			
			return false;
		});
		
		
		$("form input[id=book_a_tour]").click(function(){
		   submitButton = $(this);

				$.post("bookTourEmail.php",
				 {
					  "fullName":document.getElementById("visit").fullName.value,
					  "contactNumber":document.getElementById("visit").contactNumber.value,
					  "email":document.getElementById("visit").email.value				  
					  },
					  function(responseText)
					  {
					   submitButton.thankyou(responseText);					
					  }
				);	
		
			
			return false;
		});
		
		$("form input[id=question]").click(function(){
		   submitButton = $(this);

			var index = document.getElementById("visit").wantto.selectedIndex;
			var szError ='';
			
			var fullName = document.getElementById("visit").fullName.value;
			var contactNumber = document.getElementById("visit").contactNumber.value;
			var email = document.getElementById("visit").email.value;
			
			if(fullName =='')szError = 'Full name is missing.\n';			
			if(email =='')szError += 'Email is missing.\n';
			if(contactNumber =='')szError += 'Contact Number is missing.\n';			

			if(szError=='')
			if(!email.match(/^[a-z0-9._-]+@[a-z0-9._-]+\.[a-z]+$/i))
			  szError += 'Your email has an incorect format.';
			  
			if(szError)
			{
			 alert(szError);
			 return false;
			}
			
			
				$.post("questionEmail.php",
				 {
					  "fullName":fullName,
					  "contactNumber":contactNumber,
					  "wantto":document.getElementById("visit").wantto.options[index].value,
					  "comment":document.getElementById("visit").comment.value,
					  "moreAbout":document.getElementById("visit").moreAbout.value,
					  "member":(document.getElementById("visit").member[0].checked)?'Yes':'No',
					  "email":email
					  },
					  function(responseText)
					  {
					   submitButton.thankyou(responseText);					
					  }
				);	
		
			
			return false;
		});		
		
		$("form input[id=persTrainerSubmit]").click(function(){
		   submitButton = $(this);

		   
			var szError ='';
			
			var fullName = document.getElementById("personalTrainer").fullName.value;
			var email = document.getElementById("personalTrainer").email.value;
			var Mobile = document.getElementById("personalTrainer").Mobile.value;
			var homeAddress = document.getElementById("personalTrainer").homeAddress.value;
			var homeAddress2 = document.getElementById("personalTrainer").homeAddress2.value;
			var postcode = document.getElementById("personalTrainer").postcode.value;
			
			if(fullName =='')szError = 'Full name is missing.\n';			
			if(email =='')szError += 'Email is missing.\n';
			if(Mobile =='')szError += 'Mobile is missing.\n';
			if(homeAddress =='' && homeAddress2 =='')szError += 'Home address is missing.\n';
			if(postcode =='')szError += 'Postcode is missing.\n';
			

			if(szError=='')
			if(!email.match(/^[a-z0-9._-]+@[a-z0-9._-]+\.[a-z]+$/i))
			  szError += 'Your email has an incorect format.';
			  
			if(szError)
			{
			 alert(szError);
			 return false;
			}
			
			
				$.post("persTrainerEmail.php",
				 {
					  "fullName":fullName,
					  "email":email,				  
					  "Mobile":Mobile,
					  "homeAddress":homeAddress,
					  "homeAddress2":homeAddress2,
					  "postcode":postcode,
					  "goal":document.getElementById("personalTrainer").goal.value,
					  "other":document.getElementById("personalTrainer").other.value
					  },
					  function(responseText)
					  {
					   submitButton.thankyou(responseText);					
					  }
				);	
		
			
			return false;
		});

	});

	$.fn.tooltip = function(cmd, message){

		if ( typeof $.tooltip == 'undefined' ){
			$.tooltip = $("<div id='tooltip'></div>").appendTo('body');
			$.tooltip.append('<div class="inner"></div>');
			$.tooltip.hide();
			$.tooltip.msg = function(msg){
				$(this).find('div.inner').html(msg);
			}
		}
		
		/*var text = {
			'yoga': '<h3>Yoga</h3><p>Total Mind & Body Health. An ancient system that strengthens & relaxes - creating emotional & mental calm.</p>',
			'spin-all': '<h3>Spin ALL</h3><p>Just the tonic to boost your day with a bit of everything.</p>',
			'spin-lv1': '<h3>Spin LV1</h3><p>Exercising on your bike has never been so motivating! Work to pumping music with a motivating instructor. Experience all levels of terrain and endurance. Have that outdoor experience inside.</p>',
			'spin-lv2': '<h3>Spin LV2</h3><p>A combination of all aspects of indoor cycling, sprinting, hill climbs & jumps.</p>',
			'spin-lv3': '<h3>Spin LV3</h3><p>For the hardcore cyclist - designed to increase power, endurance, strength and climbing ability.</p>',
			'abs': '<h3>Abs solution</h3><p>A solution for those who do not like doing core/abdominal workout on their own.</p>',
			'pump-it': '<h3>Pump it</h3><p>Keep yourself toned & trim with this non-impact resistance class using barbells & adjustable weights. Excellent for tone & definition! Please arrive 5 mins early to class to set up.</p>',
			'hatha': '<h3>Hatha Yoga</h3><p>Total Mind & Body Health! An ancient system that strengthens & relaxes - creating emotional & mental calm!</p>',
			'step': '<h3>Step</h3><p>Power step your way to a firmer body using freestyle dance moves.</p>',
			'hiphop': '<h3>Hip hop body</h3><p>Move and shake your way to a firmer body with this high energy workout to the latest music beats.</p>',
			'pilates-lv1': '<h3>Pilates LV1</h3><p>A tranquil, controlled mind & body class - concentrating on developing core strength & improving both posture & breathing techniques.</p>',
			'pilates-lv2': '<h3>Pilates LV2</h3><p>A tranquil, controlled mind & body class - concentrating on developing core strength & improving both posture & breathing techniques.</p>',
			'running': '<h3>Running club</h3><p>Bored of running on a treadmill and not getting anywhere? Attend running club where our instructor will take you on a scenic run through the streets of Shoreditch.</p>',
			'lbt': '<h3>LBT</h3><p>The traditional Legs, Tums and Bum class is back for working the bum & tummy to the limit! It is a great class to firm up the lower body and ABS.</p>',
			'kickboxing': '<h3>Kickboxing LV2</h3><p>Kick and punch your way into top fitness. Improve strength, muscle tone and endurance. Reduce body fat and stress levels. Enjoy a safe, fun and effective workout to pumping music.</p>',
			'aerobics': '<h3>Aerobics LV2</h3><p>A hi/lo class with easy to follow choreography. Set to motivating music let our instructor lead you to fitness.</p>',
			'circuits': '<h3>Boxing circuits</h3><p>A station based full body workout, great for achieving all round fitness.</p>',
			'iyengar': '<h3>Iyengar yoga</h3><p>This style of yoga is both precise & dynamic because of its attention to detail - classes are performed at a slow & moderate pace.</p>',
			'workshop': '<h3>Workshop</h3><p>Specialist 3 week workshops from specific training techniques to dance to martial arts. Time to try something new, we will be in touch with details.</p>',
			'street-vibes': '<h3>Street vibes</h3><p>Move and shake your way to a firmer body with this high energy workout to the latest music beats.</p>',
			'fight-club': '<h3>Fight club LV2</h3><p>Kick and punch your way into top fitness. Improve strength, muscle tone and endurance. Reduce body fat and stress levels. Enjoy a safe, fun and effective workout to pumping music.</p>',
			'yoga-monks': '<h3>Yoga monks ALl</h3><p>Unique dynamic style of "flow" class, works the body deeply, includes meditation.</p>',
			'ashtanga-yoga': '<h3>Ashtanga yoga</h3><p>This is a dynamic yoga, which involves synchronising the breath with progressive series of postures, producing intense internal heat and a profuse, purifying sweat that detoxifies muscles and organs. The result is improved circulation, a light and strong body, and a calm mind.</p>',
			'triathlon': '<h3>Triathlon spin</h3><p>A combination of all aspects of indoor cycling, sprinting, hill climbs & jumps.</p>',
			'bike-abs': '<h3>Bike & abs</h3><p>A combination of all aspects of indoor cycling, sprinting, hill climbs & jumps. Combined with core strength.</p>',
			'outdoor-circuit': '<h3>Outdoor circuit</h3><p>Enjoy exercising in the great outdoors. A station based, full body workout, great for achieving all round fitness.</p>'
		};*/
		var text = [];
		if ( $("#timetable-hover").length ){
			$("#timetable-hover").children().each(function(){
				var c = $(this).attr('class');
				text[c] = $(this).html();
			});
		}

		return this.each(function(){
			var msg = '';
			var cls = $(this).attr('class').split(' ');
			for( var i = 0; i< cls.length; i++){
				if( typeof text[cls[i]] != 'undefined' ) {
					msg = text[cls[i]];
					break;
				}
			}

			$(this).hover(function(){
				var xy = $(this).offset();
				xy.top += $(this).height() + 10;
				$.tooltip.css(xy);
				$.tooltip.msg(msg);
				$.tooltip.stop(true,true).fadeIn('fast');
			}, function(){
				$.tooltip.stop(true,true).fadeOut('fast');
			});
		});
	};

	$.fn.hoverpopup = function(opt){
		return this.each(function(){

			var hover = $(this).parents(opt.container);
			var w = 0;
			if ( !hover.children('div.hover').length ){
				hover = $('<div class="hover"/>').appendTo(hover);
				hover.append('<a class="close" href="#">Close</a><div class="inner"></div>');

				hover.find('a.close').click(function(){
					hover.hide(1000);
					return false;
				});
				hover.hide();
			}else{
				hover = hover.children('div.hover');
			}

			$(this).find('a.trigger').click(function(){
				var h = $(this).parents('.hoverable');
				hover.children('div').html(h.children('div.info').html());
				hover.attr('id','hover-'+h.attr('id'));
				hover.show(1000, function(){
				});
				return false;
			});
		})
	};


	$.fn.thankyou = function(msg){
		if ( typeof $.thankyou == 'undefined' ) {
			$.thankyou = $("<div id='thank-you'></div>").appendTo('body');
			$.thankyou.append('<a class="close" href="#">close</a><p></p>');
			$("a.close", $.thankyou).click(function() {
				$.thankyou.fadeOut('fast');
				return false;
			});
		}

		var xy = $(this).offset();
		xy.left -= 261;
		$.thankyou.css(xy).fadeIn('slow');
		$.thankyou.find('p').html(msg);

	};



})(jQuery);



jQuery.fn.log = function (msg) {
  console.log("%s: %o", msg, this);
  return this;
};
