/*
	handles all javascript/ajax/jquery to process blog related requests
*/

//default call for Blog nav item
function goToBlog(){
	$('#menu a').each(function(){
		$(this).removeClass('selected');
	});
	$('#BlogNav').addClass('selected');
	getBlogPage("", "prev");
	printTags('blog');
	decorateTag();
}

//load a blog post page of set number of posts. Either specify blog ID value, or don't to get recent posts.
function getBlogPage(pId, dir){
	$('#PostContent').html("<p>Loading...</p>");
	$.ajax({
			type: "GET",
			url: "loadPostPageJson.php",
			dataType:"json",
			data:"id=" + pId + "&direction=" + dir,
			success:function(data){
				$('#PostContent').html("");
				for(i=0; i < data.blogs.length; i++){
					printBlog(data.blogs[i]);
				}
				printTags('blog');
				printBlogFooter(data.first_id, data.last_id, data.first_page, data.last_page);
				$('#PostContent .post img').onImagesLoad({itemCallback: applyImageFormatting});
			},
			error:function (xhr, ajaxOptions, thrownError){
				$('#PostContent').val("ERROR: " + xhr.status + "\n\nDetails:\n" + thrownError);
			}    
		});
}

function getBlogById(pId){
	$('#PostContent').html("<p>Loading blog entry #" + pId + "...</p>");
	$.ajax({
			type: "GET",
			url: "loadPostJson.php",
			dataType:"json",
			data:"id=" + pId,
			success:function(data){
				$('#PostContent').html("");
				printBlog(data);
				printTags('blog');
				$('#PostContent .post img').onImagesLoad({itemCallback: applyImageFormatting});
			},
			error:function (xhr, ajaxOptions, thrownError){
				alert('fail');
				$('#PostContent').val("ERROR: " + xhr.status + "\n\nDetails:\n" + thrownError);
			}    
		});
}

//load a single page of all posts tagged by specified tag ID value.
function getBlogsByTag(tId){
	$('#PostContent').html("<p>Loading...</p>");
	$.ajax({
			type: "GET",
			url: "loadPostsByTagJson.php",
			dataType:"json",
			data:"id=" + tId,
			success:function(data){
				$('#PostContent').html("");
				for(i=0; i < data.blogs.length; i++){
					printBlog(data.blogs[i]);
				}
				printTags('blog');
				decorateTag(tId);
				printTagFooter(data.first_id, data.last_id, data.first_page, data.last_page);
				$('#PostContent .post img').onImagesLoad({itemCallback: applyImageFormatting});
			},
			error:function (xhr, ajaxOptions, thrownError){
				$('#PostContent').val("ERROR: " + xhr.status + "\n\nDetails:\n" + thrownError);
			}    
		});		
}

//print single blog post entry.
function printBlog(blog){
	var tags = "<div class='tags'>Filed under:<br />";
	//populate blog list selections
	if(blog.tags.length == 1){
		tags += "<a href='javascript: getBlogsByTag(" + blog.tags[0].tag_id + ");'>" + blog.tags[0].tag_name + "</a>";
	}else{
		for(j = 0; j < blog.tags.length; j ++){
			tags += (j < blog.tags.length -1 ? ("<a href='javascript: getBlogsByTag(" + blog.tags[j].tag_id + ");'>" + blog.tags[j].tag_name + "</a>, ") : ("and <a href='javascript:getPostsByTag(" + blog.tags[j].tag_id + ");'>" + blog.tags[j].tag_name + "</a>"));
		}
	}
	tags += "</div>";
	$('#PostContent').append("<div class='post'><h1><a href='./index.php?b="+blog.blog_id+"'>"+blog.create_dt+"</a></h1>\n"+blog.blog.replace(/-amp-/g, "&")+"\n"+tags+"</div>");
}

//print footer, including page navigation if required.
function printBlogFooter(lastId, firstId, isFirstPage, isLastPage){
	$("#PostNav").html("");
	if(isLastPage != "true")
		$("#PostNav").append("<div class='nav'><a href=\"javascript: getBlogPage(" + firstId + ", 'prev');\">Older</a></div>");
	else
		$("#PostNav").append("<div class='nav_disabled'>Older</div>");
	if(isFirstPage != "true")
		$("#PostNav").append("<div class='nav'><a href=\"javascript: getBlogPage(" + lastId + ", 'next');\">Newer</a></div>");
	else
		$("#PostNav").append("<div class='nav_disabled'>Newer</div>");
}

//print footer for tag page
function printTagFooter(lastId, firstId, isFirstPage, isLastPage){
	$("#PostNav").html("");
}

//images may need to be resized, and have click handler attached, if their size exceeds the post div width.
function applyImageFormatting(img)
{
	if(img.width > 600)
	{
		$(this).attr("width", "600");
		$(this).attr("onClick", "window.open('" + img.src + "','blogImg');");
		$(this).addClass("clickable");
	}
}

//if a tag has been selected then it may be decorated to indicate its selection.
function decorateTag(tId){
	$("a[id*='tag_']").each(function(){
		$(this).removeClass("selected");
		if($(this).attr('id') == 'tag_'+tId){
			$(this).addClass("selected");
		}
	});
}

//	----------------------------	Admin functions

function SaveBlog(JSONObject){
	var tagCount = 0;
	var entryForm = document.forms[0]; 
	$('#BlogTagList :selected').each(function(){
		JSONObject.tags[tagCount] = new Object;
		JSONObject.tags[tagCount].tagId = $(this).val();
		tagCount++;
	});
	JSONstring = JSON.stringify(JSONObject);
	$.ajax({
		type: "POST",
		url: "/savePostJson.php",
		dataType:"json",
		data:"entryJson=" + JSONstring,
		success:function(data){
				if(data.error){
					Message("An error has occurred...");
					$('#EntryText').val("Error:\n[\n" + data.message + "\n]");
				}else{
					Message("Your post has been saved");
					$('#SaveEntry').removeAttr("disabled");
					if(entryForm['IsNew'].checked){
						location.reload();
					}
				}
			},
		error: function(xhr, ajaxOptions, thrownError){
			Message("An error has occurred...");
			$('#EntryID').val("");
			$('#EntryDate').val("");
			$('#EntryText').val("ERROR: " + xhr.status + "\n\nDetails:\n" + thrownError);
			$('#BlogTagList option').each(function(){
				$(this).removeAttr("selected");
			});
		}
	});
}


function LoadBlog(pId){
	if(pId != ""){
		//if a post has been specified, load that post
		$.ajax({
			type: "GET",
			url: "/loadPostJson.php",
			dataType:"json",
			data:"id=" + pId,
			success:function(data){
				//populate blog fields
				$('#EntryID').val(data.blog_id);
				$('#EntryDate').val(data.create_dt);
				//replace '-amp-' with '&'
				$('#EntryText').val(data.blog.replace(/-amp-/g, "&"));
				
				$('#SaveEntry').removeAttr("disabled");

				//populate blog list selections
				$('#BlogTagList option').each(function(){
					$(this).removeAttr("selected");
					for(i = 0; i < data.tags.length; i ++){
						if($(this).val() == data.tags[i].tag_id){
							$(this).attr("selected", "true");
							return;
						}
					}
				});
			},
			error: function(xhr, ajaxOptions, thrownError){
				$('#EntryID').val("");
				$('#EntryDate').val("");
				$('#EntryText').val("ERROR: " + xhr.status + "\n\nDetails:\n" + thrownError);
				$('#BlogTagList option').each(function(){
					$(this).removeAttr("selected");
				});
			}
		});
	}
}
