/*
Other javascript such as functions which are called can go below here */
function highlightUrl() { 	

	//grab element to highlight from URL
	var target = window.location.hash;
	
	if(target&&target!="#disqus_thread"){
		$(target).delay(200).textColorFade();
		$("html, body").animate(
			{	scrollTop: $(target).offset().top-30},
			{ 	queue:false, duration:1000 }),
			function(){location.hash = target;};	
	}
}


function highlightClick(){
	
	//grab element to highlight from href
	var target = $(this).attr("href");
	$(target).stop().delay(900).textColorFade();
	
	// Animate our whole page down the anchor that is grabbed from the URL. Scroll down should take 
	// 1000ms and the animation shouldn't queue to stop multiple scrolls happening.
	 $("html, body").animate(
		{	scrollTop: $(target).offset().top-30},
		{ 	queue:false, duration:1000 }),
		function(){location.hash = target;};
	
		if(event.preventDefault){
		    event.preventDefault();
		}else{
		    event.returnValue = false; 
		}
}

function toggleAnswer(answer){
	if(answer.is(":hidden")){
		answer.slideDown('100');
		answer.next().text("Close Answer");
		answer.next().animate({marginTop: "15px"});
		answer.parent().addClass("opened");

	} else {
		answer.slideUp('100');
		answer.next().text("View Answer");
		answer.next().animate({marginTop: 0});
		answer.parent().removeClass("opened");
	}
}
	

/*
Scrolling Sidebar */

// This function controlls the sliding navigation on long content pages as well as the fading in and
// out of CTA blocks in the sidebar
$(window).scroll(function() {
  scroll_layout()
});

$(window).resize(function() {
  scroll_layout()
});

function scroll_layout(){

    // Only run this function if a sidebar exists.
	// This is also  a check for window size to scroll_layout() because it used position: fixed, it needs to make
	// sure the window is wide enough, else the layout breaks. If a user's browser is not atleast 990px wide, then
	// scroll_layout does not execute. As soon as the window is resized to the correct size, then scroll_layout
	// springs into action
	
    if (($("body>aside").length > 0) && ($(window).width()>990)) {

        // Setup scrolling offsets and document dimensions             
        var documentWidth = $(document).width();
        var windowWidth = $(window).width();
        var windowLeftOffset = $(window).scrollLeft();

        if (windowWidth < documentWidth){
            var posLeft = (documentWidth/2)-windowLeftOffset;
            var posLeftFooter = documentWidth/2;
        }   else {
            var posLeft = '50%';
            var posLeftFooter = '50%';
        }
		
		/*
		Setup Variables for Scroll Layout */
		
		// Height of the bottom CTA
		if($("body>.cta").length>0) {
			var ctaOuterHeightBottom = $("body>.cta").outerHeight(true);
		} else {
			var ctaOuterHeightBottom = 0;
		}
		// Height of the side CTA
		if($("body>aside .cta").length>0) {
			var ctaHeight = $("body>aside .cta").outerHeight(true);
		} else {
			var ctaHeight = 0;
		}
		// Distance scrolled from top
        var windowOffset = $(window).scrollTop();
		// Height of <aside>
        var asideHeight = $("body>aside").outerHeight(true);     
   		// Distance scrolled at which we "enter the footer"
        var footerOffset = $("section.main>footer").offset().top - ctaOuterHeightBottom; // 
       	// Distance scrolled until we "enter the content"
		var contentHeadOffset = $("section.main").offset().top;
		// Distance scrolled until we "leave the header"
        var headerHeight = $("body>header").outerHeight(true);
		// Height of the content
        var contentHeight = $("section.main").outerHeight(true);
		// Height of the #sub
		if($("#sub").length>0) {
			var subHeight = $("#sub").outerHeight(true);
		} else {
			var subHeight = 0;
		}
		// Height of the sidebar
		if($("body>aside").length>0) {
			var sideHeight = $("body>aside").outerHeight(true);
		} else {
			var sideHeight = 0;
		}

		
		// Fix "jumping" CTA on initial scroll
		//$("aside .cta").css({"top":asideHeight-20, left:0});
		
		
		//Start scrolling conditional - checks position in the document and updates the position
		// of the sliding navigation
		// The -30 in the (footerOffset-30) stops jumping when the scrolling navigation changes
		// state because it makes the change occur at the point where the new state will be positioned
		
     	if ((windowOffset >= contentHeadOffset) && (windowOffset < (footerOffset - subHeight + 170 ))){
			
			// When you have scrolled past header area, fix the sub-nav to the top of the window
	        $("body>aside").removeClass('bottom').addClass('fixed').css({'top':0, 'left':posLeft});


	     } else if (windowOffset < headerHeight && windowOffset <= contentHeadOffset) {
			
			// When you are scrolling within header area fix the sub-nav to just below the header area (natural position)
	      	$("body>aside").removeClass('bottom').addClass('fixed').css({'top':headerHeight-windowOffset, 'left':posLeft});


	     } else if (windowOffset > (footerOffset - subHeight + 170 )) {
			
			// When you are scrolling past content area (into the footer) then position the sub-nav at the end of the content
			// The + 40 positions the scrolling navigation in line with the bottom of the content instead of the penis line break
			$("body>aside").removeClass("fixed").addClass("bottom").css({"top":contentHeight-sideHeight + 40, 'left': posLeft});
			
			//Deprecated code -- for single side CTA fade only, ie ALL AT ONCE instead of per item
			//$("body>aside .cta").fadeOut();

	     } // end scrolling conditional  
		
		// Load in CTA when you leave footer area
		// The +200 allows the side CTA enough time to fade out before it is hidden behind the bottom CTAs (it
		// is the height of the CTA)
				
		ctas = $("body>aside .cta>li");
		
		// Find the amount of CTAs we can accomodate in the space available til the end of the document
		spacetilend = Math.ceil((footerOffset-(windowOffset+asideHeight))/210);
		
		// Find the amount of CTAS we can accomodate in the browser window height
		spaceinwindow = Math.floor(($(window).height()-asideHeight)/210);
		
		// The smallest amount of small is chosen as the deciding factor.
		if(spacetilend>spaceinwindow) {
			space = spaceinwindow;
		}else{
			space = spacetilend;
		}
				
		// Check each CTA to see if it can fit, if so, fade it In, otherwise, fade it Out.
	 	ctas.each(function(){
			if($(ctas).index(this)+1<=space) {
				if(!$(this).hasClass("animating")){
					$(this).addClass("animating").fadeIn(300, function(){
						$(this).removeClass("animating");
					});
				}
			} else {
				if(!$(this).hasClass("animating")){
					$(this).addClass("animating").fadeOut(300, function(){
						$(this).removeClass("animating");
					});	
				}
			}
			
			if($(this).offset().top > footerOffset+400) {
				$(this).hide();
			}
		});
		
		
		//Deprecated code -- for single side CTA fade only, ie ALL AT ONCE instead of per item
	    /*if(windowOffset < (footerOffset-ctaHeight)) {
			$("body>aside .cta").fadeIn();
		
		// Hide CTA when you enter footer area
		} else if ( windowOffset > (footerOffset-ctaHeight)) {
			$("body>aside .cta").fadeOut();
		}*/
		
    } else {
		
		// Remove effects of scroll_layout once the window width becomes less than 990px;
		
		$("body>aside").removeClass('fixed').removeClass("bottom").css({"top": 0, "left": 0});
		
		} //end if sidebar exists           
} // end scroll_layout()



/* 
Javascript that needs to run when the document is ready needs to go here */
$(document).ready(function() {    

	/*
	Homepage Fader */

	$(function(){
		
		function autoFadeFader(){
			
			// Hides loader gif
			$(".fader").addClass("started");

			// Remove current selected state from both fader-controls and .fader
		    $('.fader li:nth-child('+count+')').removeClass("selected").fadeOut(2500);
			$('.fader-controls a:nth-child('+count+')').removeClass("selected");
		    count = count+1;
		    if(count>slideTotal) {
		        count = 1;
		    }

			// Select next element in both fader-controls and .fader
		    $('.fader li:nth-child('+count+')').addClass("selected").fadeIn(2500);
			$('.fader-controls a:nth-child('+count+')').addClass("selected");
		}
			
			
		//checks whether the fader exists
		if($(".fader").length>0){

			// Creates fader-controls html by grabbing all the list elements within the .fader element
			// and creating pointers to them
			$("#spotlight").append('<span class="fader-controls"></span>');
			$(".fader li").each(function(){
				$(".fader-controls").append('<a href="'+$(this).find("a").attr("href")+'"></a>');
			});

			// Setup default state of the fader. Selecting and fading in the first child of .fader
			$(".fader>*:first-child, .fader-controls>*:first-child").addClass("selected");	
			$(".fader li:first-child").fadeIn();
	
			// Setup fader-control click interactions
			$(".fader-controls a").click(function(){
		
				// Stop auto-fade on selection of an element
				clearInterval(autoFade);
				
				// Set count to current selection so when the animation resumes it resumes from
				// the position currently selected by the user.
				count = $(".fader-controls a").index(this)+1;
				
				
				// Resume auto-fade after 6 seconds
				setTimeout(function(){
					clearInterval(autoFade);
					autoFade = setInterval(autoFadeFader, 6000);
				},1000);
		
				// Updates position of the selected pointer within the fader-control
				$(".fader-controls a").removeClass("selected");
				$(this).addClass("selected");
		
				// Fade to new selection using the "href" attribute as a pointer
				ref = $(this).attr("href");
				$(".fader li").removeClass("selected").fadeOut();
				$(".fader a[href='"+ref+"']").parent().addClass("selected").fadeIn();
				
				
				if(event.preventDefault){
				    event.preventDefault();
				}else{
				    event.returnValue = false; 
				}
		
			}); //end fader-controls interaction setup
	
	
			// Start auto-fade setup. Counts all elements within .fader then cycles through them.
			slideTotal = $('.fader>li').length;
			count=1;
		
			// Start Autofade on document Load.
			var autoFade = setInterval(autoFadeFader, 8000);
	
		}	//end auto-fade setup
	
		
	}); //end Homepage Fader




	// Checks if the .index UL on Index-Pages has more than 5 children, if so, we find out how
	// many columns of 5 are required, create enough ULs and repopulate them with the original
	// child li's
	if($("ul.index li").length>5){
		questions = $("ul.index li");
		cols = Math.ceil(questions.length/5)
		cols = cols-1;
		col = new Array();
		count = 0;
	
		while(count<=cols){
			count++;
			col = questions.splice(0,5);
			$(".index:last").after('<ul class="index">').append(col);
		}		
	}


	// Add maginifying glasses to images in galleries
	$(".gallery a").each(function(){
		$(this).append('<span class="zoom"></a>');
	});


	// Invokes FancyBox on any link within a .gallery element	
	if($(".gallery a").length>0){
		$(".gallery a").fancybox({
			'transitionIn'	:	'elastic',
			'transitionOut'	:	'elastic',
			'speedIn'		:	600, 
			'speedOut'		:	200, 
			'overlayShow'	:	false
		});		
	}

	// Adds a class to first and last list items globally so we can target them with CSS, because IE7 sucks.
	$("li:first-child").addClass("first");
	$("li:last-child").addClass("last");


	// Highlight the correct section based on the hash in the URL
	highlightUrl();


	// Binds highlightClick() to all links within an index UL which will scroll users down to the correct
	// section and higlight the title of that section
	$('ul.index a[href*=#]').bind("click", highlightClick);


	// Makes our scroll to top button scroll nice and smooth.
	$('a[href=#top]').click(function(event){
		$('html, body').animate({scrollTop:0}, 'fast');

		if(event.preventDefault){
		    event.preventDefault();
		}else{
		    event.returnValue = false;
		}
		
	});


	// Calls scroll_layout function which controls our sliding navigation on long content pages.
	scroll_layout();
	
	// Emulates the placeholder attribute in browsers that don't support it yet
	if (!Modernizr.input.placeholder){
			$("input, textarea").each(function(){
				if($(this).val()==""){
					$(this).val($(this).attr("placeholder"));
				}
			});
			$("input, textarea").focus(function(){
				if($(this).val()==$(this).attr("placeholder")){
					$(this).val("");
				}
			});
			$("input, textarea").blur(function(){
				if($(this).val()==""){
					$(this).val($(this).attr("placeholder"));
				}
			});
		}
	
	// Emulate the required attribute for browsers that don't support it yet
	$("form input, form textarea").each(function(){	
		var required = $(this).attr('required');

		// For some browsers, `attr` is undefined; for others,
		// `attr` is false.  Check for both.
		if (typeof required !== 'undefined' && required !== false) {
		    $(this).addClass("required");
		}
	});
	
	
	if ( !($.browser.msie && $.browser.version == 7.0) ){	
		$("form").validate({
			invalidHandler: function(form, validator) {
			      var errors = validator.numberOfInvalids();
			      if (errors) {
			        var message = errors == 1
			          ? '<strong>Unsuccessful:</strong> You must enter in a question and tick "I agree to the Terms of Use"'
			          : '<strong>Unsuccessful:</strong> You must enter in a question and tick "I agree to the Terms of Use"';
			        if($("p.error").length<1){
						$("form[name=ask-question] input[type=checkbox]").parent().after('<p class="error">'+message+'</p>');
					}
			      } else {
			        $("div.error").hide();
			      }
			} //end invalidHandler
		}); //end validation
	} // turn off this check in IE7 because it breaks. need to fix.	


	// Make icons clickable in social areas
	$(".social li, #connect li").find("a").wrapInner("<span />");
		
	// Add spans to blog h2
	$(".blog h2, .events h2").wrapInner("<span />");
	
	// Ask a Sexpert open and close
	$(".sexpert .listing details").slideUp();
	
	// If you click on the Question or Open/Close Answer link, toggle Answer display
	$(".sexpert .listing a.open, .sexpert .listing a.opened, .openAnswer").click(function(){
		answer = $(this).parent().find(".details");
		toggleAnswer(answer);
		
		if(event.preventDefault){
		    event.preventDefault();
		}else{
		    event.returnValue = false; 
		}

	});
	
	if($(".subscribe").length>0){
		$(".subscribe").fancybox({
			'autoDimensions'	: false,
			'width'				: 400,
			'height'			: 330,
			'padding'			: 40,
			'scrolling'			: 'no',
			'overlayColor'		: '#fff',
			'overlayOpacity'	: 0.3
		});
	}
	
	$(".listing:last").addClass("last");
	
	over18 = false; // default state of age verification
	
	// Hide the videos
	$("#video-box").hide();
	$("#top-video").hide();
	$("#bottom-video").hide();
	
	// Anal Sex Video Thumbnail Click
	$('.as-link').click(function(event){
	 	event.preventDefault();
		$('.agever').removeClass('agever');
		videourl = this;
	 	if(over18) {
	 		openVideo(this);
	 	} else {
			$(this).addClass('agever');
	 		thisBtnPos = $(this).position();
	 		$('#age-verification').css({'top' : thisBtnPos.top, 'left' : thisBtnPos.left}).fadeIn(200);
	 	}
	});
	
	// Age Verification (Yes Event)
	$('#age-yes').click(function(event){
		event.preventDefault();
		$('.agever').removeClass('agever');
		$('#age-verification').fadeOut(200);
		over18 = true;
		$('.default').removeClass('default');
		$('.as-link .as-border').animate({height: '128px'},300);
		$('.as-link .as-thumb').animate({top: '-56px'},300, function() {
		    $('#video-box').slideDown(300, function() {
				openVideo(videourl);
			});
		});
	});
	
	// Age Verification (No Event)
	$('#age-no').click(function(event){
		event.preventDefault();
		$('.agever').removeClass('agever');
		$('#age-verification').fadeOut(200);
	});
	
	// Opens the selected video
	function openVideo(videobtn) {
		if(!$(videobtn).hasClass('selected')) { // if video isn't already playing
			$('.selected').removeClass('selected');
			$(videobtn).addClass('selected');
			video = $(videobtn).attr('href');
			
			$(video).show();
			
			// We need to do a manual check of the variable video as the Sublime Video API doesn't handle id's that have a #.
			if(video == "#top-video"){
				sublimevideo.unprepare('bottom-video');
				$("#bottom-video").hide();
				sublimevideo.prepare('top-video');	
			} else {
				sublimevideo.unprepare('top-video');
				$("#top-video").hide();
				sublimevideo.prepare('bottom-video');
			}			
		}
	}
	
		// content image wrapper
	$('#main img').each(function(event){
		width = $(this).width();
		height = $(this).height();
		if(width<=height) { // if the image is portrait
			pullback = height/4;
			wrapheight = height/2;
			Math.round(pullback);
			Math.round(wrapheight);
			$(this).wrap('<a href="#" class="img-wrap" style="height: ' + wrapheight + 'px;"/>');
			$(this).css({'top':-pullback});
			$(this).after('<span class="open-icon">&nbsp;</span>');
		}
	});
	
	// opens the image wrapper
	$('.img-wrap').click(function(event){
		event.preventDefault();
		if($(this).hasClass('wrapper-open')) {
			$(this).removeClass('wrapper-open');
		} else {
			$(this).addClass('wrapper-open');
			$('html,body').animate({scrollTop:$(this).offset().top}, 500); // scrolls to title
		}
	});
	
	
}); //end document ready
