/*! matchMedia() polyfill - Test a CSS media type/query in JS. Authors & copyright (c) 2012: Scott Jehl, Paul Irish, Nicholas Zakas. Dual MIT/BSD license */

window.matchMedia = window.matchMedia || (function(doc, undefined){
  
  var bool,
      docElem  = doc.documentElement,
      refNode  = docElem.firstElementChild || docElem.firstChild,
      // fakeBody required for <FF4 when executed in <head>
      fakeBody = doc.createElement('body'),
      div      = doc.createElement('div');
  
  div.id = 'mq-test-1';
  div.style.cssText = "position:absolute;top:-100em";
  fakeBody.appendChild(div);
  
  return function(q){
    
    div.innerHTML = '&shy;<style media="'+q+'"> #mq-test-1 { width: 42px; }</style>';
    
    docElem.insertBefore(fakeBody, refNode);
    bool = div.offsetWidth == 42;  
    docElem.removeChild(fakeBody);
    
    return { matches: bool, media: q };
  };
  
})(document);

jQuery(function($){

	var mo = {
		
		ATL_THUMB_BASE: 'http://www.oliverdore.com/monologue/article-thumbs/',

		iOS: (navigator.userAgent.match(/iPad/i) != null || navigator.userAgent.match(/iPhone/i) != null),

		iPhone: navigator.userAgent.match(/iPhone/i) != null,

		dims: { },

		support: {
			css_transitions: document.body.style.webkitTransition !== undefined || document.body.style.MozTransition !== undefined
		},

		el: {
			body: $('body'),
			wrap: $('section#wrap'),
			parent_wrap: $('ul#posts'),
			posts: $('ul#posts li.post'),
			content_wrap: $('section#content'),
			share_link: $('a#share-link'),
			share_icon: $('span#share-icon'),
			share_opts: $('ul#share-opts')
		},

		states: {
			mini_layout_flag: false,
			masonry_active: false
		},

		bindResize: function(){
			$(window).bind('resize', function(){
				mo.dims.win_width = $(window).width();
				if (matchMedia("(max-width: 640px)").matches || mo.dims.win_width < 640) {
					if(!mo.states.mini_layout_flag){
						mo.states.mini_layout_flag = true;
						if(mo.states.masonry_active) mo.destoryMasonry();
					}
				} else {
					mo.states.mini_layout_flag = false;
					if(!mo.states.masonry_active) mo.initMasonry();
				}
			}).trigger('resize');
		},

		initMasonry: function(){
			if(!mo.iPhone){
				var posts = mo.el.posts,
					col_width = (mo.iOS) ? 10 : 10;
				if(posts.length){
					 mo.el.parent_wrap.masonry({
	    				itemSelector : '.post',
	    				columnWidth : col_width,
	    				isAnimated: !mo.support.css_transitions
	  				});
	  				mo.states.masonry_active = true;
				}
			}
		},

		destoryMasonry: function(){
			mo.el.parent_wrap.masonry('destroy');
			mo.states.masonry_active = false;
		},

		addPostThumbs: function(){
			var posts = mo.el.posts;
			if(posts.length){
				$.each(posts, function(i, post){
					var wrap = $(post).find('div.wrap'),
						img_id = wrap.data('img');
					wrap.css('background-image', 'url(' + mo.ATL_THUMB_BASE + img_id + '.jpg)');
				});
			}	
		},

		bindPostClicks: function(){
			var posts = mo.el.posts;
			if(posts.length){
				$.each(posts, function(i, post){
					var post = $(post),
						link = post.find('a').attr('href');
					post.on('click', function(e){
						e.preventDefault();
						window.location.href = link;
					});
				});
			}
		},

		initDropCap: function(){
			if(mo.el.content_wrap.length){
				// Get first paragraph with text
				var first_para = false,
					first_letter;
				$.each(mo.el.content_wrap.find('p').not('.date'), function(i, para){
					var $para = $(para);
					if($para.text().length){
						first_para = $para;
						return false;
					}
				});
				
				if(first_para){

					// Skip categories - this is a check for a parent class on the paragraph tag
					// We can't add a skip class on the paragraph tag itself
					var skip_types = [
						'.sec-audio'
					];

					var skip_drop_cap = first_para.parents(skip_types.join(','));

					if(!skip_drop_cap.length){

						first_letter = first_para.text().substring(0,1);

						// Build dropcap
						var dc = $('<span class="drop-cap">' + first_letter + '</span>');

						// Remove first letter from first paragraph
						first_para.text(first_para.text().substring(1));

						// Append dropcap
						dc.prependTo(first_para);
					}

					// Bold first paragraph
					first_para.addClass('bold');

				}

			}
		},

		initShare: function(){
			// Google+
		    var po = document.createElement('script');
		    po.type = 'text/javascript'; 
		    po.async = true;
		    po.src = 'https://apis.google.com/js/plusone.js';
		    var s = document.getElementsByTagName('script')[0];
		    s.parentNode.insertBefore(po, s);

		    // Bind share link
		    mo.el.share_link.on('click', function(e){
		    	e.preventDefault();
		    	var link = $(this);
		    	if(!link.hasClass('active')){
		    		// Not currently active
		    		link.addClass('active');
		    		mo.el.share_icon.addClass('active');
		    		mo.el.share_opts
		    			.addClass('active')
		    			.css('opacity', '0')
		    			.animate({
		    				'opacity': '1',
		    				'top': '-5px'
		    			}, 350, 'easeInOutCirc');

		    	} else {
		    		// Active
		    		mo.el.share_icon.removeClass('active');
		    		
		    		mo.el.share_opts
		    			.animate({
		    				'opacity': '0',
		    				'top': '5px'
		    			}, 350, 'easeInOutCirc', function(){
		    				link.removeClass('active');
				    		mo.el.share_opts.removeClass('active');
				    		mo.el.share_opts.removeAttr('style');		    				
		    			});

		    	}
		    });

		},

		bindFullScreen: function(){

			  var wrap = mo.el.wrap[0];
			    
			  function toggleFullScreen() {
			    if (!document.mozFullScreen && !document.webkitFullScreen) {
			      if (wrap.mozRequestFullScreen) {
			        wrap.mozRequestFullScreen();
			      } else {
			        wrap.webkitRequestFullScreen(Element.ALLOW_KEYBOARD_INPUT);
			      }
			    } else {
			      if (document.mozCancelFullScreen) {
			        document.mozCancelFullScreen();
			      } else {
			        document.webkitCancelFullScreen();
			      }
			    }
			  }
			  
			  document.addEventListener("keydown", function(e) {
			    if (e.keyCode == 13) {
			      toggleFullScreen();
			    }
			  }, false);

		},

		// Init
		init: function(){
			mo.bindResize();
			mo.addPostThumbs();
			mo.bindPostClicks();
			mo.initDropCap();
			mo.initShare();
			mo.bindFullScreen();
		}

	};

	// Initialize
	mo.init();

});
