

$(function(){
	
	//Tag body with js class and remove nojs class
	$('body').addClass('js');
	$('body').removeClass('nojs');
	
	
	//Home Page Polaroids
	if($('#polaroids').length){
		$.fn.preload = function() {
		    this.each(function(){
		        $('<img/>')[0].src = this;
		    });
		}
		
		var polaroids = 4;
		var currentPolaroid = 1;
		var preloadArray = [];
		for(var i=0;i<=polaroids;i++){
			preloadArray.push('/images/graphics/polaroids'+i+'.png'); 
			$(preloadArray).preload();
		}
		setInterval(function(){
			$('#polaroids img').attr('src','/images/graphics/polaroids0.png');
			if(currentPolaroid==polaroids){
				currentPolaroid = 1;
			}else{
				currentPolaroid++;
			}
			setTimeout(function(){
				$('#polaroids img').attr('src','/images/graphics/polaroids'+currentPolaroid+'.png');
			},200);
		},5000);
	}
	
	//Home Page and Teen Ideas drop down
	if($('.dropdown'.length)){
		$('.dropdown').click(function(){
			$(this).siblings('ul').slideToggle().addClass('opened');
			if($(this).siblings('ul').hasClass('opened')){
				$(this).siblings('ul').removeClass('opened')
			}else{
				$(this).siblings('ul').addClass('opened')
			}
			return false;
		});
	}
	
	//Teen Ideas Article Hovers
	if($('.teen-ideas .article').length){
		$('.teen-ideas .article').hover(function(){
			$(this).find('.idea-copy').stop(true,true);
			$(this).find('.idea-image').stop(true,true).slideUp(200,function(){
				$(this).siblings('.idea-copy').slideDown(100);
			});
		},function(){
			$(this).find('.idea-image').stop(true,true);
			$(this).find('.idea-copy').stop(true,true).slideUp(100,function(){
				$(this).siblings('.idea-image').slideDown(200);
			});
		}).click(function(){
			window.location = $(this).find('a').attr('href');
		});
	}
	
	//Competition examples carousel
	if($('#comp-examples').length){
		$('#comp-examples').append(
			'<a id="prev-example" href="javascript:void(0);" class="imgrep png">Previous Example</a>			 <a id="next-example" href="javascript:void(0)" class="imgrep png">Next Example</a>');
		$('#comp-examples .carousel').cycle({
		    fx:     'scrollHorz',
		    speed:  200, 
		    timeout: 0, 
		    next:   '#next-example', 
		    prev:   '#prev-example',
		    easeIn: 'easeOutQuad',
		    easeOut: 'easeOutQuad'
		});
	}
	
	/*Modal Window on Comp page*/
	if($('.stuck-for-imaginative-ideas').length){
		$('head').append('<link rel="stylesheet" href="/css/jquery.fancybox-1.3.4.css" type="text/css" media="screen, projection">');
		$('.stuck-for-imaginative-ideas').addClass('iframe');
		$('.stuck-for-imaginative-ideas').attr('href','/perfectday/comp-modal');
		$('.stuck-for-imaginative-ideas').fancybox({
			'width': 760,
			'height': 614,
			'transitionIn': 'elastic',
			'transitionOut': 'elastic',
			'padding': 0
		});
	}
	
	/*Modal Window on Comp form page*/
	if($('#comp-form #tsandcs-modal-link').length){
		$('head').append('<link rel="stylesheet" href="/css/jquery.fancybox-1.3.4.css" type="text/css" media="screen, projection">');
		
		
		$('#tsandcs-modal-link').addClass('iframe');
		$('#tsandcs-modal-link').attr('href','/perfectday/terms-modal');
		$('#tsandcs-modal-link').fancybox({
			'width': 760,
			'height': 614,
			'transitionIn': 'elastic',
			'transitionOut': 'elastic',
			'padding': 0
		});
	}
	
	
	
	/*Accordions on Mums Zone pages*/
	if($('.accordion').length){
	
			
		$('.accordion h2').wrapInner('<a href="javascript:void(0)" />');
		$('.accordion h2 a').live('click',function(){
		
			if($(this).parents('.accordion .article').hasClass('opened')){ //If opened, then close and remove class
				$(this).parents('.accordion .article').removeClass('opened');
				$(this).parent().siblings('.acc-content').stop(true,true).slideUp(400,'easeOutQuad'); //toggle current
			}else{ //else close opened and open current and add/remove class
				$(this).parents('.accordion').find('.opened').removeClass('opened')
				.children('.acc-content').stop(true,true).slideUp(400,'easeOutQuad'); //Close opened
				$(this).parents('.accordion .article').addClass('opened');
				$(this).parent().siblings('.acc-content').stop(true,true).slideDown(400,'easeOutQuad'); //toggle current
			}
		});
		//toggle first
		setTimeout(function(){$('.accordion .article:first-child h2 a').click();},200);
	}
	
	/*They hate so try widget*/
	if($('.hates-widget select').length && $('#hates-results').length){
		$('.hates-widget select').change(function(){
			var articles = $('#hates-results .article');
			var select = $(this);
			/*slide opened box up*/
			$('#hates-results .opened').stop(true,true).removeClass('opened').slideUp(200,'easeOutQuad',function(){
				var option = select.find('option:selected').index();
				articles.eq(option).stop(true,true).slideDown(400,'easeOutQuad').addClass('opened');
			});
		})
	}
	
	/*Tabs*/
	if($('.tab-nav').length && $('.tab-content').length){
		$('.tab-nav li a').click(function(){ /*When a tab is clicked close all existing tabs and open current one*/
			
			var i = $(this).parent().index();
			var content = $(this).parents('.tab-nav').siblings('.tab-content').children('.article').eq(i);
			if(content!='undefined'&&!content.hasClass('opened')){
				content.siblings('.opened').removeClass('opened');
				content.addClass('opened');
				$(this).parent().siblings('.selected').removeClass('selected')
				$(this).parent().addClass('selected');
			}
		});
		$('.tab-nav li:first-child a').click();
	}
	
	/*New validation for 'not equal to 0' */
	if($('form').length){
		$.validator.addMethod('notzero', function(value, element, param) {
	            return (value != 0);
	        }, 'Please enter a value for this field');
	}
	
	if($('form').length){
		$.validator.addMethod('maxwords', function(value, element, param) {
	            var text = value.replace(/^\s*|\s*$/g,'');
				var count =  (text.split(/[\s]+/)).length; //get number of words
	            
	           	if(!$('#wordcount-'+element.name).length){ //if word count label not created, create it
            		$('#'+element.id).before('<label class="fr alignr" id="wordcount-'+element.name+'" for="'+element.name+'">Words remaining: '+(param-count)+'</label>')
	            }else{ //otherwise set label
	            	$('#wordcount-'+element.name).html('Words remaining: '+(param-count));
	            	
	            }
	            if(count <= param){ //attach class if word count is over
	            	$('#wordcount-'+element.name).removeClass('error2');
	            }else{ //otherwise remove class
	            	$('#wordcount-'+element.name).addClass('error2');
	            }
	            return (count <= param); //return error state
	            	
	        }, 'You have entered too many words');
	    $.validator.addMethod('minwords', function(value, element, param) {
	            var text = value.replace(/^\s*|\s*$/g,'');
				var count =  (text.split(/[\s]+/)).length; //get number of words
	            if(value.split(" ")[0]==""){count = 0}; //test for empty string
	            
	          
	          
	            if(count >= param){ //attach class if word count is under
	            	$('#wordcount-'+element.name).removeClass('error2');
	            }else{ //otherwise remove class
	            	$('#wordcount-'+element.name).addClass('error2'); 
            	    if(!$('#wordcount-'+element.name).length){ //if word count label is not created, create it
	            	    $('#'+element.id).before('<label class="fr alignr" id="wordcount-'+element.name+'" for="'+element.name+'">Words remaining: '+1500+'</label>')
	                }else{ //otherwise set label
	            	    $('#wordcount-'+element.name).html('Words remaining: '+1500);
	                }
	            }
	            
	            return (count >= param); //return error state
	            	
	        }, 'You have entered too few words');
	}	
	
	/*Comp Form validation*/
	if($('#comp-form').length){
		$('#comp-form').validate({
			rules:{
				dob_day: "required",
				dob_month: "required",
				dob_year: {
					required: true,
					notzero: true
				},
				agree_to_terms: {
					required: true
				},
				title: "required",
				first_name: "required",
				email:{
					required: true,
					email: true
				},
				perfectday:{
					maxwords: 1500,
					minwords: 1
				}
				
			},
			onkeyup: function(element){this.element(element);},
			onfocus: true,
			messages:{
				dob_day: "Hold on tiger, you&rsquo;ve forgotten to fill in your date of birth",
				dob_month: "Hold on tiger, you&rsquo;ve forgotten to fill in your date of birth",
				dob_year: "Hold on tiger, you&rsquo;ve forgotten to fill in your date of birth",
				agree_to_terms: "You must agree to the promotions terms and conditions before submiting the form",
				title: "Hold on tiger, you&rsquo;ve forgotten to fill in your title",
				first_name: "Hold on tiger, you&rsquo;ve forgotten to fill in your first name",
				email:{
					required: 'Hold on tiger, you&rsquo;ve forgotten to fill in your email',
					email: 'That email address looks funny &ndash; re-enter it and try again'
				},
				perfectday:{
					maxwords: 'Hold on tiger, this isn&rsquo;t a novel you know! The maximum word count is 1,500 words',
					minwords: 'Hold on tiger, you need to tell us what your Perfect Day is.'
				}
				
			},
			groups: {
			    dob: "dob_day dob_month dob_year"
			},
			errorPlacement: function(error, element) {
				if (element.attr("name").indexOf('dob')!=-1)
			       error.insertAfter("#dob-group");
			    else
			       error.insertAfter(element);
			}
		});
		var text = $('#perfectday').val().replace(/^\s*|\s*$/g,'');
		if(text.length!=0){
			var count =  (text.split(/[\s]+/)).length; //get number of words
		}else{
			var count = 0;
		}
	    var wordsleft = 1500-count;  
		$('#perfectday').before('<label class="fr alignr" id="wordcount-perfectday" for="perfectday">Words remaining: '+wordsleft+'</label>')
	}
	/*Comp Form validation  - under16*/
	if($('#comp-form-under16').length){
		$('#comp-form-under16').validate({
			rules:{
				dob_day: "required",
				dob_month: "required",
				dob_year: {
					required: true,
					notzero: true
				},
				agree_to_terms: {
					required: true
				},
				title: "required",
				first_name: "required",
				email:{
					required: true,
					email: true
				},
				perfectday:{
					maxwords: 1500,
					minwords: 1
				},
				parentemail: {
					required: true,
					email: true
				}
			},
			messages:{
				dob_day: "Hold on tiger, you&rsquo;ve forgotten to fill in your date of birth",
				dob_month: "Hold on tiger, you&rsquo;ve forgotten to fill in your date of birth",
				dob_year: "Hold on tiger, you&rsquo;ve forgotten to fill in your date of birth",
				agree_to_terms: "You must agree to the promotions terms and conditions before submiting the form",
				title: "Hold on tiger, you&rsquo;ve forgotten to fill in your title",
				first_name: "Hold on tiger, you&rsquo;ve forgotten to fill in your first name",
				email:{
					required: 'Hold on tiger, you&rsquo;ve forgotten to fill in your email',
					email: 'That email address looks funny &ndash; re-enter it and try again'
				},
				perfectday:{
					maxwords: 'Hold on tiger, this isn&rsquo;t a novel you know! The maximum word count is 1,500 words',
					minwords: 'Hold on tiger, you need to tell us what your Perfect Day is.'
				},
				parentemail:{
					required: 'Hold on tiger, you&rsquo;ve forgotten to fill in the Parent or Guardian Email',
					email: 'That email address looks funny &ndash; re-enter it and try again'
				}
			},
			groups: {
			    dob: "dob_day dob_month dob_year"
			},
			errorPlacement: function(error, element) {
				if (element.attr("name").indexOf('dob')!=-1)
			       error.insertAfter("#dob-group");
			    else
			       error.insertAfter(element);
			}
		});
		var text = $('#perfectday').val().replace(/^\s*|\s*$/g,'');
		if(text.length!=0){
			var count =  (text.split(/[\s]+/)).length; //get number of words
		}else{
			var count = 0;
		}
	    var wordsleft = 1500-count;  
		$('#perfectday').before('<label class="fr alignr" id="wordcount-perfectday" for="perfectday">Words remaining: '+wordsleft+'</label>')
	}
	
	/*Reg Form validation*/
	if($('#reg-form').length){
		$('#reg-form').validate({
			rules:{
				title: "required",
				first_name: "required",
				dob_day: "required",
				dob_month: "required",
				dob_year: {
					required: true,
					notzero: true
				},
				email:{
					required: true,
					email: true
				},
				gender: "required"
			},
			messages:{
				title: "Please fill in your title",
				first_name: "Please fill in your first name",
				dob_day: "Please fill in your date of birth",
				dob_month: "Please fill in your date of birth",
				dob_year: "Please fill in your date of birth",
				email:{
					required: 'Please fill in your email',
					email: 'Please enter a valid email address'
				},
				gender: "Please select your gender"
				
			},
			groups: {
			    dob: "dob_day dob_month dob_year"
			},
			errorPlacement: function(error, element) {
				if (element.attr("name").indexOf('dob')!=-1)
			       error.insertAfter("#dob-group");
			    else
			       error.insertAfter(element);
			}
		});
		
	}
	
	/*Contact Form validation*/
	if($('#contact-form').length){
		$('#contact-form').validate({
			rules:{
				title: "required",
				first_name: "required",
				last_name: "required",
				email:{
					required: true,
					email: true
				},
				querytype: "required",
				comments: "required"
			},
			messages:{
				title: "Please enter your title",
				first_name: "Please enter your first name",
				last_name: "Please enter your last name",
				email:{
					required: 'Please enter an email address',
					email: 'That email address looks funny &ndash; re-enter it and try again'
				},
				querytype: "Please select a query type",
				comments: "Please enter your comments"
				
			}
		});
		
	}
	
	
	
	/*Unsubscribe Form validation*/
	if($('#unsub-form').length){
		$('#unsub-form').validate({
			rules:{
				
				email:{
					required: true,
					email: true
				}
			},
			messages:{
				
				email:{
					required: 'Hold on tiger, you&rsquo;ve forgotten to fill in your Email',
					email: 'That email address looks funny &ndash; re-enter it and try again'
				}
				
			}
		});
		
	}
	
	/*External Links Modal Window*/
	if($('.external').length){
		//append modal css file to head
		$('head').append('<link rel="stylesheet" href="/css/jquery.fancybox-1.3.4.css" type="text/css" media="screen, projection">');
		
		/*Append modal window to end of body*/
		$('body').append('<div style="display: none"><div class="box yellow" id="external-link-container"><h2 class="imgrep just-so-you-know">Just so you know</h2><p>You are about to leave the Capri-Sun website, this just means we&rsquo;re not responsible for any of the content on the site you are going to.</p><p>Do you wish to continue?</p><p class="clearfix"><a href="#" class="button fl imgrep no">No</a> <a href="http://www.externallink.co.uk" target="_blank" class="button imgrep fl yes">Yes</a></p></div></div>');
		
		/*On clicking the link, pass it's href attribute to the yes button of the modal window, and set the href to the modal window*/
		$('.external').click(function(){
		
			if($(this).attr('href')!='#external-link-container'){
				$(this).data('externallink',$(this).attr('href'));
				
				$(this).attr('href','#external-link-container');
				
			}
			$('#external-link-container .yes').attr('href',$(this).data('externallink'));
				
			return false;
		});
		
		/*Setup modal window*/
		$('.external').fancybox({
			'width': 567,
			'height': 240,
			'transitionIn': 'elastic',
			'transitionOut': 'elastic',
			'padding': 0,
			'autoDimensions': false
		});
		
		/*Attach close event to no button of modal window*/
		$('#external-link-container .no, #external-link-container .yes').click(function(){
			$.fancybox.close();
		});
	}
	
	
});
