
/*

Developed by:

      ___           ___                 
     /__/|         /__/\        ___     
    |  |:|         \  \:\      /  /\    
    |  |:|          \  \:\    /  /:/    
  __|  |:|      _____\__\:\  /__/::\    
 /__/\_|:|____ /__/::::::::\ \__\/\:\__ 
 \  \:\/:::::/ \  \:\~~\~~\/    \  \:\/\
  \  \::/~~~~   \  \:\  ~~~      \__\::/
   \  \:\        \  \:\          /__/:/ 
    \  \:\        \  \:\         \__\/  
     \__\/         \__\/               

*/

/*******************************
        Event Handlers
*******************************/

chester.onReady = function() {

	// run once to size site
	chester.resizeColumns();
		
	// append Safari stylesheet
	if($.browser.safari) {
		$('head').append(chester.safariStyleSheet);
	}
	
	// only load images on screen
	$("#content img").lazyload(chester.lazyLoad);		
	
	// precache required content
	chester.precache(chester.precacheable);
	
	// add event for resizing columns on window change
	$(window)
		// hide post count on window click
		.click(function() {
      		$postCount.fadeOut(chester.post.fadeDuration);
			$(this).unbind('click');			
		})
		.scroll(function () { 
      		$postCount.fadeOut(chester.post.fadeDuration);
   		})
		.resize(function() {
			// self clearing timer set to 30ms delay to prevent overfiring
			chester.delayedTimer(chester.resizeTimer, chester.resizeColumns, chester.resizeDelay);
		})
	;
	
	// Prompt for chrome frame install for IE6
	if(chester.chromeFrameRequired && $.browser.msie && parseInt(+$.browser.version) < 7) {
		chester.chromeFrameInstall();
	};
	
	// cache dom objects
	// *NOTE - these originally descended using jQuery object caching, but this INCREASED load time during memory profiling
	// Sizzle engine appears to be faster when used normally and not descending from cached object
	var $cheetos = $('#toolbar .cheetos');
	// search
	var $search = $('#search');	
	var $searchForm = $('#toolbar .search.module form');
	var $searchGo = $('#toolbar .search .go');
	
	
	var $dropdown = $('#filter');
	var $navigation = $('#navigation li');
	var $navigationSelect = $('#navigation select');
	var $navigationMenu = $('#navigation li:has(.menu)');
	
	// cache dom card components
	var $cards = $('#content .card');
	var $cardLink = $('#content .card .info a');
	var $loaders = $('#content .card .throbber');
	var $cardContent = $('#content .card .content');
	var $swap = $('#content .card .swap');
	var $linkCopy = $('#content .card li.link');
	var $embedCopy = $('#content .card li.embed');
	var $likes = $('#content .card .like');
	var $shareLinks = $('#content .card .share li');
	// photo lightbox cards
	var $photoCards = $('#content .card.photo');
	var $photoLinks = $('#content .card.photo .unit a');
	// cache twitter and slideshow 
	var $twitter = $('#content .card.twitter .front .unit');
	var $tweets = $('#content .card.twitter .front .unit .tweet');
	var $feature = $('#content .feature .card .slideshow');
	// one offs
	var $postCount = $('#post-count');
	var $about = $('#toolbar .links .about, #logo-menu .about');
	var $submit = $('#toolbar .links .submit, #logo-menu .submit');
	
	var $facebookLinks = $('#content .card.facebook .unit li');
	
	// Hide loader animations for performance
	/*
	setTimeout(function() {
		$loaders.hide();
	}, 1000);
	*/
	
	// Add pop effect to logo on hover and down
	$cheetos
		.hoverClass()
		.downClass()
	;
	
	// Add hover and down class for navigation
	$navigation
		.hoverClass()
		.downClass()
		.click(function() {
			var $menu = $(this).find('.menu');
			if(!$menu.exists()) {
				$(this)
					.addClass('active')
					.siblings()
						.removeClass('active')
				;
				// follow link
				window.location = $(this).find('a').attr('href');
				return false;
			}
		})
	;
	
	$navigationSelect
		.change(function() {
			window.location = $(this).find('option:selected').attr('value');
		})
	;
	
	
	$navigationMenu
		.hoverClass()
		.hover(function() {
			var $menu = $(this).find('.menu');
			$menu
				.show();
		}, function() {
			var $menu = $(this).find('.menu');	
			$menu
				.hide();
		})
		.find('.menu li a')
			.click(function() {
				$(this).parents('.menu').hide();
				var href = $(this).attr('href');
				window.location = href;			
			})
	;
	
	// Add hover and down effect to like this
	$likes
		.hoverClass()
		.hover(
			function(){
				if(!$(this).parents('.small').exists()) {
					var $text = $(this).find("p");
					// store text for mouseout
					$(this).data('defaultText', $text.html());
					// add unlike/like text
					if($(this).hasClass("liked")) {
						$text.html(chester.like.text.unlike);
					} 
					else {
						$text.html(chester.like.text.like);					  
					}
				}
			},
			function(){
				// cache
				var $this = $(this);
				if(!$this.parents('.small').exists()) {
					var $text = $this.find('p');  
					var $likeCount = $this.find(".likeCount");
					var likeCount = $likeCount.val();
					var defaultText = $(this).data('defaultText');
					// return text to default
					$text.html(defaultText);
				}
			}
		)
		.downClass()
		.click(function(e) {
			// prevent link from following
			e.stopImmediatePropagation();
			// cache
			var $post = $(this);
			var $card = $(this).parents('.card');
			var $text = $post.find('p');
			// report like to backend
			if (!$(this).hasClass("liked")){
				// add liked class
				$post.addClass('liked');
				// track like
				var title = $post.parents('.card').find('.title').html();
				if( $(this).parents('.feature').exists() ) {
					title = $post.parents('.card').find('.info .active a').html();
				}
				chester.track.like(title);
				// report like to backend
				chester.addLike($post, function() {
					// change default text 
					var text = $post.find('p').html();
					$post.data('defaultText', text);					
				});
			} 
			else {
				$post.removeClass("liked");
				// report unlike to backend
				chester.removeLike($post, function() {
					// change default text 
					var text =  $post.find('p').html();
					$post.data('defaultText', text);												   
				});
			}
			return false;
		})
	;
	/*
	$linkCopy
		.tooltip({
			className: 'link',
			text: chester.tooltip.link.text
		})
		.click(function() {
			var $tooltip = $('#tooltip');
			var $tooltipText = $('#tooltip-copy');
			$tooltipText.html(chester.tooltip.link.copied);
			setTimeout(function() {
				$tooltip
					.fadeTo(250, 0.0, 'easeInQuad')
					.fadeTo(150, 1.0)
					.fadeOut(250, 'easeInQuad', function(){
						$tooltip.remove();			   
					})
				;
			}, 750);
			return false;			
		})
	;
	$embedCopy
		.tooltip({
			className: 'embed',
			text: chester.tooltip.embed.text
		})
		.click(function() {
			var $tooltip = $('#tooltip');
			var $tooltipText = $('#tooltip-copy');
			$tooltipText
				.html(chester.tooltip.embed.copied);
			setTimeout(function() {
				$tooltip
					.fadeTo(250, 0.0, 'easeInQuad')
					.fadeTo(150, 1.0)
					.fadeOut(250, 'easeInQuad', function(){
						$tooltip.remove();			   
					})
				;
			}, 750);
			return false;			
		})
	;
	*/
	
	$shareLinks
		.click(chester.activateShareLinks)
	;
	
	// About overlay
	$about
		.click(function() {
      		// track click
			chester.track.about();
			// hide postcount
			$postCount.fadeOut(200);
			// show modal
			$.dimScreen(chester.crossfadeDuration, chester.dimmerOpacity, function() {
				var $aboutContent = $('#about');
				var $close = $aboutContent.find('.close');				
				$close
					.hoverClass()
					.downClass()
					.click(function() {
						$aboutContent.fadeOut(chester.crossfadeDuration, function() {
							$.unDimScreen();									
						});
						return false;
					})
				;
				$aboutContent.fadeIn(chester.crossfadeDuration);
			});
			return false;
		})
	;
	
	// Submission overlay
	$submit
		.click(function() {
      		$postCount.fadeOut(200);
			$.dimScreen(chester.crossfadeDuration, chester.dimmerOpacity, function() {
				// cache
				var $submitContent = $('#submit');
				var $submitCategory = $('#submit-category');
				var $submitButton = $submitContent.find('.submit');
				var $close = $submitContent.find('.close');
				var $retry = $submitContent.find('.success a, .error a');
				// attach events only on first load
				if( !$submitContent.hasClass('init') ) {
					// Add init class
					$submitContent.addClass('init');
					// Close modal
					$close
						.hoverClass()
						.downClass()
						.click(function() {
							$submitContent.fadeOut(chester.crossfadeDuration ,function() {
								$.unDimScreen();									
							});
							return false;
						})
					;
					// Submit new chester feed item
					$submitButton
						.hoverClass()
						.downClass()
						.click(function() {
							chester.submitContent();
							return false;
						})
					;
					// Retry submission 
					$retry
						.click(function() {
							$(this).parent().parent()
								.fadeOut(chester.crossfadeDuration, function(){
									$submitContent.find('.form').fadeIn(chester.crossfadeDuration);
								})
							;
							return false;
						})
					;					
					// init dropdown
					$submitCategory.initDropdown({
						shadowOffset: -5,
						opacity: 0
					});
				
				}
				$submitContent.fadeIn(chester.crossfadeDuration);
			});
			return false;
		})
	;
	
	// init dropdown
	$dropdown
		.initDropdown(chester.dropdownSettings)
	;	
	
	// init search
	$search
		.hoverClass()
		.focusClass()
		.preserveDefaultText()
	;
	$searchForm
		.submit(function() {
			var value = chester.addDashes( $('#search').val() );
			if ((value.toLowerCase() == "search-the-feed-") || (value.toLowerCase() == "enter-a-search-term-")){
				value = null;
				$("#search")
					.val("Enter a search term ...")
					.preserveDefaultText()
				;
			}
			if (value){
				var url = $(this).attr('action');
				window.location = url + value + '/';
			}
			return false;    	 
		 })
	;
	// search button
	$searchGo
		.hoverClass()
		.downClass()
		.click(function() {
			// submit form
			$(this).parents('form').submit();
			return false;
		})
	;
	
	// make sure link triggers photobox
	$photoCards
		.click(function(e) {
			var $this = $(this);
			var uid = $(this).find('.uid').html();
			// add viewed image dust
			if(!$this.find('.dust').exists()) {
				var $front = $(this).find('.front');
				chester.addDust($front);
			}
			var category = 'photo';
			var title = $this.find('.title').html();
			chester.track.feedView(category, title);
			chester.trackView(uid);
			// set active photo for share links
			chester.setActivePhoto($this);
			// prevent link from following
			$this.find('.unit a').click();
			return false;
		}
	);
	
	// Initialize photos
	$photoLinks
		.bind('mousedown', function() {
			var $this = $(this);
			var $card = $(this).parents('.card');
			var uid = $card.find('.uid').html();
			var $front = $card.find('.front');
			// add viewed image dust
			if(!$(this).find('.dust').exists()) {
				chester.addDust($front);
			}
			var category = 'photo';
			var title = $front.find('.title').html();
			// ajax request for db tracking
			chester.track.feedView(category, title);
			// 3rd party tracking code
			chester.trackView(uid);
			// set active photo config object
			chester.setActivePhoto($card);
			return false;
		})
		.fancybox(chester.fancyConfig)
	;
	
	$cardLink.click(function(e) {
			e.stopImmediatePropagation();
			window.open($(this).attr('href'));
			return false;
		})
	;
	
	// init card					   
	$cardContent
		.hoverClass({ filter: '.flip, .animating'})
		.click(function(e){
			var $this = $(this);
			var $front = $this.find('.front');
			var uid = $this.find('.uid').html();
			if($front.visible()) {
				var url = $front.find('.info a:visible').attr('href');
				// facebook link is not visible
				if($this.parents('.facebook').exists()) {
					url = $front.find('.info a').attr('href');
				}
				if(url != '' && url && typeof(url) != 'undefined') {
					// grab tracking info, take out semicolon
					var category = $this.find('h3').html().replace(':','');
					var title = $this.find('.title').html();
					chester.track.feedView(category, title);
					if(url == '#') {
						url = '';	
					}
					else {
						// pass in mouse coordinates
						chester.addDust($front);
						chester.trackView(uid);
						window.open(url);
					}				
				}
			}
		})
	;
	
	// init share
	$swap
		.hoverClass()
		.bind('mousedown',function() {
			var $content = $(this).parents('.content');	
			var $previousCards = $cards.find('.flip.content').not($content);
			// reset bg color
			$content.removeClass('hover');
			// stop slieshow if it exists 
			if($(this).parents('.feature').exists()) {
				$(this).parents('.card').find('.slideshow').cycle('pause');
			}
			// turn any flipped cards back
			if($previousCards.exists()) {
				setTimeout(function() {
				$previousCards.each(function() {
					chester.cardFlip($(this));
				}); 
				}, 300);
			}
			// flip new card
			chester.cardFlip($content);
		})
	;	
	
	
	// Iterate through all slideshows to create relative pager links !IMPORTANT!
	$twitter.each(function() {	
		var $this = $(this);
		// No way to relatively define pager reference, so pass in actual DOM element for pager
		var $pager = $this.next('ul');
		$this.cycle({ 
			fx:     'fade', 
			speed:  500, 
			timeout: 8000, 
			pager:  $pager, 
			pagerAnchorBuilder: function(idx, slide) { 
				return '<li><a href="#">'+idx+'</a></li>'; 
			} 
		});
	});
	
	$tweets
		.hoverClass()
	;
	$feature.each(function() {
		var $this = $(this);
		// No way to relatively define pager reference, so pass in actual DOM element for pager
		var $pager = $this.parent().next('ul');
		$this.cycle({ 
			fx:     'fade', 
			speed:  500, 
			timeout: 8000, 
			pager:  $pager,
			before: function(lastel, el) {
				var $el = $(this);
				var $card = $el.parents('.card');
				var $info = $card.find('.info div');
				var $like = $card.find('.like');
				var index = $el.parent().find('img').index($el);
				var $activeInfo = $info.eq(index);
				
				var uid = $activeInfo.find('input.uid').val();
				var likes = $activeInfo.find('input.likes').val();
				var liked = $activeInfo.find('input.liked').val();
				var likeText = chester.like.verbose.replace('$num',likes);
				
				// Set like heart icon
				var likeClass = 'like';
				if(liked == 'true') {
					var likeClass = 'like liked';	
				}
				
				// Set new like content
				$like
					.find('.uid')
						.html(uid)
						.end()
					.find('.likeCount')
						.val(likes)
						.end()
					.find('p')
						.html(likeText)
						.end()
					.attr('class', likeClass)
				;
				
				$info
					.hide()
					.removeClass('active')
				;
				var className = $activeInfo
					.fadeIn(500)
					.attr('class')
				;
				$activeInfo
					.addClass('active')
				;
				// add proper classname
				$card.attr('class', className+' card');
			},
			pagerAnchorBuilder: function(idx, slide) { 
				return '<li><a href="#">'+idx+'</a></li>'; 
			} 
		});
	});	
	
	// Special dust tracking for facebook links
	$facebookLinks
		.click(function() {
			if(!$(this).find('.dust').exists()) {
				var $front = $(this).parents('.front');
				chester.addDust($front);
			}
		})
	;
	
	// add featured badge
	chester.addBadge()

};
$(document).ready(chester.onReady); 