
//
// Initialise an XMLHTTP Object
// Code from Jim Ley's:
// http://jibbering.com/2002/4/httprequest.html
//

var xmlhttp;

//function newXmlHttpRequest() {
xmlhttp="";
/*@cc_on @*/
/*@if (@_jscript_version >= 5)
 try {
  xmlhttp=new ActiveXObject("Msxml2.XMLHTTP")
 } catch (e) {
  try {
   xmlhttp=new ActiveXObject("Microsoft.XMLHTTP")
  } catch (E) {
   xmlhttp=false
  }
 }
@else
 xmlhttl=false
@end @*/
if (!xmlhttp) {
 try {
  xmlhttp = new XMLHttpRequest();
 } catch (e) {
  xmlhttp=false;
  alert("XmlHttp Not supported.");
 }
}
//}



// URL of the current atomAPI entry point
var atomEntryPoint="";

// Reference to the XML document representing
// a list of entries in a blog
var currentEntryList;

var entryDoc="";
var entryUrl="";

var entryButton="";

// Reference of the current page being displayed
var currentCard="atomEntry";

// Standard content-type
var atomContentType = "application/x.atom+xml";

var defaultAuthorName="";
var defaultAuthorEmail="";
var defaultAuthorUrl="";
var defaultAuthorFrom="";

var authorAction="";

/*
 * DOM Functions
 */

function showCard(cardid) {
	cardid = document.getElementById(cardid);
	if (cardid) {
		if (cardid.style) {
			cardid.style.display="block";
		} else {
			cardid.display="block";
		}
	}
}

function hideCard(cardid) {
	cardid = document.getElementById(cardid);
	if (cardid) {
		if (cardid.style) {
			cardid.style.display="none";
		} else {
			cardid.display="none";
		}
	}
}

function setCard(cardid) {
	hideCard(currentCard);
	showCard(cardid);
	currentCard=cardid;
	return false;
}

function hideButton(butt) {
	butt = document.getElementById(butt);
	if (butt) {
		if (butt.style) {
			butt.style.visibility="hidden";
		} else {
			butt.visiblity="hidden";
		}
	}
}

function showButton(butt) {
	butt = document.getElementById(butt);
	if (butt) {
		if (butt.style) {
			butt.style.visibility="visible";
		} else {
			butt.visiblity="visible";
		}
	}
}

function updateEntryMenu() {
	hideButton("entryAddButton");
	showButton("entryUpdateButton");
	showButton("entryDeleteButton");
}

function newPostEntryMenu() {
	showButton("entryAddButton");
	hideButton("entryUpdateButton");
	hideButton("entryDeleteButton");
}

function antiCache(tempUrl) {
	if (document.all) {
		ts = new Date().valueOf();
		if (tempUrl.indexOf('?')>=0) {
			return "&ts=" +  ts;
		} else {
			return "?ts=" + ts;
		}
	}
	return "";
}

/*
 * XMLHTTP functions
 */

function requestBlog() {
	if (atomEntryPoint) {
		//newXmlHttpRequest();
		//xmlhttp.open("GET", atomEntryPoint, true);
		xmlhttp.open("GET", atomEntryPoint + antiCache(atomEntryPoint), true);
		xmlhttp.onreadystatechange = requestBlogFeed;
		xmlhttp.setRequestHeader("Content-Type", atomContentType);
		xmlhttp.send(null);

		//alert("Content2:" + xmlhttp.responseXML);
	} else {
		alert("atomEntryPoint not set");
	}
}

function requestBlogFeed() {
	switch(xmlhttp.readyState) {
		case 2,3:

			break;
		case 4:
			if (xmlhttp.status==200) {
				//currentEntryList = xmlhttp.responseText;
				//alert("Content:" + xmlhttp.responseXML);
				currentEntryList = xmlhttp.responseXML;
				//alert("XMLDoc: " + currentEntryList);

				setCard("debugEntry");
				document.debug.output.value=xmlhttp.responseText;
				document.debug.dump.value=currentEntryList;

				extractEntryList();

			} else {
				alert("Status is: " + xmlhttp.status);
			}
			break;
	}
}

function extractEntryList() {
	//alert(currentEntryList);

	el = document.getElementById("blogUnorderedList");
	while (el.hasChildNodes()) {
		el.removeChild(el.lastChild);
	}
	if (currentEntryList) {
		entries = currentEntryList.getElementsByTagName("entry");
		document.debug.dump.value = "Entries: " + entries.length + "\n";
		msg="";
		for (i=0; i < entries.length; i++) {
			msg += "Entry(" + i + "): " + entries[i].nodeName + "\n";
			msg += "Children: " + entries[i].childNodes.length + "\n";

			title     = "";
			link      = "";
			//author    = "";
			created   = "";

			for(j=0; j < entries[i].childNodes.length; j++) {
				msg += "Child(" + j + "):\n "
				+ entries[i].childNodes[j].nodeName + "|" + entries[i].childNodes[j].nodeType + "\n";

				if (entries[i].childNodes[j].nodeName=="title") {
					title = entries[i].childNodes[j].childNodes[0].nodeValue;
				}
				if (entries[i].childNodes[j].nodeName=="link") {
					link = entries[i].childNodes[j].childNodes[0].nodeValue;
				}
				//if (entries[i].childNodes[j].nodeName=="author") {
				//	for (k=0; k < entries[i].childNodes[j].childNodes.length; k++) {
				//		if (entries[i].childNodes[j].childNodes[k].nodeName=="name") {
				//			author = entries[i].childNodes[j].childNodes[k].childNodes[0].nodeValue;
				//		}
				//	}
				//}
				if (entries[i].childNodes[j].nodeName=="created") {
					created = entries[i].childNodes[j].childNodes[0].nodeValue;
				}

			}

			if (!title) {
				title = link;
			}

			msg += " Title: " + title + "\n";
			msg += " Link: " + link + "\n";
			//msg += " Author: " + author + "\n";
			msg += " Created: " + created + "\n";


			// Creating the li

			listItem = document.createElement('li');
			anchor = document.createElement('a');
			if (document.all) {
				anchor.setAttribute("href", "javascript:editAnEntry(\"" + link + "\"); void 0;");
			} else {
				anchor.setAttribute("href", link);
				//anchor.setAttribute("target", "_blank");
				anchor.setAttribute("onclick", "editAnEntry(this); return false;");
			}

			anchor.appendChild(document.createTextNode(title));

			listItem.appendChild(anchor);

			el.appendChild(listItem);

		}
		document.debug.dump.value += msg;
	} else {

		listItem = document.createElement('li');
		listItem.appendChild(document.createTextNode("No entries in this Atom service"));

		el.appendChild(listItem);
	}
	setCard("blogList");
}


function requestEntry() {
	if (entryUrl) {
		//alert(atomEntryPoint);
		//newXmlHttpRequest();
		//xmlhttp.open("GET", atomEntryPoint, true);
		xmlhttp.open("GET", entryUrl + antiCache(entryUrl), true);
		xmlhttp.onreadystatechange = requestBlogEntry;
		xmlhttp.setRequestHeader("Content-Type", atomContentType);
		xmlhttp.send(null);

		//alert("Content2:" + xmlhttp.responseXML);
	} else {
		alert("entryUrl not set");
	}
}

function requestBlogEntry() {
	switch(xmlhttp.readyState) {
		case 2,3:

			break;
		case 4:
			if (xmlhttp.status==200) {
				//alert("Content:" + xmlhttp.responseXML);
				entryDoc = xmlhttp.responseXML;
				//alert("XMLDoc: " + xmlhttp.responseText);

				setCard("debugEntry");
				document.debug.output.value=xmlhttp.responseText;
				document.debug.dump.value= entryUrl + "\n" + entryDoc + "\n";

				extractEntry();

			} else {
				alert("Status is: " + xmlhttp.status);
			}
			break;
	}
}

function extractEntry() {
	msg = "";
	entryList = entryDoc.getElementsByTagName("entry");
	anEntry = entryList[0];

	title="";
	summary=""
	content="";

	id="";
	link="";

	authorName="";
	authorUrl="";
	authorEmail="";

	content="";

	for (j=0; j < anEntry.childNodes.length; j++) {
		msg += " Child(" + j + "): " + anEntry.childNodes[j].nodeName + "|" + anEntry.childNodes[j].childNodes.length + "\n";

		//summary += "[" + entry.childNodes[j].nodeName + "]";
		if (anEntry.childNodes[j].nodeName=="title") {
			title = anEntry.childNodes[j].childNodes[0].nodeValue;
		}
		if (anEntry.childNodes[j].nodeName=="summary") {
			summary += anEntry.childNodes[j].childNodes[0].nodeValue;
		}
		if (anEntry.childNodes[j].nodeName=="id") {
			id = anEntry.childNodes[j].childNodes[0].nodeValue;
		}
		if (anEntry.childNodes[j].nodeName=="link") {
			link = anEntry.childNodes[j].childNodes[0].nodeValue;
		}
		if (anEntry.childNodes[j].nodeName=="author") {
			for (k=0; k < anEntry.childNodes[j].childNodes.length; k++) {
				if (anEntry.childNodes[j].childNodes[k].nodeName=="name") {
					authorName = anEntry.childNodes[j].childNodes[k].childNodes[0].nodeValue;
				}
				if (anEntry.childNodes[j].childNodes[k].nodeName=="url") {
					authorUrl = anEntry.childNodes[j].childNodes[k].childNodes[0].nodeValue;
				}
				if (anEntry.childNodes[j].childNodes[k].nodeName=="email") {
					authorEmail = anEntry.childNodes[j].childNodes[k].childNodes[0].nodeValue;
				}
			}
		}
		if (anEntry.childNodes[j].nodeName=="content" && !content) {
			for(k=0; k < anEntry.childNodes[j].childNodes.length;k++) {
				msg += "  " + anEntry.childNodes[j].childNodes[k].nodeName + "|" + anEntry.childNodes[j].childNodes[k].nodeType + "|" + anEntry.childNodes[j].childNodes[k].nodeValue + "\n";
				if (anEntry.childNodes[j].childNodes[k].nodeType=="4") {
					content = anEntry.childNodes[j].childNodes[k].nodeValue
				}
			}
		}


	}

	msg += "\n Title: " + title + "\n";
	msg += " Summary: " + summary + "\n";
	msg += " Content: " + content + "\n";

	msg += "\n Author Name: " + authorName + "\n";
	msg += " Author Email: " + authorEmail + "\n";
	msg += " Author Url: " + authorUrl + "\n";


	document.entry.title.value = title;
	document.entry.summary.value = summary;
	document.entry.cont.value = content;

	document.entry.entryid.value = id;
	document.entry.entrylink.value = link;

	document.author.name.value = authorName;
	document.author.url.value = authorUrl;
	document.author.email.value = authorEmail;

	document.debug.dump.value += msg;

	updateEntryMenu();
	setCard("blogEntry");
}

function updateEntry() {
	if (entryUrl) {
		//alert(atomEntryPoint);
		//newXmlHttpRequest();
		//xmlhttp.open("GET", atomEntryPoint, true);
		msg = getCurrentEntryAsXml();
		//alert(getCurrentEntryAsXml());
		xmlhttp.open("PUT", entryUrl, true);
		xmlhttp.onreadystatechange = updateBlogEntry;
		xmlhttp.setRequestHeader("Content-Type", atomContentType);
		xmlhttp.setRequestHeader("Content-Length", msg.length);

		xmlhttp.send(msg);

		setCard("debugEntry");
		document.debug.output.value=msg;
		document.debug.dump.value=entryUrl + "\n" + msg.length;

		//alert("Content2:" + xmlhttp.responseXML);
	} else {
		alert("entryUrl not set");
	}
}

function getCurrentEntryAsXml() {

	// Unfortunately this commented out DOM-related script generates the
	// document using all uppercase XML element names.
	// Don't know how to get it generating lower case.
	/* entryEl = document.createElement('entry');

	titleEl = document.createElement('title');
	titleEl.appendChild(document.createTextNode(document.entry.title.value));
	entryEl.appendChild(titleEl);

	if (document.entry.summary.value) {
		summaryEl = document.createElement('summary');
		summaryEl.appendChild(document.createTextNode(document.entry.summary.value));
		entryEl.appendChild(summaryEl);
	}

	authorEl = document.createElement('author');

	authorNameEl = document.createElement('name');
	authorNameEl.appendChild(document.createTextNode(document.author.name.value));
	authorEl.appendChild(authorNameEl);

	if (document.author.url.value) {
		authorUrlEl = document.createElement('url');
		authorUrlEl.appendChild(document.createTextNode(document.author.url.value));
		authorEl.appendChild(authorUrlEl);
	}
	if (document.author.email.value) {
		authorEmailEl = document.createElement('email');
		authorEmailEl.appendChild(document.createTextNode(document.author.email.value));
		authorEl.appendChild(authorEmailEl);
	}
	entryEl.appendChild(authorEl);

	contentEl = document.createElement('content');
	//contentEl.appendChild(document.createTextNode(document.entry.cont.value));
	entryEl.appendChild(contentEl);

	serializer = new XMLSerializer();
	return serializer.serializeToString(entryEl); */

	// Hack until I can get the above DOM-based script to work properly.
	// i.e. lower case elements

	msg = "";

	msg += "<?xml version=\"1.0\" encoding=\"iso-8859-1\"?>\n";
	msg += "<entry>\n";
	msg += "<title>" + document.entry.title.value + "</title>\n";

	if (document.entry.summary.value) {
		msg += "<summary>" + document.entry.summary.value + "</summary>\n";
	}

	if (document.entry.entrylink.value) {
		msg += "<link>" + document.entry.entrylink.value + "</link>\n";
	}
	if (document.entry.entryid.value) {
		msg += "<id>" + document.entry.entryid.value + "</id>\n";
	}

	msg += "\n";
	msg += "<author>\n";
	msg += "<name>" + document.author.name.value + "</name>\n";
	msg += "\n";

	if (document.author.url.value) {
		msg += "<url>" + document.author.url.value + "</url>\n";
	}

	if (document.author.email.value) {
		msg += "<email>" + document.author.email.value + "</email>\n";
	}
	msg += "</author>\n";

	msg += "\n";
	msg += "<created>2003-09-10T13:53+01:00</created>\n";
	//msg += "<issued>2003-08-08T09:31+01:00</issued>\n";
	//msg += "<modified>2003-08-08T09:31+01:00</modified>\n";
	msg += "\n";
	msg += "<content type=\"text/html\" mode=\"escaped\">\n";
	msg += "<![CDATA[\n";
	msg += document.entry.cont.value;
	msg += "]]>\n";
	msg += "</content>\n";
	msg += "\n";
	msg += "</entry>\n";

	return msg;

}

function updateBlogEntry() {
	switch(xmlhttp.readyState) {
		case 2,3:

			break;
		case 4:
			if (xmlhttp.status==205 || xmlhttp.status==201) {
				//alert("Content Updated.");
				requestBlog();
			} else {
				//alert("Status is: " + xmlhttp.status);
				alert("Status is: " + xmlhttp.status + " Response Text:[" + xmlhttp.responseText + "]");
			}
			break;
	}
}

function addEntry() {
	if (atomEntryPoint) {
		//alert(atomEntryPoint);
		//newXmlHttpRequest();
		//xmlhttp.open("GET", atomEntryPoint, true);
		msg = getCurrentEntryAsXml();
		//alert(getCurrentEntryAsXml());
		xmlhttp.open("POST", atomEntryPoint, true);
		xmlhttp.onreadystatechange = addBlogEntry;
		xmlhttp.setRequestHeader("Content-Type", atomContentType);
		xmlhttp.setRequestHeader("Content-Length", msg.length);

		xmlhttp.send(msg);

		setCard("debugEntry");
		document.debug.output.value=msg;
		document.debug.dump.value=entryUrl + "\n" + msg.length;

		//alert("Content2:" + xmlhttp.responseXML);
	} else {
		alert("entryUrl not set");
	}
}

function addBlogEntry() {
	switch(xmlhttp.readyState) {
		case 2,3:

			break;
		case 4:
			if (xmlhttp.status==201) {
				//alert("Content Added.");
				requestBlog();
			} else {
				//alert("Status is: " + xmlhttp.status);
				alert("Status is: " + xmlhttp.status + " Response Text:[" + xmlhttp.responseText + "]");
			}
			break;
	}
}

function deleteEntry() {
	if (entryUrl) {
		xmlhttp.open("DELETE", entryUrl, true);
		xmlhttp.onreadystatechange = deleteBlogEntry;
		xmlhttp.setRequestHeader("Content-Type", atomContentType);

		xmlhttp.send(null);

		setCard("debugEntry");
		document.debug.output.value="";
		document.debug.dump.value=entryUrl + "\n";

		//alert("Content2:" + xmlhttp.responseXML);
	} else {
		alert("entryUrl not set");
	}
}

function deleteBlogEntry() {
	switch(xmlhttp.readyState) {
		case 2,3:

			break;
		case 4:
			if (xmlhttp.status==200) {
				//alert("Content Deleted.");
				requestBlog();
			} else {
				//alert("Status is: " + xmlhttp.status);
				alert("Status is: " + xmlhttp.status + " Response Text:[" + xmlhttp.responseText + "]");
			}
			break;
	}
}



/*
 *	Atom Functions
 */

function init() {
	showCard(currentCard);
}

function saveDefaultAuthorDetails() {
	if (!defaultAuthorFrom) {
		if (document.author.name.value) {
			defaultAuthorName = document.author.name.value;
		}
		if (document.author.url.value) {
			defaultAuthorUrl = document.author.url.value;
		}
		if (document.author.email.value) {
			defaultAuthorEmail = document.author.email.value;
		}
	}
}

function doAtom(f) {
	atomEntryPoint="";
	if (f.entryPoint.value) {
		//alert("entryPoint entered");
		atomEntryPoint = f.entryPoint.value;
	} else if (f.entryList.selectedIndex) {
		//alert("entryList selected")
		atomEntryPoint = f.entryList.options[f.entryList.selectedIndex].value;
	} else {
		//alert("Atom Entry");
	}

	if (atomEntryPoint) {
		//alert("Atom Entry Point set: " + atomEntryPoint);
		requestBlog();
	} else {
		alert("Please either enter an AtomAPI url in the text area, or select a predefined one from the dropdown.");
	}


	return false;
}

function editAnEntry(aref) {
	if (document.all) {
		saveDefaultAuthorDetails();
		defaultAuthorFrom="edit";

		entryUrl = aref;
		requestEntry();
		//alert(aref);
	} else {
		if (aref && aref.href) {
			saveDefaultAuthorDetails();
			defaultAuthorFrom="edit";

			entryUrl = aref.href;
			requestEntry();
			//alert("Done");
		} else {
			alert("No blog entry specified");
		}
	}

	return false;
}

function doEntry(f) {
	if (atomEntryPoint) {
		if (entryButton=="update") {
			updateEntry();
		} else if (entryButton=="delete") {
			if (confirm("Are you sure you want to delete this post?")) {
				deleteEntry();
			}
		} else if (entryButton=="add") {
			if (document.author.name.value) {
				addEntry();
			} else {
				alert("You need to enter your author details before adding a new post");
				setCard("authorEntry");
			}
		} else {
			alert("Entry Submit: " + entryButton);
		}
	} else {
		alert("Chose an AtomAPI entry point first!");
	}
	return false;
}

function doBlogList(f) {
	if (atomEntryPoint) {
		document.entry.title.value = "";
		document.entry.summary.value = "";
		document.entry.cont.value = "";
		document.entry.entryid.value = "";
		document.entry.entrylink.value = "";

		document.author.name.value = defaultAuthorName;
		document.author.url.value = defaultAuthorUrl;
		document.author.email.value = defaultAuthorEmail;
		defaultAuthorFrom="";

		newPostEntryMenu();
		setCard("authorEntry");
	} else {
		alert("Chose an AtomAPI entry point first!");
	}

	return false;
}

function doAuthor(f) {
	if (authorAction=="reset") {
		//alert("Reset author to default " + defaultAuthorName);
		if (defaultAuthorName) {
			document.author.name.value = defaultAuthorName;
			document.author.url.value = defaultAuthorUrl;
			document.author.email.value = defaultAuthorEmail;
		} else {
			alert("No decent defaults available. Who are you again?");
		}
	} else if (authorAction=="save") {
		//alert("Save Author as default");

		defaultAuthorFrom="";
		saveDefaultAuthorDetails();
		defaultAuthorFrom="save";
		setCard("blogEntry");
	} else {
		alert ("No action requested. [" + authorAction + "]");
	}
	return false;
}


