var dhtmlHistory = null;
var searchResultsPanel;
var searchResults;
var loginForm;
var contactForm;
var lastSearchPhrase;
var inProcess;
var postElementsDeclared;
var modalForm;

var postDisplay_body;
var postDisplay_relatedPosts;
var postDisplay_time;
var postDisplay_date;
var postDisplay_commentCount;
var postDisplay_commentCollection;
var loadingAnimation;
var originalPost = null;
var currentPost = null;
var arrCachedPosts = new Array();

function initializeAjaxHistory()
{
	if(dhtmlHistory == null)
		return;

	dhtmlHistory.initialize();
	dhtmlHistory.addListener(handlePostChange);
}

function handlePostChange(newLocation, postUrl)
{
	if(postUrl != null)
	{
		var p = arrCachedPosts[postUrl];
		if(p != null)
			hydrateCompleteBlogPostDisplay(p);
		else
			loadPost(postUrl);
	}
}

function loadPost(url)
{
	if(inProcess)
		return;
	
	inProcess = true;
	if(originalPost != null)
	{
		if(lastPostMode == "preview")
			cancelEditBlogPostFromPreview();
		else
			cancelEditBlogPostFromForm();
	}
	
	if(typeof(commentFormContainer) != "undefined" && commentFormContainer.style.display != "none")
		hideBlogPostCommentFormComplete();
	
	if(typeof(addedClonedComment) != "undefined" && addedClonedComment != null)
	{
		addedClonedComment.style.display = "none";
	}

	if(loadingAnimation == null)
		loadingAnimation = document.getElementById("loadingAnimation");
	
	lookupPostElements();
	
	if(postDisplay_commentCollection != null)
	{
		loadingAnimation.style.display = "inline";
		Library.setOpacity(loadingAnimation, .8);
		var arrCoords = Library.getCenterObjectOnScreen(loadingAnimation);
		loadingAnimation.style.left = arrCoords[0] + "px";
		loadingAnimation.style.top = arrCoords[1] + "px";
	}
	
	CSharper.Net.ScriptService.GetBlogPostWithCommentsByUrl(url, loadPostCallback);	
}

function loadPostCallback(post)
{
	if(post != null)
	{
		currentPost = post;

		if(dhtmlHistory != null)
		{
			dhtmlHistory.add(currentPost.Post.Url, currentPost.Post.Url);
			arrCachedPosts[currentPost.PostID] = currentPost;
		}
		
		hydrateCompleteBlogPostDisplay(post);
	}
		
	var attributes = { opacity: {to: 0 }  };
	anim = new YAHOO.util.Anim(loadingAnimation, attributes, 1, YAHOO.util.Easing.easeOut);
	anim.duration = .5;
	anim.animate();
	inProcess = false;
}

function lookupPostElements()
{
	if(postElementsDeclared)
		return;
	
	postDisplay_body = document.getElementById("postDisplay_body");
	postDisplay_date = document.getElementById("postDisplay_date");
	postDisplay_time = document.getElementById("postDisplay_time");
	postDisplay_relatedPosts = document.getElementById("postDisplay_relatedPosts");
	postDisplay_commentCount = document.getElementById("postDisplay_commentCount");
	postDisplay_commentCollection = document.getElementById("postDisplay_commentCollection");
}

function hydrateCompleteBlogPostDisplay(post)
{
	lookupPostElements();

	if(postDisplay_commentCollection == null)
	{
		window.location = post.Post.FullUrl;
		return;
	}
	
	//var y = YAHOO.util.Dom.getY("postAnchor");
	attributes = { scroll: { to: [0, 0] } };
	var animScroll = new YAHOO.util.Scroll(document.documentElement, attributes, 1, YAHOO.util.Easing.easeOut);
	animScroll.duration = .5;
	animScroll.animate();

	hydrateBlogPostDisplay(post.Post);
	postDisplay_body.parentNode.setAttribute("postId", post.PostID);
	postDisplay_title.href = post.Post.FullUrl;
	document.title = "C# Shiznit - " + post.Post.Title;
	
	postDisplay_permalink.href = post.Post.FullUrl;
	postDisplay_delicious.href = "http://del.icio.us/post?url=" + post.Post.FullUrl;
	postDisplay_digg.href = "http://www.digg.com/submit?phase=2&url=" + post.Post.FullUrl;

	if(post.NextPostUrl != null)
	{
		postDisplay_nextLink.style.display = "";
		postDisplay_nextLink.href = "javascript:loadPost('" + post.NextPostUrl + "')";
		postDisplay_nextLink.childNodes[0].title = "Next Post: " + post.NextPostTitle;
	}
	else
		postDisplay_nextLink.style.display = "none";
	
	if(post.PreviousPostUrl != null)
	{
		postDisplay_prevLink.style.display = "";
		postDisplay_prevLink.href = "javascript:loadPost('" + post.PreviousPostUrl + "')";
		postDisplay_prevLink.childNodes[0].title = "Previous Post: " + post.PreviousPostTitle;
	}
	else
		postDisplay_prevLink.style.display = "none";

	if(post.PackagedComments.length == 0)
		postDisplay_commentCount.innerHTML = post.Post.CommentCount;
	else
		postDisplay_commentCount.innerHTML = "<a href=\"#comments\">" + post.Post.CommentCount + "</a>";
	
	if(post.PackagedComments.length == 0)
		commentsTitle.style.display = "none";
	else
		commentsTitle.style.display = "";
	
	postDisplay_commentCollection.innerHTML = "";
	for(var i = 0; i < post.PackagedComments.length; i++)
	{
		var comment = post.PackagedComments[i];
		var cloneNode = commentClone.cloneNode(true);
		
		assignRelatedCommentElements(cloneNode);
		hydrateBlogPostCommentDisplay(comment);

		postDisplay_commentCollection.appendChild(cloneNode);
		cloneNode.style.display = "";
		cloneNode.setAttribute("commentId", comment.ID);
	}
}

function hydrateBlogPostDisplay(post)
{
	if(post == null)
		return;
		
	lookupPostElements();
	postDisplay_body.innerHTML = post.BodyDisplay;
	
	var oldTitle = postDisplay_title.innerHTML;
	postDisplay_title.innerHTML = Library.replaceStr(postDisplay_title.innerHTML, oldTitle, post.Title);
	
	postDisplay_date.innerHTML = post.DateStampLabel;
	postDisplay_time.innerHTML = post.TimeStampLabel;

	post.RelatedPostsDisplay = post.RelatedPostsDisplay == null ? "" : post.RelatedPostsDisplay;
	postDisplay_relatedPosts.innerHTML = post.RelatedPostsDisplay;
}

function sendContact()
{
	var validated = Page_ClientValidate("contact");
	if(!validated)
		return;

	var name = contactForm_name.value;
	var email = contactForm_email.value;
	var message = contactForm_message.value;

	var contactForm_notes = document.getElementById("contactForm_notes");
	contactForm_notes.className = "meta";
	contactForm_notes.innerHTML = "Sending data...";
	contactForm_notes.style.visibility = "visible";

	CSharper.Net.ScriptService.SendContact(name, email, message, sendContactCallback);
}

function sendContactCallback()
{
	var contactForm_notes = document.getElementById("contactForm_notes");
	contactForm_notes.className = "meta success";
	contactForm_notes.innerHTML = "Your message has been sent.";
	window.setTimeout(hideContactForm, 2000);
}

function displayContactForm()
{
	if(contactForm == null)
		contactForm = document.getElementById("contactForm");

	var contactForm_notes = document.getElementById("contactForm_notes");
	contactForm_notes.style.visibility = "hidden";

	modalForm = new ModalForm(contactForm);
	modalForm.display(function(){contactForm_name.focus()});
	contactForm_name.value = "";
	contactForm_email.value = "";
	contactForm_message.value = "";
}

function hideContactForm()
{
	modalForm.hide();
}


function displayLoginForm()
{
	if(loginForm == null)
		loginForm = document.getElementById("loginForm");
		
	var loginForm_notes = document.getElementById("loginForm_notes");
	loginForm_notes.style.visibility = "hidden";
	loginForm_username.value = "";
	loginForm_password.value = "";

	modalForm = new ModalForm(loginForm);
	modalForm.display(function(){loginForm_username.focus()});
}

function hideLoginForm()
{
	modalForm.hide();
}

function copyCode(img)
{
	var block = img.nextSibling;
	if(block == null)
		return;

	if(Library.isIe)
	{
		copyToClipboard(block.innerText);
		var div = img.parentNode.previousSibling;
		div.className = "meta";
		div.style.marginTop = "5px";
		div.style.display = "";
		div.innerHTML = "The code below has been copied to your clipboard";
		
		window.setTimeout(function(){div.style.display="none";}, 2000);
		return;
	}
	
	var range = document.createRange();
	range.selectNodeContents(block);

	var sel = window.getSelection();
	sel.addRange(range);
}

function copyToClipboard(text)
{
    if(!window.clipboardData)
	    return;

    window.clipboardData.setData("Text", text);
}

function subscribe()
{
	var validated = Page_ClientValidate("subscribe");
	if(!validated)
		return;

	var email = txtSubscribeEmail.value.trim();
	if(email.length == 0 || email == "your@email.com")
		return;
	
	btnSubscribe.disabled = true;
	CSharper.Net.ScriptService.Register(email, subscribeCallback);
}

function subscribeCallback(success)
{
	var subscribeConfirm = document.getElementById("subscribeConfirm");
	var subscribeForm = document.getElementById("subscribeForm");

	subscribeConfirm.innerHTML = success ? "Done. You'll be notified of new posts." : "You are already subscribed";

	subscribeConfirm.style.display = "";
	subscribeForm.style.display = "none";
	btnSubscribe.disabled = false;
}

function unsubscribeProduct(elId, pId, email)
{
	CSharper.Net.ScriptService.UnregisterProduct(pId, email);
	var el = document.getElementById(elId);
	el.style.display = "none";
}

function searchPosts()
{
	if(inProcess)
		return;
	
	lastSearchPhrase = searchPanel_search.value.trim();
	if(lastSearchPhrase == "this.Search();")
		return;

	inProcess = true;
	searchPanel_search.disabled = true;
	searchPanel_search.value = "Searching...";
	
	if(searchResults == null)
	{
		 searchResultsPanel = document.getElementById("searchResultsPanel");
		 searchResults = document.getElementById("searchResults");
	}

	if(searchResultsPanel.style.display == "none")
		searchResultsPanel.style.height = "1px";
	
	CSharper.Net.ScriptService.GetSearchResults(lastSearchPhrase, getSearchResultsCallback);
	btnSearch.disabled = true;
}

function searchPostsAnimateComplete()
{
	inProcess = false;
	if(searchPanel_search.disabled)
		return;
}

function getSearchResultsCallback(resultList)
{
	btnSearch.disabled = false;
	searchResultsPanel.style.overflow = "hidden";
	searchResultsPanel.style.display = "";
	
	var curHeight = searchResults.offsetHeight;
	searchResults.innerHTML = resultList;
	searchPanel_search.value = lastSearchPhrase;
	searchPanel_search.disabled = false;
	var newHeight = searchResults.offsetHeight + 30;

	if(newHeight < 400)
	{
		searchResults.parentNode.style.overflow = "hidden";
	}
	else
	{
		searchResults.parentNode.style.overflow = "auto";
		
		if(Library.isIe)
			searchResults.parentNode.style.overflowX = "hidden";
		 
		newHeight = 420;
	}
	
	var attributes = { height: {to: newHeight }  };
	var anim = new YAHOO.util.Anim(searchResultsPanel, attributes, 1, YAHOO.util.Easing.easeOut);
	anim.duration = 1;
	anim.onComplete.subscribe(searchPostsAnimateComplete);
	anim.animate();

	searchPanel_search.focus();
	searchPanel_search.select();

	searchPanel_search.blur();

	searchPanel_search.focus();
	searchPanel_search.select();
}

function clearSearchResults(txt)
{	
	txt.value = "this.Search();";

	if(searchResultsPanel == null || searchResultsPanel.style.display == "none")
		return;

	var attributes = { height: {to: 0 }  };
	var anim = new YAHOO.util.Anim(searchResultsPanel, attributes, 1, YAHOO.util.Easing.easeOut);
	anim.duration = 1;
	anim.onComplete.subscribe(clearSearchResultsAnimateComplete);
	anim.animate();
}

function clearSearchResultsAnimateComplete()
{
	searchResultsPanel.style.display = "none";
}

function loginUser()
{
	var validated = Page_ClientValidate("login");
	if(!validated)
		return;
		
	var loginForm_notes = document.getElementById("loginForm_notes");
	loginForm_notes.style.visibility = "visible";
	loginForm_notes.innerHTML = "Authorizing...";
	loginForm_notes.className = "meta";
	
	CSharper.Net.ScriptService.Login(loginForm_username.value, loginForm_password.value, loginUserCallback);
}

function loginUserCallback(response)
{
	var loginForm_notes = document.getElementById("loginForm_notes");

	if(response != null)
	{
		if(response != "refresh")
		{
			loginForm_notes.innerHTML = "Too many attempts. You need a timeout";
			loginForm_notes.className = "meta error";
			window.location = response;		
		}
		else
		{
			loginForm_notes.innerHTML = "You have been logged in. Redirecting...";
			loginForm_notes.className = "meta";
		}

		hideLoginForm();
		window.setTimeout(function() { window.location.reload(true);}, 1000);
	}
	else
	{
		
		loginForm_notes.innerHTML = "Invalid login.";
		loginForm_notes.className = "meta error";
		loginForm_username.focus();
	}
}