//The main blog functions
$(document).on("click", "#blogSearch", function(e){
	var theText = $(this).parents("#searchContain").children("input").val();
	
	if(theText != ""){
		$(this).parents("#searchContain").children("input").removeClass("error");
		document.location.href = "/" + beginURL + "/search/" + theText;
		//searchTheBlog(theText);
	}else{
		$(this).parents("#searchContain").children("input").addClass("error").val("Please enter a search term");
	}
});

$(document).on("focus", "#searchContain input", function(){
	var theText = $(this).val();
	
	if(theText == "Please enter a search term"){
		$(this).val("");
	}
});
	  
$(document).on("keypress", "#searchContain input", function(e){
	if(e.which == 13){
		var theText = $(this).parents("#searchContain").children("input").val();
	  
		if(theText != ""){
			$(this).parents("#searchContain").children("input").removeClass("error");
			document.location.href = "/" + beginURL + "/search/" + theText;
			//searchTheBlog(theText);
		}else{
			$(this).parents("#searchContain").children("input").addClass("error").val("Please enter a search term");
		}
	}
});

function getCategoryID(slug, thePage, listType, searchTerm, numWanted, urlStart, childrenCategories){
	if(childrenCategories === undefined) {
        childrenCategories = false;
    }
	
	categoryID = false;
	
	$.ajax({
		type: "GET",
		url: "//blog.afsshareportal.com/wp-json/wp/v2/categories?slug=" + slug,
		data: "",
		async: false,
		dataType: "json",
		success: function(theCategory){
			allCategories = theCategory[0].id;
			
			if (childrenCategories !== false) {
				$.ajax({
					type: "GET",
					url: "//blog.afsshareportal.com/wp-json/wp/v2/categories?parent=" + theCategory[0].id,
					data: "",
					async: false,
					dataType: "json",
					success: function(theCategories){
						
						$.each(theCategories, function(index, category){
							allCategories += "," + category.id;
						});
						
					}
				});
			}
			
			if (theCategory.length) {
				if (listType == "search") {
					searchTheBlog(allCategories, searchTerm, numWanted, urlStart);
				}else if (listType == "home") {
					getBlogPostsHomePage(allCategories, urlStart);
				}else{
					$.ajax({
						type: "GET",
						url: "//blog.afsshareportal.com/wp-json/wp/v2/categories?include=" + allCategories,
						data: "",
						async: false,
						dataType: "json",
						success: function(theCategories){
							totalCount = 0;
							
							$.each(theCategories, function(index, category){
								totalCount += parseInt(category.count);
							});
							
							setBlogNav(totalCount, thePage, "blog", urlStart);
						}
					});
					
					getAllPosts(allCategories, numWanted, thePage, urlStart);
				}
			}else {
				theHTML = "<p>There are no blog posts.</p>";
				$("#allBlogPosts").html(theHTML);
			}
		}
	});
}

function searchTheBlog(categoryID, searchTerm, numWanted, urlStart){
	$.ajax({
		type: "GET",
		url: "//blog.afsshareportal.com/wp-json/wp/v2/posts/?categories=" + categoryID + "&_embed",
		data: "&per_page=" + numWanted + "&page=" + thePage + "&search=" + searchTerm,
		async: false,
		dataType: "json",
		success: function(thePosts, textStatus, request){
			setBlogNav(request.getResponseHeader('X-WP-Total'), thePage, "search", urlStart);
			wpAllPostsCallback(thePosts, urlStart);
		}
	});
}

function getBlogPostsHomePage(categoryID, urlStart){
	$.ajax({
		type: "GET",
		url: "//blog.afsshareportal.com/wp-json/wp/v2/posts/?categories=" + categoryID + "&per_page=4&_embed",
		data: "",
		async: false,
		dataType: "json",
		success: function(thePosts){
			var theHTML = "";
			var theCount = 0;
			var specialClass = "";
			var hasFeature = 0;
			var postsCount = thePosts.length;
			
			$.each(thePosts, function(){
				theCount++;
				
				if((postsCount % 2) != 0){
					if(theCount == 1){
					  sizeClass = "full";
					  hasFeature = 1;
					}else{
					  sizeClass = "half";
					}
				}else{
					sizeClass = "half";
				}
				
				if((theCount % 2) == (0 + hasFeature)){
					specialClass = "right";
				}else{
					specialClass = "left";
				}
				
				
				//Make the blurb standard length
				var blurbLength = 75;
				if(sizeClass == "full"){
					blurbLength = 200;
				}
				
				var noTags = removeFirstTag(this.excerpt.rendered, 0, 1);
				var theBlurb = noTags;
				
				if(noTags.length > blurbLength){
					theBlurb = noTags.substring(0, blurbLength) + "...";
				}
				
				var date = new moment(this.date);
				
				theHTML += "<div class='onePost " + sizeClass + " " + specialClass + " clearfix'>";
				theHTML += "<h4 class='blogTitle'>" + this.title.rendered + "</h4>";
				theHTML += "<h6 class='blogDate'>" + date.format('YYYY-MM-DD h:mm A') + "</h6>";
				if (this._embedded['wp:featuredmedia'] != undefined) {
					theHTML += "<img src='" + this._embedded['wp:featuredmedia']['0'].source_url + "' width='95' class='floatLeftImg' alt='" + this.title.rendered + "'>";
				}
				theHTML += "<p class='blogDescr'>" + theBlurb + "</p>";
				theHTML += "<p class='blogUrl'><a href='/" + urlStart + "/" + this.slug + "' class='btn btn-primary'>Read More</a></p>";
				theHTML += "</div>";
			  
			});
			
			$("#blogPosts").append(theHTML);
		}
	});
}
	
function getAllPosts(categoryID, numWanted, thePage, urlStart){
	$.ajax({
		type: "GET",
		url: "//blog.afsshareportal.com/wp-json/wp/v2/posts/?categories=" + categoryID + "&_embed",
		data: "&per_page=" + numWanted + "&page=" + thePage,
		async: false,
		dataType: "json",
		success: function(thePosts){
			wpAllPostsCallback(thePosts, urlStart);
		}
	});
}

function wpAllPostsCallback(thePosts, urlStart){
	var theHTML = "";
	if(thePosts.length > 0){
		$.each(thePosts, function(){
			var newContent = trimContent(this.content.rendered);
			//var newContent = "";
			//console.log(newContent);
			theHTML += "<div class='onePost clearfix'>";
			if (this._embedded['wp:featuredmedia'] != undefined) {
				theHTML += "<img src='" + this._embedded['wp:featuredmedia']['0'].source_url + "' width='95'>";
			}
			var date = new moment(this.date);
			
			theHTML += "<h2>" + this.title.rendered + "</h2>";
			theHTML += "<h5>" + date.format('YYYY-MM-DD h:mm A') + "</h5>";
			theHTML += "<div style='clear:both'></div>";
			theHTML += newContent;
			theHTML += "<p><a href='/" + urlStart + "/" + this.slug + "' class='btn'>Read More</a></p>";
			//theHTML += "</div>";
			theHTML += "</div>";
		});
	}else{
		theHTML += "<p>There are no blog posts.</p>";
		theHTML += "<p>Please visit the blog <a href='/" + urlStart + "'>home page</a> to see our blog posts.</p>";
	}
	
	$("#allBlogPosts").html(theHTML);
	//console.log(thePosts);
}

function getOnePost(shouldPin, urlStart){
	$.ajax({
		type: "GET",
		url: "//blog.afsshareportal.com/wp-json/wp/v2/posts?slug=" + theName,
		success: function(thePost){
			thePost = thePost[0];
			var theHTML = "";
			
			theHTML += "<h1>";
			
			shouldPin = false;
			if (shouldPin) {
				theHTML += '<span id="pinBtn" class="pull-right"><a data-pin-config="none" href="http://pinterest.com/pin/create/button/?url=this&media=picture&description=recipeName" data-pin-do="buttonPin" target="blank"><img src="//assets.pinterest.com/images/pidgets/pin_it_button.png" /></a></span>';
			}
			
			var date = new moment(thePost.date);
			
			theHTML += thePost.title.rendered + "</h1>";
			theHTML += "<h4>" + date.format('YYYY-MM-DD h:mm A') + "</h4>";
			theHTML += thePost.content.rendered;
			theHTML += "<p style='margin-top:30px;margin-bottom:30px;' class='pull-right'>";
			theHTML += "<a href='/" + urlStart + "' class='btn btn-primary'>Back to Blog Home</a>";
			theHTML += "</p>";
			$("#theBlogPost").append(theHTML);
			
			shouldPin = false;
			if (shouldPin) {
				setTimeout(function(){
					var thePage = window.location.href;
					var theMedia = $("#theBlogPost p img").first().attr("src");
					var thePinText = thePost.title.rendered;
					var pinURL = "http://pinterest.com/pin/create/button/?url=" + encodeURIComponent(thePage) + "&media=" + encodeURIComponent(theMedia) + "&description=" + encodeURIComponent(thePinText);
					$("#pinBtn a").attr("href", pinURL);
				}, 1000);
			}
		}
	});
}
	
function setBlogNav(totalPosts, currentPage, theType, urlStart){
	currentPage = parseInt(currentPage);
	var theHTML = "";
	var theHref = "";
	var prevPage, nextPage, baseHref;
	var maxPages = Math.ceil(totalPosts / numWanted);
	nextPage = currentPage + 1;
	
	theHTML += "<p>";
	
	if(theType == "search"){
		baseHref = "/" + urlStart + "/search/" + theTerm;
	}else{
		baseHref = "/" + urlStart + "/more";
	}
	
	if(currentPage != 1){
		if(currentPage == 2){
			prevPage = "";
		}else{
			prevPage = currentPage - 1;
		}
		theHTML += "<a href='" + baseHref + "/" + prevPage + "'><i class='icon-chevron-left'></i> Newer Posts</a>";
	}
	
	
	if(maxPages > 15){
		if(currentPage <= 3){
			for(var i=1;i<=8;i++){
				var specialClass = i == currentPage ? "currentPage" : "";
				
				if(i == 1){
					theHref = baseHref;
				}else{
					theHref = baseHref + "/" + i;
				}
				theHTML += "<a href='" + theHref + "' class='" + specialClass + "'><span class='navPageNum'>" + i + "</span></a>";
			}
			
			theHTML += "<a href='#'><span class='navPageNum'>. . .</span></a>";
			
			for(var j = (maxPages - 3);j<=maxPages;j++){
			  theHref = baseHref + "/" + j;
			  theHTML += "<a href='" + theHref + "' class='" + specialClass + "'><span class='navPageNum'>" + j + "</span></a>";
			}
		}else if(currentPage > (maxPages - 3)){
			for(var i=1;i<=3;i++){
				if(i == 1){
					theHref = baseHref;
				}else{
					theHref = baseHref + "/" + i;
				}
				theHTML += "<a href='" + theHref + "' class='" + specialClass + "'><span class='navPageNum'>" + i + "</span></a>";
			}
			
			theHTML += "<a href='#'><span class='navPageNum'>. . .</span></a>";
			
			for(var j = (maxPages - 8);j<=maxPages;j++){
				var specialClass = j == currentPage ? "currentPage" : "";
				theHref = baseHref + "/" + j;
				theHTML += "<a href='" + theHref + "' class='" + specialClass + "'><span class='navPageNum'>" + j + "</span></a>";
			}
		}else{
			if(currentPage < 9){
				var firstRun = 8;
				var needFirstEllipses = false;
				var lastRun = 3;
				var needLastEllipses = true;
			}else if(currentPage > (maxPages - 6)){
				var firstRun = 3;
				var needFirstEllipses = true;
				var lastRun = 8;
				var needLastEllipses = false;
			}else{
				var firstRun = 3;
				var needFirstEllipses = true;
				var lastRun = 3;
				var needLastEllipses = true;
			}
			
			for(var i=1;i<=firstRun;i++){
				if(i == 1){
					theHref = baseHref;
				}else{
					theHref = baseHref + "/" + i;
				}
				var specialClass = i == currentPage ? "currentPage" : "";
				theHTML += "<a href='" + theHref + "' class='" + specialClass + "'><span class='navPageNum'>" + i + "</span></a>";
			}
			
			if(needFirstEllipses && needLastEllipses){
				theHTML += "<a href='#'><span class='navPageNum'>. . .</span></a>";
			  
				for(var k = (currentPage-2);k<=(currentPage + 2);k++){
					var specialClass = k == currentPage ? "currentPage" : "";
					theHref = baseHref + "/" + k;
					theHTML += "<a href='" + theHref + "' class='" + specialClass + "'><span class='navPageNum'>" + k + "</span></a>";
				}
			}
		  
			theHTML += "<a href='#'><span class='navPageNum'>. . .</span></a>";
		  
			for(var j = (maxPages - lastRun);j<=maxPages;j++){
				var specialClass = j == currentPage ? "currentPage" : "";
				theHref = baseHref + "/" + j;
				theHTML += "<a href='" + theHref + "' class='" + specialClass + "'><span class='navPageNum'>" + j + "</span></a>";
			}						  
		}
	}else{
		for(var j = 1;j<=maxPages;j++){
			var specialClass = j == currentPage ? "currentPage" : "";
			theHref = baseHref + "/" + j;
			theHTML += "<a href='" + theHref + "' class='" + specialClass + "'><span class='navPageNum'>" + j + "</span></a>";
		}
	}
	
	
	if(currentPage < maxPages){
		theHTML += "<a href='" + baseHref + "/" + nextPage + "'>Older Posts <i class='icon-chevron-right'></i></a>";
	}
	
	theHTML += "</p>";
	
	$("#blogNavigation").html(theHTML);
}







//Helper Functions
function trimContent(theContent){
	var theMax = 500;
	var thePosition = -2;
	var endPositionGT = 0;
	var endPositionSpace = 0;
	var wantedEnd = 0;
	var theTag = "";
	var theReturnContent = noImg(theContent);
	var openTags = [];
	var contentLength = theReturnContent.length;
	
	var i = 0;
	if(contentLength > theMax){
		do{
			thePosition = theReturnContent.indexOf("<", (thePosition + 1));
			endPositionGT = theReturnContent.indexOf(">", thePosition);
			endPositionSpace = theReturnContent.indexOf(" ", thePosition);
			
			wantedEnd = Math.min(endPositionGT, endPositionSpace);
			if(wantedEnd == -1){
				break;
			}
			theTag = theReturnContent.substr(thePosition, ((wantedEnd + 1) - thePosition));
			
			if(theTag.substr(-1) == " "){
				theTag = theTag.replace(" ", ">");
			}
			if(theTag.charAt(1) != "/"){
				if(theTag != "<img>"){
					openTags.push(theTag);
				}
			}else{
				openTags.splice(-1,1);
			}
			
			
			i++;
		}while(wantedEnd < theMax && i < 50);
		
		theReturnContent = theReturnContent.substr(0, (endPositionGT + 1));
		
		openTags.reverse();
		
		$.each(openTags, function(){
			theReturnContent = theReturnContent + this.slice(0,1) + "/" + this.slice(1);
		});
	}
	
	return theReturnContent;
}
  
function noImg(theContent){
	var j = 0;
	var imgArray = [];
	var imgLoc = 0;
	var imgEnd = 0;
	
	do{
		imgLoc = theContent.indexOf("img", imgLoc);
		imgEnd = theContent.indexOf(">", imgLoc);
		
		if(imgLoc < 0 && j == 0){
			return theContent;
		}
		
		imgArray.push([(imgLoc - 1), (imgEnd + 1)]);
		
		imgLoc++;
		j++;
	}while(j < 30);
	
	imgArray.reverse();
	var returnContent = "";
	var theImg = "";
	
	$.each(imgArray, function(){
		theImg = theContent.substr(this[0], (this[1] - this[0]));
		returnContent = theContent.replace(theImg, "");
	});
	
	return returnContent;
}
  
  
function removeLastPP(theContent){
	var components = theContent.split("<p");
	var returnThis = "";
	
	var theLast = components[components.length-1];
	
	if(theLast.indexOf("Read more") < 0){
		returnThis = theContent;
	}else{
		components.pop();
		$.each(components, function(){
			returnThis += "<p" + this;
		});
	}
	
	return returnThis;
}

function removeFirstTag(myContent, startPosition, iteration) {
	var firstTagPos = myContent.indexOf("<", startPosition);
	var firstTagEndPos = myContent.indexOf(">", startPosition + 1);
	
	var myFirstTag = myContent.substring(firstTagPos, firstTagEndPos + 1);
	var myFirstClosingTag = "</" + myFirstTag.substring(1, myFirstTag.length);
	
	var myContentEndPos = myContent.indexOf(myFirstClosingTag, startPosition);
	var myContentTrunc = myContent.substring((firstTagEndPos + 1), myContentEndPos);
	
	
	return myContentTrunc;
}