//cufon font replacement
Cufon.replace('.replace');
Cufon.replace('#question', {fontFamily: 'Gill Sans MT'});

$(function() {
			  
	$('.ingredients').hide();
	$('.moreinfolink').click(function() {
		var element = $(this);
		element.parent().find('.ingredients').slideToggle(500);
		element.toggleClass('open');
		return false;
	});
			  
	$('#question h2').each(function() {
		var element = $(this);
		var offseth = element.height() / 2;
		element.css({marginTop: '-'+offseth+'px', top: '50%'});
	});

	//home page expanding story box
	$('#headlinetext').append('<a id="headlinereadon" href="#" title="read on"><span class="hidden">read on</span></a>'); //add read more button
	$('span.extratext').hide().before('<span class="hellip">&hellip;</span>'); //hide extra text and append '...' to end of visable text
	
	//toggle extra text
	$('#headlinereadon').click(function() {
		if ($(this).hasClass('opened')) {
			$('span.extratext').before('<span class="hellip">&hellip;</span>');
		} else {
			$('span.hellip').remove();
		}
		$(this).toggleClass('opened');
		$('span.extratext').slideToggle();
	});
	
	//fix Firefox 3+ autocomplete bug
	$('#clubform, #competitionform').attr('autocomplete','off');
	
	//Club page form elements
	$('#duedate, #childrendetails, #optionalfields').hide();
	$('#optionstoggle').addClass('closed');
	$('input[name="pregnant"]').change(function() {
		if ($('input[name="pregnant"]:checked').val() == 'yes') {
			$('#duedate').slideDown().show();
		} else {
			$('#duedate').slideUp();
		}
	});
	$('input[name="children"]').change(function() {
		if ($('input[name="children"]:checked').val() == 'yes') {
			$('#childrendetails').slideDown().show();
		} else {
			$('#childrendetails').slideUp();
		}
	});
	$('#optionstoggle').click(function() {
		$(this).toggleClass('closed');
		$('#optionalfields').slideToggle();
		return false;
	});
	
	//remove default value of email registration form on focus
	$('#e').each(function() {
		var e = $(this);
		e.css('color','#999999');
		e.focus(function() {
			if (e.val() == 'your email address') {
				e.val('');	
			}
			e.css('color','#000000');
		});
		e.blur(function() {
			if (e.val() == '') {
				e.css('color','#999999').val('your email address');
			}
		});
	});
	
	//add overlay to DOM
	$('body')
	.append(
		'<div id="overlay"></div>'
	)
	.append(
		'<div class="modalbox" id="rafwrapper"><div id="rafmodal"><a class="closeicon closelink" href="#"><img src="/images/close-icon.png" alt="" /></a><div id="rafformheader"><h3 class="replace">refer a friend</h3></div>'+
		'<div id="rafformmain"><div id="rafformcontainer" class="clearfix"><form method="post" id="rafform" action="/app/index.php/refer">'+
		'<input id="frmurl" type="hidden" name="url" />'+
		'<fieldset><div class="clearfix"><label for="frmyourname">Your name:<span>*</span></label><input id="frmyourname" name="name" type="text" tabindex="101" /></div>'+
		'<div class="clearfix"><label for="frmyouremail">Your email address:<span>*</span></label><input id="frmyouremail" name="email" type="text" tabindex="102" /></div></fieldset>'+
		'<fieldset><div class="clearfix"><label for="frmfriendsname">Friends name:<span>*</span></label><input id="frmfriendsname" name="friend_name" type="text" tabindex="103" /></div>'+
		'<div class="clearfix"><label for="frmfriendsemail">Friends email address:<span>*</span></label><input id="frmfriendsemail" name="friend_email" type="text" tabindex="104" /></div></fieldset>'+
		'<fieldset><div class="clearfix"><label for="frmmessage">Your message:</label><textarea rows="" cols="" id="frmmessage" name="message" tabindex="105" /></textarea></div></fieldset>'+
		'<div id="submitbutton"><p><span>*</span> required</p><input type="submit" name="rafsubmit" id="rafsubmit" tabindex="106" /></div></form></div><a class="closelinkbottom closelink" href="#">Close window</a>'+
		'</div>' +
		'</div></div>'
	)
	.append(
		'<div class="modalbox" id="contact_privacywrapper"><div class="privacymodal"><a class="closeicon closelink" href="#"><img src="/images/close-icon.png" alt="" /></a>'+
		'<h3 class="replace">privacy</h3><p>Little Me Organics respects your privacy and will not pass your details to third parties. View our full <a href="/privacy.php">Privacy Policy</a></p>'+
		'<a class="closelinkbottom closelink" href="#">Close window</a></div></div>'
	)
	.append(
		'<div class="modalbox" id="club_privacywrapper"><div class="privacymodal"><a class="closeicon closelink" href="#"><img src="/images/close-icon.png" alt="" /></a>'+
		'<h3 class="replace">privacy</h3><p>Little Me Organics respects your privacy and will not pass your details to third parties. View our full <a href="/privacy.php">Privacy Policy</a></p>'+
		'<a class="closelinkbottom closelink" href="#">Close window</a></div></div>'
	)
	.append(
		'<div class="modalbox" id="competition_privacywrapper"><div class="competition_privacymodal"><a class="closeicon closelink" href="#"><img src="/images/close-icon.png" alt="" /></a>'+
		'<h3 class="replace">privacy</h3>'+
		'<p>Entering the Little Me competition registers you to the Little Me Organics Club, where you will receive the latest news and information from Little Me. '+
		'If you would like to leave the Club at any stage or would like to stop receiving communication use the unsubscribe link on any emails that you receive. '+
		'Little Me Organics respects your privacy and will not pass your details to third parties.</p>'+
		'<p>Little Me Organics respects your privacy and will not pass your details to third parties. View our full <a href="/privacy.php">Privacy Policy</a></p>'+
    '<p>&nbsp;</p>'+
		'<a class="closelinkbottom closelink" href="#">Close window</a></div></div>'
	)
	.append(
		'<div class="modalbox" id="termswrapper"><div id="termsmodal"><a class="closeicon closelink" href="#"><img src="/images/close-icon.png" alt="" /></a><h3 class="replace">terms &amp; conditions</h3><ul><li>Deadline for entry Midnight January 31st</li><li>One entry per person</li><li>This competition is open to residents of the UK, Channel Islands, Isle of Man and Republic of Ireland</li><li>Employees (or members of the families or households of employees) of KMI Brands or any company involved in the competition draw are not eligible to enter the competition</li><li>KMI Brands reserve the right not to award a prize (and to select an alternative winner) if KMI Brands are aware or has reasonable grounds to believe that a winner is not eligible</li><li>The prize is subject to availability, is non transferable and there are no cash alternatives</li><li>The winner will be notified 10 days of the closing date of the competition draw</li><li>In the event of any dispute regarding the rules, conduct, results and all other matters relating to a competition, the decision of KMI shall be final and no correspondence or discussion shall be entered into.</li></ul><p>Promoter: Little Me Organics, part of KMI Brands, Head Office, Harlequin House, 7 High Street, Teddington, Middlesex, TW11 8EE, UK.</p><a class="closelinkbottom closelink" href="#">Close window</a></div></div>'
	);
  
  $( '#frmurl' ).attr( 'value', location.href );
	
	//modal box
	$('.modallink').click(function(e) {
											
		Cufon.replace('.replace');

		var overlay = $('#overlay');
		var target = $($(this).attr('href'));
		var maskHeight = $(document).height();  
		var maskWidth = $(window).width();  

		$('body').append('<iframe id="frame" src=""></iframe>'); //Prevent select boxes appearing above overlay in IE6
		
		overlay.css({'width':maskWidth+'px','height':maskHeight+'px', 'opacity':0.8}).fadeIn(500);    

		var winH = $(window).height(); 
		var winW = $(window).width();  

		target.css({'top':winH/2-target.height()/2+'px','left': winW/2-target.width()/2+'px'}).fadeIn(500);   
		
		return false;
	});  

	$('.closelink, #overlay').click(function (e) {  
		$('#frame').remove();												
		$('#overlay, div.modalbox').fadeOut(300); 
		return false;
	});       
 
  $('#rafform')
	.prepend('<ul id="rafform_errors" />')
	.validate({
		errorLabelContainer: "#rafform_errors",
		wrapper: "li",
		rules: {
			name: {
				required: true
			},
			friend_name: {
				required: true
			},
			email: {
				required: true,
				email: true
			},
			friend_email: {
				required: true,
				email: true
			},
			message: {
				required: true
			}
		},
		messages: {
			name: {
				required: "Please provide your name."
			},
			friend_name: {
				required: "Please provide your friends name."
			},
			email: {
				required: "Please provide your email address.",
				email: "Please provide a valid email address."
			},
			friend_email: {
				required: "Please provide your friends email address.",
				email: "Please provide a valid email address."
			},
			message: {
				required: "Please provide a message to your friend."
			}
		},
    onkeyup : false,
    onclick: false,
    onfocusout: false,
		submitHandler: function(form) {
			$(form).ajaxSubmit({
				success: function() {
					$( '#rafformcontainer' ).html( '<div style="height: 287px; font-size: 13px;">Thank you!</span><br/><br/><span>Your friend will receive your message shortly.</div>' );
				},
        error: function(xhr, statusText )  { 
          var data = $.httpData(xhr, 'json' );
          $( '#rafform_errors' ).empty();
          for ( var field in data.errors ) {
            $( '#rafform_errors' ).css( 'display', 'block' ).append( 
              '<li><label for="frmyourname" generated="true" class="error" style="display: block;">'+
              data.errors[ field ]+
              '</label></li>');
          }
        }
			});
			return false;
		}
	});
 
});
