$(document).ready(function() {
	/* Use this js doc for all application specific JS */
	/* ENABLE FANCYBOX, FOR ARTICLE-LEVEL LIGHTBOXES */
	var fancyboxBox = $('.fancybox, .fancybox-thumbs');
	
	if (fancyboxBox.length) {
		fancyboxBox.fancybox({
			prevEffect : 'none',
			nextEffect : 'none',
			closeBtn   : false,
			arrows     : false,
			nextClick  : true,
      beforeLoad : function() { $('html, body').css('overflow','hidden'); },
      afterClose : function() { $('html, body').css('overflow','auto'); },
			helpers    : {
				thumbs : {
					width: 200,
					height: 200
				}
			}
		});
	}

	var fancyBoxVarious = $('.various');
	if(fancyBoxVarious.length){ 
		fancyBoxVarious.fancybox({
			maxWidth	  : 800,
			maxHeight	  : 600,
			fitToView	  : false,
			width		    : '70%',
			height		  : '70%',
			autoSize	  : false,
			closeClick	: false,
			openEffect	: 'none',
			closeEffect	: 'none',
      beforeLoad  : function() { $('html, body').css('overflow','hidden'); },
      afterClose  : function() { $('html, body').css('overflow','auto'); }
		});
	}
	
	var youtubeLinks = $('a.youtube.video');
	if(youtubeLinks.length) {
		var regExp = /^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\?))\??v?=?([^#\&\?]*).*/;
		var match = $('a.youtube.video').attr('href').match(regExp);
		if (match&&match[7].length==11){        
		  youtubeLinks.attr('href', 'http://www.youtube.com/embed/' + match[7] + '?rel=0&autoplay=1');
		  youtubeLinks.fancybox({
		      maxWidth      : 960,
		      maxHeight     : 540,
		      fitToView     : true,
		      width         : '70%',
		      height        : '70%',
		      autoSize      : false,
		      closeClick    : false,
		      openEffect    : 'fade',
		      closeEffect   : 'fade',
		      padding       : 0,
		      beforeLoad    : function() { $('html, body').css('overflow','hidden'); },
		      afterClose    : function() { $('html, body').css('overflow','auto'); }
		  });
		}
	}

	var fancyBoxButtons = $('.fancybox-buttons');
	if(fancyBoxButtons.length){ 
	fancyBoxButtons.fancybox({
		openEffect  : 'none',
		closeEffect : 'none',	
		prevEffect  : 'none',
		nextEffect  : 'none',
		closeBtn    : false,
    beforeLoad  : function() { $('html, body').css('overflow','hidden'); },
    afterClose  : function() { $('html, body').css('overflow','auto'); },
		helpers     : {
			title : {
				type : 'inside'
			},
			buttons	: {}
		}
	});
}
	/* TABS --------------------------------- */
	/* Remove if you don't need :) */
		
	/* PLACEHOLDER FOR FORMS ------------- */
	/* Remove this and jquery.placeholder.min.js if you don't need :) */
	$('input, textarea').placeholder();


	$('a#show_letters_modal').click(function(e) {
		e.preventDefault();
		$('#letter_editor_submit').reveal({
			animation: 'fadeAndPop',
			animationspeed: 900,
			closeOnBackgroundClick: false,
			dismissModalClass: 'cancel'
		});
	});
	$('a#show_add_event_modal').click(function(e) {
		e.preventDefault();
		$('#submit_event_form').reveal({
			animation: 'fadeAndPop',
			animationspeed: 900,
			closeOnBackgroundClick: false,
			dismissModalClass: 'cancel'
		});
	});	
	$('a#show_submit_pothole_reveal').click(function(e) {
		e.preventDefault();
		$('#submit_pothole_form').reveal({
			animation: 'fadeAndPop',
			animationspeed: 900,
			closeOnBackgroundClick: false,
			dismissModalClass: 'cancel'
		});
	});	
	/* FORM VALDATION, USING jQuery Validation Engine ------------- */
	/* https://github.com/posabsolute/jQuery-Validation-Engine            */
	/* This first bit sets needed form element states for the jQVE        */
	var submissionForm = $('#submit_event_form, #letter_editor_submit, #contactForm, #submit_pothole_form').find('form#freeform');
	if(submissionForm.length) {
		submissionForm.find('a#submitButton').click(function() {
			if(submissionForm.validationEngine('validate')) {
				submissionForm.submit();
			}
		});
		submissionForm.find('a#cancelButton').click(function() {
			submissionForm.validationEngine('hideAll');
		});
	}


	/* DISABLED BUTTONS ------------- */
	/* Gives elements with a class of 'disabled' a return: false; */
	
		/* script from markparolisi.com */
	$("a[href^='http://']").each(function(){
	    var thehref = $(this).attr('href');
	    if(!thehref.match(window.location.host)){
	        $(this).attr('target', '_blank');
	    }
	});

	// Extends jQuery to provide a NY Times like Read-More  on Article pages
	// https://github.com/xaviershay/nytimes-
	// 2011-NOV-01 Updated to latest version
	if(!isIOSDevice()) {
		(function ($) {
		  jQuery.fn.slidebox = function() {
		    var slidebox = this;
		    var originalPosition = slidebox.css('right');
		    var open = false;
		
		    /* GA tracking */
		    var track = function(label) {
		      return _gaq.push(['_trackEvent', 'Slidebox', label]);
		    };
		    var boxAnimations;
		
		    if (Modernizr.cssanimations) {
		      boxAnimations = {
		        open:  function() { slidebox.addClass('open'); },
		        close: function() { slidebox.removeClass('open'); }
		      };
		    } else {
		      boxAnimations = {
		        open: function() {
		          slidebox.animate({
		            'right': '0px'
		          }, 300);
		        },
		        close: function() {
		          slidebox.stop(true).animate({
		            'right': originalPosition
		          }, 100);
		        }
		      };
		    }
		
				var lastParagraph = $('#last');
				if(lastParagraph.length) {
			    $(window).scroll(function() {
			      var distanceTop = lastParagraph.offset().top - $(window).height();
			
			      if ($(window).scrollTop() > distanceTop) {
			        if (!open) {
			          open = true;
			          boxAnimations.open();
			          track("Open");
			        }
			      } else {
			        open = false;
			        boxAnimations.close();
			      }
			    });
				}
				
		    slidebox.find('.close').click(function() {
		      $(this).parent().remove();
		      track("Close");
		    });
		    slidebox.find('.related a').click(function() {
		      track("Read More");
		    });
		  };
		
		  $(function() {
		    $('#slidebox').slidebox();
		  });
		  
		})(jQuery);
	}
	
	if($('#landing_section_list').length) {
		/* IF ON NON-MOBILE SITE */
		if (screen.width > 600) {
				$('.more_articles').hide();
				$('#show_more_all').show();
				$('#show_more_all').css("display","block");
				$('#show_more_all').click(function() {
					$('.more_articles').slideToggle('slow');
					$(this).text($(this).text() == 'SHOW MORE FROM EDITION' ? 'HIDE MORE FROM EDITION' : 'SHOW MORE FROM EDITION');
					return false;
				});
			$('#landing_section_list .columns.four ul li a:even').addClass('alt');
		}
			$('#landing_section_list .columns.four ul li:last-child').filter(":visible").css("border-bottom","red");
	}

	/* Handle content flipping on GUIDES page                          */
	if($('#guideViewer').length) {
		$('#viewerReplacement').replaceWith(pdfViewerContent);
	}

	/* Initialize Pothole Pig Map Data                                 */	
	if($('#pothole_pig').length) {
		if(!isIOSDevice()) {
			initialize();
		}
	}

	/* Initialize Facebook Comments when appropriate, see the posting: */
	/* http://stackoverflow.com/questions/4556941/facebook-javascript-sdk-problem-fb-is-not-defined */
	var fbRoot       = $('#fb-root');
	var fbRootMobile = $('#fb-root-mobile');
	
	if(fbRoot.length || fbRootMobile.length) {
	  window.fbAsyncInit = function() {
	    FB.init({
	      appId  : '263954800299757',
	      status : true, // check login status
	      cookie : true, // enable cookies to allow the server to access the session
	      xfbml  : true  // parse XFBML
	    });
	  };
	
	  (function() {
	    var e = document.createElement('script');
	    e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
	    e.async = true;
	    /* Only post to the visible body, controls mobile versus non-mobile */
	    if(fbRoot.is(':visible')) { fbRoot.append(e); }
	    /* DISABLED DO TO MOBILE CONSTANT-LOAD BUG
	    else if(fbRootMobile.is(':visible')) { fbRootMobile.append(e); }
	    */
	  }());
  }
});

/***************************/
/* Global Helper functions */
/***************************/

/* Load up external JS and CSS data                                */
/* http://www.javascriptkit.com/javatutors/loadjavascriptcss.shtml */
function loadjscssfile(filename, filetype){
	var fileref;

	if (filetype === 'js') {
		fileref = document.createElement('script');
		fileref.setAttribute('type','text/javascript');
		fileref.setAttribute('src', filename);
	}
	else if (filetype === 'css') {
		fileref = document.createElement('link');
		fileref.setAttribute('rel', 'stylesheet');
		fileref.setAttribute('type', 'text/css');
		fileref.setAttribute('href', filename);
	}
	if (typeof fileref != 'undefined') {
		document.getElementsByTagName('head')[0].appendChild(fileref);
	}
	
	return true;
}

/* Some JS we only want to run on iOS devices, this helps us */
function isIOSDevice() {
	var result = false;
	var uagent = navigator.userAgent.toLowerCase();
	if(!result) { result = (uagent.search('iphone') > -1); }
	if(!result) { result = (uagent.search('ipod') > -1); }
	if(!result) { result = (uagent.search('iPad') > -1); }
	return result;
}

/* Cookie helper functions */
function createCookie(name,value,days) {
		var expires;
		
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        expires = '; expires='+date.toGMTString();
    }
    else { expires = ''; }
    
    document.cookie = name + '=' + value + expires + '; path=/';
}
function readCookie(name) {
    var nameEQ = name + '=';
    var ca = document.cookie.split(';');
    for(var i=0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') { c = c.substring(1,c.length); }
        if (c.indexOf(nameEQ) === 0) { return c.substring(nameEQ.length,c.length); }
    }
    return null;
}
function eraseCookie(name) {
    createCookie(name,'',-1);
}
