var channels = [];
var masonry_container;
var is_home = false;
var page = 1;

function init_site(){
	init_more();
	init_channels();
	init_sticky_share();
	init_search();
	if( $('.posts').length > 0 ){
		init_masonry();
		init_load_more();
	}

	$(document).on("click", "a[href='#search']", function(e) {
		e.preventDefault();
		$('.search_form').slideToggle(150);
		$(this).toggleClass('open');
		$('html,body').animate({scrollTop:0},500);
		$(".search_form input").focus();
	});

	$(document).on("click", ".dismiss", function(e) {
		e.preventDefault();
		$(".hero_popover_wrapper").removeClass("active");
	});

	if ($(".hero_popover_wrapper").hasClass("active")) {
		window.setTimeout(function(){
			$(".hero_popover_wrapper").removeClass("active");
		}, 30000);
	}

	$(document).on("click", ".sigil", function(e) {
		e.preventDefault();
		var latest_offset = $(".latest").offset();
		$('html,body').animate({scrollTop: (latest_offset.top-10) },500);
	});

	$(document).on("click", ".tweet", function(e) {
		var targ;
		if (!e) var e = window.event;
		if (e.target) targ = e.target;
		else if (e.srcElement) targ = e.srcElement;
		if ($(targ).is("a")) {
			//do nothing
		} else {
			e.preventDefault();
			newTab($(this).data("tweet-link"));
		}
		
	});

	//Adds text to the bottom of the donation page forms
	console.log($('.page-id-216309 .the_post#post-216309 .donation_form'));
	$('.page-id-216309 .the_post#post-216309 .donation_form').append('<p style="margin-top: 40px">Your gift will be used exclusively for the charitable purposes of LIFE Outreach International. Gifts are considered to be without restriction unless explicitly stipulated by the donor. If funds exceed the specific need of a project, or due to unforeseen circumstances the project cannot be completed, they will be used for similar purposes or other outreaches of LIFE such as LIFE Centers, Mission Feeding, LIFE TODAY television and Water for LIFE. LIFE Outreach International is a longtime member of the Evangelical Council for Financial Accountability (ECFA).</p>');

	$('.cat-item-7').after('<li class="cat-item cat-item-podcast"><a href="https://stream.org/podcast/">Podcasts</a></li>');

	$("img.has_credit").each(function() {
		$(this).wrap('<div class="image_with_credit"></div>');
		$(this).after("<span class='image_credit'>"+$(this).data("credit")+"</span>");
	});

	$(".more #subscribe .button.subscribe_submit").on("click", function(e) {
		e.preventDefault();
		var data = $(".more form#subscribe").serialize();
		console.log($(".more form#subscribe #email").val());
		if ($(".more form#subscribe #email").val() != "Email Address") {
			$.ajax({
				url: $(".more form#subscribe").attr("action"),
				data: data,
				type: "POST",
				// code to run if the request succeeds;
				// the response is passed to the function
				success: function( data ) {
					if (data == "valid") {
						$(".more .subscribe_message").removeClass("error").addClass("success").html('Thanks for subscribing!');
					} else if (data == "invalid"){
						$(".more .subscribe_message").removeClass("success").addClass("error").html('To help prevent this form from getting abused, it expires after an extended amount of time spent on the same page. Please refresh the page and try again. If you are still experiencing issues, please let us know.');
					} else if (data == "unable") {
						$(".more .subscribe_message").removeClass("success").addClass("error").html('Unable to complete your subscription. Please make sure you have entered a valid email address');
					} else if (data == "already") {
						$(".more .subscribe_message").removeClass("success").addClass("error").html('This email address has already been subscribed to The Stream.');
					}
				},
				// code to run if the request fails; the raw request and
				// status codes are passed to the function
				error: function( xhr, status, errorThrown ) {
					console.log( "Error: " + errorThrown );
					console.log( "Status: " + status );
					console.dir( xhr );
				},
				// code to run regardless of success or failure
				complete: function( xhr, status ) {
				
				}
			});
		} else {
			alert("Enter a valid email address.");
		}
	});

	$(document).on("click", ".giving_method_tabs a:not(.active)", function(a) {
        var b = this;
        a.preventDefault(),
        $(".giving_method_tabs a.active").removeClass("active"),
        $(b).toggleClass("active").queue(function() {
            $(".giving_method.active").removeClass("active"),
            $(".giving_method." + $(b).data("toggle-div")).toggleClass("active"),
            $("input#payment-method").val($(b).data("toggle-div")),
            $(this).dequeue()
        })
	});
	
    $(document).on("click", ".giving_method_tabs a.active", function(a) {
        a.preventDefault()
    });

	$("#subscribe a.subscribe_submit").on("click", function(e) {
		e.preventDefault();
		var data = $("form#subscribe").serialize();
		if ($("form#subscribe #email").val() !== "") {
			$.ajax({
				url: $("form#subscribe").attr("action"),
				data: data,
				type: "POST",
				// code to run if the request succeeds;
				// the response is passed to the function
				success: function( data ) {
					if (data == "valid") {
						$(".subscribe_message").removeClass("error").addClass("success").html('Thanks for subscribing!');
					} else if (data == "invalid"){
						$(".subscribe_message").removeClass("success").addClass("error").html('To help prevent this form from getting abused, it expires after an extended amount of time spent on the same page. Please refresh the page and try again. If you are still experiencing issues, please let us know.');
					} else if (data == "unable") {
						$(".subscribe_message").removeClass("success").addClass("error").html('Unable to complete your subscription. Please make sure you have entered a valid email address');
					} else if (data == "already") {
						$(".subscribe_message").removeClass("success").addClass("error").html('This email address has already been subscribed to The Stream.');
					}
				},
				// code to run if the request fails; the raw request and
				// status codes are passed to the function
				error: function( xhr, status, errorThrown ) {
					console.log( "Error: " + errorThrown );
					console.log( "Status: " + status );
					console.dir( xhr );
				},
				// code to run regardless of success or failure
				complete: function( xhr, status ) {
				
				}
			});
		} else {
			alert("Enter a valid email address.");
		}
	});

	$("#subscribe .subscribe_submit").on("click", function(e) {
		e.preventDefault();
		var data = $("form#subscribe").serialize();
		if ($("form#subscribe #email").val() !== "") {
			$.ajax({
				url: $("form#subscribe").attr("action"),
				data: data,
				type: "POST",
				// code to run if the request succeeds;
				// the response is passed to the function
				success: function( data ) {
					if (data == "valid") {
						$(".subscribe_message").removeClass("error").addClass("success").html('Thanks for subscribing!');
					} else if (data == "invalid"){
						$(".subscribe_message").removeClass("success").addClass("error").html('To help prevent this form from getting abused, it expires after an extended amount of time spent on the same page. Please refresh the page and try again. If you are still experiencing issues, please let us know.');
					} else if (data == "unable") {
						$(".subscribe_message").removeClass("success").addClass("error").html('Unable to complete your subscription. Please make sure you have entered a valid email address');
					} else if (data == "already") {
						$(".subscribe_message").removeClass("success").addClass("error").html('This email address has already been subscribed to The Stream.');
					}
				},
				// code to run if the request fails; the raw request and
				// status codes are passed to the function
				error: function( xhr, status, errorThrown ) {
					console.log( "Error: " + errorThrown );
					console.log( "Status: " + status );
					console.dir( xhr );
				},
				// code to run regardless of success or failure
				complete: function( xhr, status ) {
				
				}
			});
		} else {
			alert("Enter a valid email address.");
		}
	});
	
	//billing same as mailing functionality 
	$(document).on("click", ".sameas", function(e) {
		var context = this;
		e.preventDefault();
		$(context).toggleClass("active").queue(function() {
			if ($(context).hasClass("active")) {
				//duplicate fields
				$("#mailing_address input").each(function() {
					$("#billing_address input#billing_"+$(this).attr("id")).val($(this).val());
				});
			} else {
				$("#billing_address input").each(function() {
					$(this).val("");
				});
			}
			$( this ).dequeue();
		});
	});

	$(document).on("click", ".recurring-check", function(a) {
        var b = this;
        a.preventDefault(),
        $(b).toggleClass("active").queue(function() {
            $(b).hasClass("active") ? $(".element.recurringInterval").addClass("active") : ($(".element.recurringInterval").removeClass("active"),
            $(".recurring-schedule").removeClass("active")),
            $(this).dequeue()
        })
	});
	
    $(document).on("change", "#recurringInterval", function() {
        var a = ($("option:selected", this),
        this.value);
        $(".recurring-schedule").removeClass("active"),
        $(".recurring-schedule[data-recurringInterval='" + a + "']").addClass("active")
    });
    
	//if they start typing in one field, uncheck the box so that it can be reset.
	$("#billing_address input").on("keydown", function(e) {
		$(".sameas").removeClass("active");
	});


	$(document).on("click", ".comments_toggle", function(e) {
		e.preventDefault();
		$(".comments_area, .comments_toggle").toggleClass("active");
	});

	$(".wp-caption.aligncenter").before("<span class='clear'></span>").after("<span class='clear'></span>");

	moveAuthorBox();

	$(window).resize(function(){
		moveAuthorBox();
	});

	if( $('body').hasClass('home') ){
		init_load_more_voices();
	}
}

function moveAuthorBox() {
	//insert author box. 
	var inserted = false;
	var desired_offset = 310;
	if ($(".featured_image").length > 0) {
		desired_offset = parseInt($(".featured_image").height(),10) + 300;
	}
	if ($(".the_post .content p:first-child span[class^='embed-']").length > 0) {
		desired_offset = parseInt($(".the_post .content p:first-child span[class^='embed-']").outerHeight(),10) + 310;
	}
	/*$(".the_post .content .the_author").attr("offset", desired_offset);
	$(".the_post .content p").not(".wp-caption-text").not("blockquote p").each(function(e) {
		var offset = $(this).position();
		$(this).attr("offset", offset.top);
		if (inserted === false & offset.top > desired_offset) {
			inserted = true;
			$(this).before($(".the_post .content .the_author"));
		}
	});*/
	$(".the_post .content p").not(":has(span.embed-youtube)").not(":has(span.embed-vimeo)").not('.wp-caption-text').not("blockquote p").each(function(e) {
		if (inserted === false) {
			inserted = true;
			$(this).before($(".the_post .content .the_author"));
		}
	});
	//.before($(".the_post .content .the_author"));
	$(".the_post .content .the_author").addClass("positioned");
}

function newTab(url) {
     form = document.createElement("form");
     form.method = "GET";
     form.action = url;
     form.target = "_blank";
     document.body.appendChild(form);
     form.submit();
}

function init_home(){
	is_home = true;
	//init_toggle_post_views();
	if( $(window).width() > 959 ){
		$('.voices').imagesLoaded(function(){
			$('.page_wrap').attr('style','min-height:'+($('.voices').height()+60)+'px');
		});
	}
	if( $(window).width() < 768 ) {
			$( ".insp_sidebar" ).prependTo( $( ".insp_position768" ) );
	} else if( $(window).width() < 1280 ) {
		$( ".insp_sidebar" ).prependTo( $( ".insp_position1280" ) );
	} else {
		$( ".insp_sidebar" ).prependTo( $( ".insp_position" ) );
	}
	$(window).resize(function(){
		if( $(window).width() > 959 ){
			$('.page_wrap').attr('style','min-height:'+($('.voices').height()+60)+'px');
		}

		if( $(window).width() < 768 ) {
			$( ".insp_sidebar" ).prependTo( $( ".insp_position768" ) );
		} else if( $(window).width() < 1280 ) {
			$( ".insp_sidebar" ).prependTo( $( ".insp_position1280" ) );
		} else {
			$( ".insp_sidebar" ).prependTo( $( ".insp_position" ) );
		}
	});
}

function init_more(){
	$('a.more').click(function(){
		if( $(window).width() > 959 ){
		} else {
			if( !$('html').hasClass('move') ){
				$('html').addClass('move');
				$('.page_wrap').bind('click',function(event){
					$('html').removeClass('move');
					$('.page_wrap').unbind('click');
					return false;
				});
				return false;
			} else {
				$('html').removeClass('move');
				$('.page_wrap').unbind('click');
				return false;
			}
		}
	});

	function close_menu(){
		$('.mega_menus').slideToggle(300).delay(100).queue(function() {
			$('.mega_menus').attr("style", "");
			$( this ).dequeue();
		});
		setTimeout(function(){
			$('.mega_menus').attr('class','mega_menus');
			$('.category-content').hide();
		}, 300);
		$('nav a').removeClass('open');
		$.ajax({
			type: 'POST',
			url: '/wp-content/themes/TheStreamBuzz/includes/category_menu.php',
			success: function( html ){
				$('.mega_menus .category').html(html);
			}
		});
	}

	function open_menu(name, link, category){
		$('.mega_menus').toggleClass(name).slideToggle(300);

		$('.search_form').slideUp(150);
		$(".search_toggle").removeClass('open');
		$('.channels').removeClass('open');
		$(".channel_settings").removeClass('open');
		if ($(".mega_menus_cat").hasClass("more_cat")) {
			close_all_mega_menus_cat();
		}
		$(link).toggleClass('open');
		if( category > 0 ){
			$.ajax({
				type: 'POST',
				url: '/wp-content/themes/TheStreamBuzz/includes/category_menu.php',
				data: { 'category': category },
				success: function( html ){
					$('.mega_menus .loading').fadeOut(300);
					setTimeout(function(){
						$(html).imagesLoaded(function(){
							$('.mega_menus .category .category-content').html(html).slideDown(300).css('opacity',1);
						});
					}, 300);
				}
			});
		}
	}

	function toggle_menu(name, link, category){
		if( $('.mega_menus').hasClass(name) ){
			close_menu();
		} else if( $('.mega_menus').is(':visible') ){
			close_menu();
			setTimeout(function(){
				open_menu(name, link, category);
			}, 300);
		} else {
			open_menu(name, link, category);
		}
	}

	/*$('nav .cat-item').click(function(){
		var item = $(this).attr('class').replace('cat-item-','').replace('cat-item ','');
		toggle_menu('cat-'+item, $(this).children('a'), item);
		return false;
	});*/

	$('li.more a').click(function(){
		toggle_menu('more', $(this), 0);
		return false;
	});

	$('.mega_menus .close').click(function(){
		$('html').removeClass('move');
		$('.page_wrap').unbind('click');
		return false;
	});

	$('.company_more, .voices_link').click(function(){
		if( $(window).width() < 960 ){
			$(this).next().slideToggle(300, function() {
				if ($(this).is(":visible")) {
					console.log("test");
				} else {
					$(this).delay(100).queue(function() {
						$(this).attr("style", "");
						$( this ).dequeue();
					});
				}
			});
			$(this).children('.icon-plus').toggleClass('open');
		}
		return false;
	});
}

function init_load_more(){
	$('.load_more').click(function(){
		page++;
		var load_more = $(this);
		load_more.html('Loading...').addClass('loading').unbind();
		var is_buzzing = false;
		if ($("#is_buzzing").length > 0 && $("#is_buzzing").val() == 1) {
			is_buzzing = true;
		}
		$.ajax({
			type: 'POST',
			url: '/wp-content/themes/TheStreamBuzz/includes/main_query.php',
			data: { 'category': $.cookie('CHANNELS'), 'page': page, 'is_home': is_home, 'is_buzzing': is_buzzing },
			success: function( html ){
				if( html.length > 0 ){
					var el = $(html);
					load_more.fadeOut().remove();
					$('.posts').append(el).masonry( 'appended', el, true );
					if( is_home ){
						$('.posts .load_more').appendTo('.main');
					} else {
						$('.posts .load_more').appendTo('.page');
					}
				}
				titleex_run_experiment();
				masonryUpdate();
				init_load_more();
			}
		});
		return false;
	});
}
var voices_page = 1;
function init_load_more_voices(){
	if( !$('.more_voices').hasClass('stop_loading') ){
		$('.more_voices').click(function(){
			voices_page++;
			var load_more = $(this);
			load_more.html('Loading...').addClass('loading').unbind();
			$.ajax({
				type: 'POST',
				url: '/wp-content/themes/TheStreamBuzz/includes/voices_query.php',
				data: { 'page': voices_page },
				success: function( html ){
					if( html.length > 0 ){
						load_more.fadeOut().remove();
						$('.voices .list').append(html);

						if ($(".page_wrap .grid").height() < $('.voices').height()) {
							$(".page_wrap .grid").css("min-height", parseInt($('.voices').height(), 10)+parseInt(100, 10)+"px");
						}
					}
					if( !$('.more_voices').hasClass('stop_loading') ){
						init_load_more_voices();
					}
				}
			});
			return false;
		});
	}
}

function init_channels(){
	$('.channels .selected').each(function(){
		var channel = $(this).children('.channel').attr('data-channel');
		channels.push(channel);
	});
	$('.channels').attr('style','margin-top: -'+(parseInt($('.channels').height(), 10)+140)+'px;');
	$(window).resize(function(){
		$('.channels').attr('style','margin-top: -'+(parseInt($('.channels').height(), 10)+140)+'px;');
	});
	$('.channel_settings').click(function(){
		if( !$('.channels').hasClass('open') ){
			if ($(".mega_menus").hasClass("more")) {
				close_all_mega_menus();
			}
			$('.search_form').slideUp(150);
			$(".search_toggle").removeClass('open');
			$('.channels').addClass('open');
			$('.channel_settings').addClass("open");
			$('html').bind('click',function(event){
				if($(event.target).index('.channels *') == -1) {
					$('.channels').removeClass('open');
					$('.channel_settings').removeClass('open');
					$('html').unbind('click');
				}
			});
			return false;
		}
	});
	$('.channels .channel').click(function(){
		var channel = $(this).attr('data-channel');
		var li = $('.channels #channel_'+channel);
		li.toggleClass('selected');
		if( li.hasClass('selected') ){
			channels.push(channel);
		} else {
			channels.splice( $.inArray(channel, channels), 1);
		}
		return false;
	});

	$('.channels .save_channels').click(function(){
		$.cookie('CHANNELS', channels, { expires: 30 });
		$('.channels').removeClass('open');
		$(".channel_settings").removeClass('open');
		$('html').unbind('click');
		if( is_home ){
			if( !$('.tabs .latest').hasClass('active') ){
				$('.main,.buzzing').toggle();
				$('.tabs a').toggleClass('active');
			}
			page = 1;
			$.ajax({
				type: 'POST',
				url: '/wp-content/themes/TheStreamBuzz/includes/main_query.php',
				data: { 'category': $.cookie('CHANNELS'), 'page': 1 },
				success: function( html ){
					if( html.length > 0 ){
						var el = $(html);
						$('.main .load_more').remove();
						var main_items = $('.main .posts').masonry('getItemElements');
						$('.main .posts').masonry('remove', main_items);
						$('.main .posts').append(el).masonry( 'addItems', el, true );
						$('.main .posts .load_more').appendTo('.main');
						setTimeout(function(){
							$('.posts').masonry();
						}, 50);
					}
					init_load_more();
				}
			});
		}
		return false;
	});
}

function init_masonry(){
	if( $('.post').length > 0 ){
		masonry_container = $('.masonry');
		masonry_container.imagesLoaded(function(){
			masonry_container.masonry({
				itemSelector: '.post',
				columnWidth: '.grid-sizer'
			});
		});
	}
}

function init_toggle_post_views(){
	// Toggles between "Latest" and "Buzzing" posts.
	// $('.tabs a').click(function(){
	// 	if( !$(this).hasClass('active') ){
	// 		$('.main,.buzzing').toggle();
	// 		$('.tabs a').toggleClass('active');
	// 	}
	// 	masonry_container.masonry();
	// 	return false;
	// });
}

function init_sticky_share(){
	var object = $('.content');
	if( $('.featured_image').length > 0 ){
		object = $('.featured_image');
	}

	$(object).waypoint(function(){
		$('.sticky_share, .back_to_top').toggleClass('show');
		$('.navigation').toggleClass('sticky_logo');
	});

	var topoffset = 50;
	if ($('.hero_popover_wrapper').is(":visible")) {
		topoffset = 300;
		console.log(topoffset);
	}
	$($(".page_wrap")).waypoint(function(){
		$('.navigation').toggleClass('sticky_logo');
	}, { offset: topoffset });

	$('.subfooter').waypoint({
		offset: '91%',
		handler: function(){
			$('.back_to_top').toggleClass('unfixed');
		}
	});

	$('.back_to_top').click(function(){
		$('html,body').animate({scrollTop:0},500);
		return false;
	});
}

function init_search(){
	$('.search_submit').click(function(){
		if( $(this).parents('form').parents('.tab-links').length > 0 ){
			var input = $('.tab-links input');
			if( input.hasClass('open') && input.val() !== '' && input.val() != 'Search' ){
				$(this).parents('form').submit();
			} else {
				input.toggleClass('open');
			}
		} else {
			$(this).parents('form').submit();
		}
		return false;
	});
	$(document).on("click", '.search_toggle', function(){
		$('.search_form').slideToggle(150);
		if ($(".mega_menus").hasClass("more")) {
			close_all_mega_menus();
		}
		$('.channels').removeClass('open');
		$(".channel_settings").removeClass('open');
		$(this).toggleClass('open');
		return false;
	});
}

function multiline_text_overflow(elem) {
	$(elem).each(function(i){
		$(this).text($(this).data("originalText"));
		$(this).data("originalText", $(this).text()).wrapInner("<span class='mlto'></span>");
		var p=$(this).find(".mlto");
		var divh = $(this).height();
		while($(p).outerHeight()>divh) {
			$(p).text(function (index, text) {
				return text.replace(/\W*\s(\S)*$/, '...');
			});
		}
	});
}

function close_all_mega_menus(){
	$('.mega_menus').slideToggle(300);
	setTimeout(function(){
		$('.mega_menus').attr('class','mega_menus');
		$('.category-content').hide();
	}, 300);
	$('nav a').removeClass('open');
	$.ajax({
		type: 'POST',
		url: '/wp-content/themes/TheStreamBuzz/includes/category_menu.php',
		success: function( html ){
			$('.mega_menus .category').html(html);
		}
	});
}

/*function ClickOutsideCheckMore(e)
{
  var el = e.target;
  var popup = $('.mega_menus.more:visible')[0];
  if(popup==undefined) return true;

  while (true){
    if (el == popup ) {
      return true;
    } else if (el == document) {
      close_all_mega_menus();
      return false;
    } else {
      el = $(el).parent()[0];
    }
  }
};

$(document).bind('mousedown.popup', ClickOutsideCheckMore);

function ClickOutsideCheckChannels(e)
{
  var el = e.target;
  var popup = $('.channels:visible')[0];
  if(popup==undefined) return true;

  while (true){
    if (el == popup ) {
      return true;
    } else if (el == document) {
      $("ul.channels").removeClass("open");
      return false;
    } else {
      el = $(el).parent()[0];
    }
  }
};

$(document).bind('mousedown.popup', ClickOutsideCheckChannels);*/