/*
|--------------------------------------------------------------------------
| Custom functions and plugins for Expeditionary Art
|--------------------------------------------------------------------------
*/
(function($){

	jQuery(document).ready(function(){
	
		var body = $('body');
		
		// customize <selects>
		eaScripts.customSelects();
		
		// clear inputs
		$('input:text').clearInput();

		// Home page specific
		if(body.hasClass('home')){
			eaScripts.homeBannerCycle();
		}
		
		// Single post specific
		if(body.hasClass('single-post')){
			eaScripts.limitComments();
		}
		
		// Archive specific
		if(	body.hasClass('page-template-archive-php') || 
				body.hasClass('search-results') || 
				body.hasClass('archive')){
			eaScripts.blogArchives();
		}
		
		// Shop specific
		if(body.hasClass('page-template-taxonomy-shop-categories-php')){
			eaScripts.shopFilter();
			eaScripts.shopInfoButton();
			eaScripts.shopProductLinks();
		}
		
		// Product page specific
		if(body.hasClass('single-product')){
			eaScripts.shopInfoButton();
			eaScripts.shopProductCycle();
			eaScripts.shopProductLinks();
		}
		
		// Project page specific
		if(body.hasClass('page-template-project-php')){
			eaScripts.mediaPlayer();
		}
		
		jQuery('a.rollover-image-link').each(function(){
  
	  	var container = jQuery(this);
	  	var image = container.find('img');
	  	var imageSrc = image.attr('src');
	  	var newImage = container.attr('href');
	  	
			container.hover(
				function(){
					image.attr('src', newImage);
				},
				function(){
					image.attr('src', imageSrc);
				}
			);
	  });
	
	});
	
	/*
	|--------------------------------------------------------------------------
	| Expeditionary art scripts
	|--------------------------------------------------------------------------
	*/
	var eaScripts = {
	
		/**
		 * Customize <selects>
		 */
		customSelects: function(){

			$('.customselect').each(function(){
				
				var cs = $(this),
					select = cs.find('select'),
					classes = select.attr('class').split(/\s+/),
					options = select.find('option'),
					selected = select.find('option:selected'),
					submit = cs.find(':submit');
					
				// add button class
				classes.push('button');
					
				// wrap select in dl
				select.wrap('<dl>');
				
				cs = select.parent('dl');
				
				// move select classes to cs
				for(var i = 0; i < classes.length; i++){
					cs.addClass(classes[i]);
				}
				
				// replace select with dt and dd > ul, using first option as title
				select.replaceWith('<dt>' + selected.text() + '</dt><dd><ul></ul></dd>');
				
				// add options to ul, minus first option
				var ul = cs.find('dd ul');
				
				options.each(function(){
					if($(this).index() > 0){
						ul.append('<li><a href="' + $(this).attr('value') + '" data-filter="' + $(this).attr('data-filter') + '">' + $(this).text() + '</a></li>');
					}
				});
				
				// list should be at least as wide as its parent
				if(ul.outerWidth() < cs.outerWidth()){
					ul.width(cs.outerWidth());
				}
				
				var list = cs.find('dd');
				
				// clicking outside of a customselect
				$(document).click(function(){
					list.fadeOut(100);
					cs.removeClass('active');
				});
				
				// clicking a customselect
				cs.click(function(event){
					event.stopPropagation();
					
					// if active, fade out
					if(select.hasClass('active')){
						list.fadeOut(100);
						cs.removeClass('active');
					} else {
						// disable other customselects
						$('.customselect').find('dl').each(function(){
							$(this).removeClass('active')
								.find('dd')
								.fadeOut(100);
						});
						
						list.fadeIn(100);
						cs.addClass('active');
					}
				});
				
			 	/* // use this if filtering with isotope
				cs.find('a').click(function(){
					$(this).attr('selected', 'selected');
					list.fadeOut(100);
					cs.removeClass('active');
					return false;
				}); */
					
			});
			
		},
		
		/**
		 * Home page banner cycle
		 */
		homeBannerCycle: function(){
			$('.feature:hidden').show();
			
			$('#features').find('.cycle')
			.before('<div id="cycle-nav">')
			.cycle({
				fx: 'fade',
				pause: 1,
				speed: 500,
				timeout: 6000,
				pager: '#cycle-nav'
			});
		},
		
		/**
		 * Limit number of comments displayed on blog posts
		 * (add button to show all)
		 */
		limitComments: function(){
			var comments = $('.comment'),
					count = comments.length,
					show = 5,
					hidden = count - show;
					
			comments.filter(function(index){
				if(index > (show - 1)) return this;
			}).wrapAll('<div class="more-comments">');
			
			var moreComments = $('.more-comments');
			
			if(hidden > 1){
				moreComments.hide();
				
				$('<a href="#" class="button showCommentsButton">' + hidden + ' more comments...</a>')
					.insertAfter(moreComments);
					
				$('.showCommentsButton').click(function(){
					$(this).fadeOut(200);
					moreComments.slideDown(600);
					return false;
				});
			}
		},
		
		/**
		 * Implement isotope for blog archives
		 */
		blogArchives: function(){
			$('.archives').isotope({
				itemSelector: '.entry',
				layoutMode: 'fitRows'
			});
		},
		
		/**
		 * Implement isotope for shop
		 */
		shopFilter: function(){
			// handle hash tags
			var hash = window.location.hash.replace('#', ''),
					filter = hash !== '' ? '.' + hash : '*',
					buttons = $('.controls .buttons'),
					filterButton = buttons.find('a[data-filter="' + filter + '"]'),
					filterTitle = filter === '*' ? '' : ': ' + filterButton.text(),
					pageTitle = $('.page-header h1');
					

		
			// highlight filter button, add filter page title
			buttons.find('a.active').removeClass('active');
			filterButton.addClass('active');
			pageTitle.append('<span>' + filterTitle + '</span>');
			
			// isotope
			$('.shop').isotope({
				itemSelector: '.product',
				layoutMode: 'cellsByRow',
				cellsByRow: {
					columnWidth: 240,
					rowHeight: 300
				},
				filter: filter
			});
			
			// clicking buttons
			buttons.find('a').click(function(){
				filter = $(this).attr('data-filter');
				filterTitle = filter === '*' ? '' : ': ' + $(this).text();
				
				pageTitle.find('span').remove();
				pageTitle.append('<span>' + filterTitle + '</span>');
				
				buttons.find('a.active').removeClass('active');
				$(this).addClass('active');
				
				$('.shop').isotope({ filter: filter });
				
				hash = filter === '*' ? '' : filter.replace('.', '');
				
				window.location.hash = hash;
				
				return false;
			});
			
			// clicking category links on shop items
			var shopItems = $('.shop .product');
			
			shopItems.find('a').click(function(){
				filter = $(this).attr('data-filter');
				
				filterTitle = filter === '*' ? '' : ': ' + $(this).text();
				
				pageTitle.find('span').remove();
				
				pageTitle.append('<span>' + filterTitle + '</span>');
				
				buttons.find('a.active').removeClass('active');
				
				
				
				// activate this category or parent category in buttons
				buttons.find('[data-filter="' + filter + '"]').addClass('active');
				
				$('.shop').isotope({ filter: filter });	
				hash = filter === '*' ? '' : filter.replace('.', '');
				window.location.hash = hash;
				return false;
			});
		},
		
		shopInfoButton: function(){
			// shop info button
			var button = $('#shop-info'),
			header = button.parent('header');
		
			header.after('<div id="shop-info-area" class="clearfix"><div class="info"></div><a href="#" class="button align-right"></a></div>');
		
			var infoArea = $('#shop-info-area').hide(),
					buttonWords = button.text().split(/\s/),
					firstWord = buttonWords[0],
					lcFirstWord = firstWord.toLowerCase(),
					buttonWords = button.text().replace(firstWord, lcFirstWord),
					closeButton = infoArea.find('.button').text('Hide ' + buttonWords);
			
			infoArea.find('.info').load('/info/ .entry');
		
			button.click(function(event){
			
				if(!$(this).parents('html').hasClass('lt-ie9')){
					event.preventDefault();
					
					infoArea.slideDown(300);
					$(this).fadeOut(200);		
					
				}
			});
			
			closeButton.click(function(){
				infoArea.slideUp(300);
				button.fadeIn(200);
				return false;
			});	
		},
		
		/**
		 * Product image cycle
		 */
		shopProductCycle: function(){
			$('.product-images .cycle')
				.before('<div id="cycle-nav">')
				.cycle({
					fx: 'fade',
					pause: 1,
					speed: 500,
					timeout: 6000,
					pager: '#cycle-nav'
				});
		},
		
		/**
		 * Replace normal shop links with isotope filter links for product pages
		 */
		shopProductLinks: function(){
			$('.controls .buttons').find('a').each(function(){
				var filter = $(this).attr('data-filter') != '*' ? '#' + $(this).attr('data-filter').replace('.', '') : '';
				$(this).attr('href', $(this).attr('href').replace(/shop(.*)/, 'shop/' + filter));
			});
		},
		
		/**
		 * Feature media display
		 */
		mediaPlayer: function(){
		
			var player = $('.player'),
					content = player.find('.content'),
					dashboard = player.find('.dashboard'),
					thumbs = dashboard.find('li');
					
			thumbs.find('a').click(function(event){
			
				if(!$(this).parents('html').hasClass('lt-ie9')){
					event.preventDefault();
				}
			
				// remove ssp navigation if present
				content.find('.ssp-nav').remove();
			
				var mediaSource = $(this).attr('href') + ' .media',
						contentHeight = content.outerHeight(); // save content height for now
						
				// do nothing if active
				if($(this).hasClass('active')) return false;
				
				// switch active class to new item
				player.find('.active').removeClass('active');
				$(this).addClass('active');
				
				// add loading indicator
				content.append('<div id="loading">loading...</div>');
				
				var loading = content.find('#loading');
				
				loading.css({
					'left': content.width() / 2 - loading.width() / 2,
					'top': content.height() / 2 - loading.height() / 2
				}).fadeIn(100);
				
				// adjust content height
				content.height(contentHeight)
					.find('.media-container')
					
					// load media
					.load(mediaSource, '', function(){
					
						var mediaContainer = $(this);
								
						if(mediaContainer.find('.ssp-album').length > 0){
							eaScripts.mediaSlideShow();	
						}
						
						// adjust content height
						content.animate({ 'height': mediaContainer.find('.media').outerHeight() }, 100, 'swing');
						
						// remove loading indicator
						loading.fadeOut(100);
					});
			});
		
		},
		
		mediaSlideShow: function(){
			
			var player = $('.player'),
					content = player.find('.content'),
					album = content.find('.ssp-album'),
					items = album.find('article'),
					maxHeight = 0;
			
			items.each(function(){
			
				var item = $(this);
				
				// find max height of items (image, title, caption)
				maxHeight = Math.max(item.outerHeight(), maxHeight);
				
				item.css({
					'display': 'none',
					'visibility': 'visible'
				});
				
				// center
				item.find('div').css({
					'left': album.width() / 2 - item.width() / 2,
					'top': maxHeight / 2 - item.height() / 2
				});
				
			});
			
			// set container height to max height
			album.height(maxHeight);
			
			// display first item
			items.first().show();
			
			// setup navigation
			content.append('<div id="ssp-next" class="ssp-nav"></div><div id="ssp-prev" class="ssp-nav"></div><div id="ssp-tooltip"></div>');
			
			var nav = content.find('.ssp-nav'),
					next = content.find('#ssp-next'),
					prev = content.find('#ssp-prev'),
					toolTip = content.find('#ssp-tooltip');
					
			nav.css({
				'width': album.width() / 3,
				'height': album.height()
			});
			
			// tooltips
			toolTip.hide();
			
			content.mousemove(function(event){
				toolTip.css({
					'left': event.pageX - $(this).offset().left - (toolTip.width() / 2),
					'top': event.pageY - $(this).offset().top - 30
				});
			});
			
			// set up cycle
			album.cycle({
				fx: 'fade',
				speed: 500,
				timeout: 40000000,
				next: '#ssp-next',
				prev: '#ssp-prev'
			});
			
			nav.hover(
				function(){
				
					album.cycle('pause'); // pause for whole area, not just prev and next
				
					if($(this).is('#ssp-next')){
						toolTip.text('next');
					} else {
						toolTip.text('previous');
					}
					toolTip.show();
				},
				function(){
					album.cycle('resume');
				
					toolTip.hide();
				}
			);
			
			
				
			
		},
		 		
	}

})(jQuery);

/*
|--------------------------------------------------------------------------
| Plugins
|--------------------------------------------------------------------------
*/

/*
jQuery Clear-Input plugin
v1.0
Author: Aidan Feldman

USAGE
Add the class .clear-input to any text input element
whose value you want cleared when it gains focus.
The initial value will be replaced when the input
loses focus, and no new text has been entered.

If you prefer to not add classes to your elements,
you can alternatively call clearInput() on any jQuery
input object.
*/
(function( $ ){
  // define the initialValue() function
  $.fn.initialValue = function(value) {
    if (value) {
      return this.attr('initial-value', value);
    } else {
      return this.attr('initial-value');
    }
  };
  
  $.fn.clearInput = function() {
    return this
      .focus(function(){
        if (this.value == $(this).initialValue()) {
          this.value = '';
        }
      })
      .blur(function(){
        if (this.value == '') {
          this.value = $(this).initialValue();
        }
      })
      .each(function(index, elt) {
        $(this).initialValue(this.value);
      });
  };

  // apply plugin to all inputs with class ".clear-input"
  $(function() {
    $('input.clear-input').clearInput();
  });
})( jQuery );
