/**
 * @note Application level jQuery and/or javascript code
 */

/**
 * Functions to write and read cookies
 * @author Peter Paul Koch (PPK)
 */
function createCookie(name,value,days) {
  if (days) {
    var date = new Date();
    date.setTime(date.getTime()+(days*24*60*60*1000));
    var 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;
}

/**
 * Functions to get and set the body's font size
 * @author William Dodson
 */
function getBodyFontSize() {
  var size = $('body').css('font-size');
  return size;
}
function setBodyFontSize(size) {
  $('body').css({
    'font-size': size
  });
}

/**
 * Get the Base URL for the current site
 */
function getBaseURL() {
  var url = location.href;
  var baseURL = url.substring(0, url.indexOf('/', 14));
  if (baseURL.indexOf('http://localhost') != -1) {
    var url = location.href;
    var pathname = location.pathname;
    var index1 = url.indexOf(pathname);
    var index2 = url.indexOf("/", index1 + 1);
    var baseLocalUrl = url.substr(0, index2);
    
    return baseLocalUrl + "/";
  } else {
    return baseURL + "/";
  }
}

/**
 * When the user navigates away from the page 
 * we set a cookie with their current font size
 * to use later.
 */
$(window).unload(function(e) {
  var size = getBodyFontSize();
  createCookie("fontsize", size, 365);
});

// The base URL
var baseURL = getBaseURL();

// Speed of the automatic slideshow
var slideshowSpeed = 6000;

// Variable to store the images we need to set as background
// which also includes some text and url's.
var photos = [ {
		"title" : "Feeling Independent?",
		"image" : "header-bg-img_1.jpg",
		"url" : "/news/feeling-independent",
		"firstline" : "Are you",
		"secondline" : "empowered?"
	}, {
		"title" : "Places of Worship",
		"image" : "header-bg-img_2.jpg",
		"url" : "/resources/worship",
		"firstline" : "Find your place of",
		"secondline" : "worship"
	}
];

$(document).ready(function() {
  // text placeholders for forms
  $('#s').textPlaceholder();
  $('#newsletter-signup input.text').textPlaceholder();
  
  // see if we have a fontsize cookie set
  var cookieFont = readCookie('fontsize');
  var size = cookieFont ? cookieFont : getBodyFontSize();
  setBodyFontSize(size);
  
  // Check cookie for contrast mode
  var cookiecontrast = readCookie('highcontrast');
  if (cookiecontrast) {
      var style = "<style>body, h1, h2, h3, h4, h5, h6, a:link, a:visited, a:focus, a:hover, a:active, abbr[title='and'], #header #masthead #tagline, .post-share, #nav-util, #nav-util #top-opts a, #nav-util #top-opts #view-opts li#opt-text a:hover, #nav-util #top-opts #view-opts li#opt-text-large a:hover, #nav-util #top-opts #view-opts li#opt-contrast a:hover, #nav-util #top-opts #view-opts li#opt-contrast-high a:hover, #nav-util #top-opts #view-opts li#opt-translate a:hover, #nav #menu-main li a, body#home #nav #menu-main li#nav-home a, body#about #nav #menu-main li#nav-about a, body#news-events #nav #menu-main li#nav-news a, body#services #nav #menu-main li#nav-services a, body#support-groups #nav #menu-main li#nav-support a, body#resources #nav #menu-main li#nav-resources a, body#help-meril #nav #menu-main li#nav-help-meril a, body#blog #nav #menu-main li#blog a, #nav #menu-main li a:focus, #nav #menu-main li a:hover, #article #resource-list h3 a, #callouts h2 a:hover, #callouts h2#cta-schedule a:hover, #callouts h2#signupnewsletter a:hover, #aside #latest-news dt a, #testimonial-text blockquote p, #tertiary #newsletter-signup, #newsletter-signup h2, #newsletter-signup label, #newsletter-signup label:hover, #tertiary #character-trait, #footer, #footer a, #footer a:hover, .button, .blue, .blue:active, .navy, .navy:hover, .navy:active, .orange, .orange:hover, .orange:active, .subheading, .text, .text-placeholder, .meta, .off-color, .menu li a  { color:#ffffff !important; }</style>";

        $(style).appendTo('body');
		
		var darktwo = "<style>body, .box, #article.subsection h2.post-title, #article.subsection hgroup h1, .widget-title, #top, #content, #bottom, #header, #tertiary #character-trait, #footer, #tagline em, #nav-util, #nav-util #top-opts #view-opts li#opt-text-large, #nav-util #top-opts #view-opts li#opt-contrast-high, #nav-util #top-opts #view-opts li#opt-text a, #nav-util #top-opts #view-opts li#opt-text-large a, #nav-util #top-opts #view-opts li#opt-contrast a, #nav-util #top-opts #view-opts li#opt-contrast-high a, #nav-util #top-opts #view-opts li#opt-translate a, #top-opts #form-search #s, #nav, body#home #nav #menu-main li#nav-home a, body#about #nav #menu-main li#nav-about a, body#news-events #nav #menu-main li#nav-news a, body#services #nav #menu-main li#nav-services a, body#support-groups #nav #menu-main li#nav-support a, body#resources #nav #menu-main li#nav-resources a, body#help-meril #nav #menu-main li#nav-help-meril a, body#blog #nav #menu-main li#blog a, #nav #menu-main li a:focus, #nav #menu-main li a:hover, #main, body#home #main, #article #resource-list, body#home #ancillary, #ancillary #donations, #ancillary #callouts, #callouts h2 a, #callouts h2#cta-schedule a, #callouts h2#signupnewsletter a, #callouts h2 a:hover, #callouts h2#cta-schedule a:hover, #callouts h2#signupnewsletter a:hover, .widget .testimonial { background:none !important; background-color:#000000 !important; text-shadow:0 0 #000 !important; -moz-box-shadow:none; }</style>";
		
		$(darktwo).appendTo('body');
		
		var darkone = "<style>#testimonial-text blockquote p, #testimonial-text cite, #tertiary, #tertiary #newsletter-signup, #tertiary #character-trait, #footer, #footer #menu-footer li, #footer #menu-footer li.last, #footer #menu-footer li:last-child, .blue, .blue:hover, .blue:active, .navy, .navy:hover, .navy:active, .orange, .orange:hover, .orange:active, .widget .testimonial, .even, .odd, #comments input, #comments textarea, input#submit, blockquote, h2, h3.widget-title, h3, h1, .menu li a:focus, .menu li a:hover, .menu { background:none !important; background-color:#000000 !important; text-shadow:0 0 #000 !important; -moz-box-shadow:none; }</style>";
		
		$(darkone).appendTo('body');
		
  }

  // prepend these to the view-opts menu to keep them out of the markup
  var optText = '<li id="opt-text" role="menuitem"><a href="'+ baseURL +'site-options/#normal-text" title="Normal text size">Normal</a></li>';
  var optTextLarge = '<li id="opt-text-large" role="menuitem"><a href="'+ baseURL +'/site-options/#large-text" title="Large text size">Large</a></li>';
  var optTextXtra = '<li id="opt-text-xtra" role="menuitem"><a href="'+ baseURL +'/site-options/#xtra-text" title="Extra Large text size">Extra Large</a></li>';
  var optContrast = '<li id="opt-contrast" role="menuitem"><a href="'+ baseURL +'site-options/#normal-contrast" title="Default layout">Default</a></li>';
  var optContrastHigh = '<li id="opt-contrast-high" role="menuitem"><a href="'+ baseURL +'site-options/#high-contrast" title="High contrast layout">High contrast</a></li>';
  $('#view-opts').prepend(optText, optTextLarge, optTextXtra, optContrast, optContrastHigh);
  
  //text options
  $('#opt-text a').click(function(e) {
    e.preventDefault();
    setBodyFontSize('75%');
  });
  $('#opt-text-large a').click(function(e) {
    e.preventDefault();
    setBodyFontSize('90%');
  });
  $('#opt-text-xtra a').click(function(e) {
    e.preventDefault();
    setBodyFontSize('105%');
  });
  $('#opt-contrast a').click(function(e) {
    e.preventDefault();
    createCookie('highcontrast', "", -1);
    window.location.reload()
  });
  $('#opt-contrast-high a').click(function(e) {
      e.preventDefault();
        createCookie('highcontrast', 'true', 45);
        window.location.reload()
  });
  
  /**
   * jQuery Audio Shim
   */
  var audio = $('<audio />', {
    controls : 'controls',
    style: 'width:300px;'
  });
  
  addSource(audio, 'http://jeffrey-way.s3.amazonaws.com/zelda.ogg');
  addSource(audio, 'http://jeffrey-way.s3.amazonaws.com/zelda.mp3');
  
  audio.prependTo('#audio-transcript');
  
  
  function addSource(elem, path) {
    $('<source />').attr('src', path).appendTo(elem);
  };

  
  /**
   * Header Slideshow
   */
  // Backwards navigation
	$("#back").click(function() {
		stopAnimation();
		navigate("back");
	});
	
	// Forward navigation
	$("#next").click(function() {
		stopAnimation();
		navigate("next");
	});
	
	var interval;
	$("#control").toggle(function(){
		stopAnimation();
	}, function() {
		// Change the background image to "pause"
		$(this).css({ "background-image" : "url(images/btn_pause.png)" });
		
		// Show the next image
		navigate("next");
		
		// Start playing the animation
		interval = setInterval(function() {
			navigate("next");
		}, slideshowSpeed);
	});
	
	
	var activeContainer = 1;	
	var currentImg = 0;
	var animating = false;
	var navigate = function(direction) {
		// Check if no animation is running. If it is, prevent the action
		if(animating) {
			return;
		}
		
		// Check which current image we need to show
		if(direction == "next") {
			currentImg++;
			if(currentImg == photos.length + 1) {
				currentImg = 1;
			}
		} else {
			currentImg--;
			if(currentImg == 0) {
				currentImg = photos.length;
			}
		}
		
		// Check which container we need to use
		var currentContainer = activeContainer;
		if(activeContainer == 1) {
			activeContainer = 2;
		} else {
			activeContainer = 1;
		}
		
		showImage(photos[currentImg - 1], currentContainer, activeContainer);
		
	};
	
	var currentZindex = -1;
	var showImage = function(photoObject, currentContainer, activeContainer) {
		animating = true;
		
		// Make sure the new container is always on the background
		currentZindex--;
		
		// Set the background image of the new active container
		$("#top" + activeContainer).css({
			"background-color" : "#ffffff",
			"background-image" : "url(/assets/img/temp/" + photoObject.image + ")",
			"display" : "block",
			"z-index" : currentZindex
		});
		
		// Hide the header text
		$("#headertxt").css({"display" : "none"});
		
		// Set the new header text
		$("#firstline").html(photoObject.firstline);
		$("#secondline")
			.attr("href", photoObject.url)
			.html(photoObject.secondline);
		$("#pictureduri")
			.attr("href", photoObject.url)
			.html(photoObject.title);
		
		
		// Fade out the current container
		// and display the header text when animation is complete
		$("#top" + currentContainer).fadeOut(function() {
			setTimeout(function() {
				$("#headertxt").css({"display" : "block"});
				animating = false;
			}, 500);
		});
	};
	
	var stopAnimation = function() {
		// Change the background image to "play"
		$("#control").css({ "background-image" : "url(images/btn_play.png)" });
		
		// Clear the interval
		clearInterval(interval);
	};
	
	// We should statically set the first image
	navigate("next");
	
	// Start playing the animation
	interval = setInterval(function() {
		navigate("next");
	}, slideshowSpeed);
});

