// JS file for KC front page
var pageCurr = "news";


// Initialize event handlers
window.onload = function(){

	// Mike-Edit: Replaced the below commented out line with what follows.  This
	// code is pretty ugly and should be cleaned up, but at least it works :)
	//$("#news").onclick = newsClick;
	$("#news").click(function() { newsClick(); });
	$("#name").click(function() { newsClick(); });
	$("#about").click(function() { aboutClick(); });
	$("#photos").click(function() { photosClick(); });
	$("#shows").click(function() { showsClick(); });
	$("#contact").click(function() { contactClick(); });
	$("#music").click(function() { musicClick(); });
    newsClick();
}

function newsClick(){
	pageCurr = "news";
	ajaxCall("news");
}

function aboutClick(){
	pageCurr = "about";
	ajaxCall("about");
	Image1= new Image(358,537);
	Image1.src = "about/normalFaces.jpg";
	Image2= new Image(358,537);
	Image2.src = "about/goofyFaces.jpg";
}

function photosClick(){
	pageCurr = "photos";
	ajaxCall("photos");
}

function showsClick(){
	pageCurr = "shows";
	ajaxCall("shows");
}

function contactClick(){
	pageCurr = "contact";
	ajaxCall("contact");
}

function musicClick(){
	pageCurr = "music";
	ajaxCall("music");
}

function bostonClick(){
	pageCurr = "boston";
	ajaxCall("boston");
}

function trim(str){
	var start; var end; var length;
	while (true)
	{
		length = str.length;
		str = str.replace("  ", " ");
		if (length == str.length)
			break;
	}
	for (start = 0; start < str.length; start++)
	{
		if (str.charAt(start) != ' ')
			break;
	}
	for (end = str.length - 1; end >= 0; end--)
	{
		if (str.charAt(end) != ' ')
			break;
	}
	if (start <= end)
		return str.substring(start, end + 1);
	else
		return "";
}

function validateInput(str){
	if (str.length > 80)
		return false;
	if (str.indexOf("\"") != -1)
		return false;
	if (str.indexOf("<") != -1)
		return false;
	if (str.indexOf(">") != -1)
		return false;

	return true;
}

function validateName(name){
	return validateInput(name);
}

function validateEmail(email){
	if (!validateInput(email))
		return false;

	// Make sure the '@' isn't the first character and the '.' comes after the '@' but isn't the last character.
	var atIdx = email.indexOf("@");
	if (atIdx < 1)
		return false;

	var dotIdx = email.lastIndexOf(".");
	return (dotIdx > atIdx + 1 && dotIdx + 1 < email.length);
}

// Zak, here is the email list code you might want to add 'method: "post"' after the url line, not sure
function submitClick(){
	var name = $("#fullname").val();
	var email = $("#email").val();
	name = trim(name);
	email = trim(email);
	if (!validateName(name))
		alert("I've heard some made up names in my day, but that's just rich.");
	else if (!validateEmail(email))
		alert("I'm supposed to believe that's your email address?  Nice try, Chuckles.");
	else
	{
		$.ajax({
			url: "content.php",
			data: ({name: name, email: email}),
			context: document.body,
			success: function(event, request, settings){ // not sure what this stuff does other than fun what is in the curly brackets. You will have to ask mike, it is different.
				alert("Thanks for joining!");
				$("#fullname").val("");
				$("#email").val("");
			}
		});
	}
}

function ajaxCall(pageName){
	$.ajax({
		url: "content.php",
		data: ({page: pageName}),
		context: document.body,
		success: function(event, request, settings){
			if(pageCurr == "news")
			{
				showNews(settings.responseXML.getElementsByTagName("newspost"));
			}
			else if(pageCurr == "shows")
			{
				showShows(settings.responseXML.getElementsByTagName("show"));
			}
			else
			{
				showOther(settings.responseText);
				if(pageCurr == "music"){
					$("#boston").click(function() { bostonClick(); });
				}

				if(pageCurr == "contact"){
					$("#submit").click(function() { submitClick(); });
				}
			}

			scroll(0,0);
		}
	});
}

/*
 * Mike-Edit: This 'showContent' is now passed as an anonymous function
 * as the 'success' parameter of 'ajaxCall's actual ajax call.
 *
function showContent(ajax){
	if(pageCurr == "news")
	{
		showNews(ajax.responseXML.getElementsByTagName("newspost"));
	}
	else if(pageCurr == "shows")
	{
		showShows(ajax.responseXML.getElementsByTagName("show"));
	}
	else
	{
		showOther(ajax.responseText);
	}
}
*/

// Function to display non news or show content
function showOther(newContent){
	// Mike-Edit: Replaced below
	//$("content").innerHTML = newContent;
	$('#content').html(newContent);

	$('a[rel*=lightbox]').lightBox(); // Select all links that contains lightbox in the attribute rel
}

function isFuture(day, month, year){
	var date = new Date();
	var dayC = date.getDate();
	var monthC = date.getMonth() + 1;
	var yearC = date.getFullYear();

	return (year > yearC ||
		(year == yearC && (month > monthC ||
		(month == monthC && (day > dayC || (day == dayC))))));
}

function getElementValue(entry, name){
	var elements = entry.getElementsByTagName(name);
	if (elements.length > 0 &&
		elements[0].childNodes.length > 0)
		return elements[0].childNodes[0].nodeValue;
	else
		return "";
}

function showShows(entries){

	//Variables for xml processing
	var month; var day; var year = 0; var prevYear;
	var venueLink; var venueName; var address; var city; var state; var zip;
	var time; var cover; var ages;
	var bands; var band; var bandLink; var bandName;
	var divLeft; var divMid; var divRight;
	var venueTag; var currentPost; var oldPost;
	var showInfo; var showInfo2; var line1; var line2; var line3;
	var line; var future = true;
	var firstPost; var latestShow; var yearChange;
	var entryT; var titleT; var show;
	var CALENDAR = ["","JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEPT", "OCT", "NOV", "DEC"];
	var i; var lastShowIdx;

	for (i = 0; i < entries.length; i++)
	{
		year = getElementValue(entries[i], "year");
		month = getElementValue(entries[i], "month");
		day = getElementValue(entries[i], "day");

		if (!isFuture(day, month, year))
		{
			lastShowIdx = i;
			if (i > 0)
				i--;
			break;
		}
	}

	$('#content').empty();

	while (i < entries.length)
	{
		prevYear = year;
		year = getElementValue(entries[i], "year");
		month = getElementValue(entries[i], "month");
		day = getElementValue(entries[i], "day");

		venueLink = getElementValue(entries[i], "venueLink");
		venueName = getElementValue(entries[i], "venueName");
		address = getElementValue(entries[i], "address");
		city = getElementValue(entries[i], "city");
		state = getElementValue(entries[i], "state");
		zip = getElementValue(entries[i], "zipcode");
		time = getElementValue(entries[i], "time");
		cover = getElementValue(entries[i], "cover");
		ages = getElementValue(entries[i], "ages");
		bands = (entries[i].getElementsByTagName("band"));

		future = isFuture(day, month, year);
		firstPost = (i == lastShowIdx - 1 ||
			(i == 0 && lastShowIdx == 0));
		latestShow = (i == lastShowIdx);
		yearChange = (!future && year != prevYear);

		if (firstPost || future || latestShow || yearChange)
		{
			// end this post (if there is one) and start a new one
			if (!firstPost)
				$('#content').append(entryT);
			entryT = newElement("div", "", "post");
			if (firstPost && future)
			{
				titleT = newElement("h2", "Upcoming Shows", "");
				entryT.append(titleT);
			}
			else if (latestShow)
			{
				titleT = newElement("h2", "Past Shows", "");
				entryT.append(titleT);
			}

			if (latestShow || yearChange)
			{
				titleT = newElement("h3", year, "");
				entryT.append(titleT);
			}
		}

		// create shows columns
		show = newElement("div", "" , "show");
		divLeft = newElement("div", "", "left");
		dateT = newElement("p", "", "showDate");
		dayT = newElement("span", day, "day");
		monthT = newElement("span", CALENDAR[Number(month)], "month");
		dateT.append(dayT);
		dateT.append(monthT);
		divLeft.append(dateT);

		// Create middle div
		divMid = newElement("div", "" , "middle");

		showInfo = newElement("p", "", "showInfo");
		// venue info and start time
		if (venueLink == "")
		{
			line1 = newElement("span", venueName, "venue");
		}
		else
		{
			line1 = newElement("a", venueName, "venue");
			line1.attr('href', venueLink);
		}
		showInfo.append(line1);
		showInfo.append(document.createElement("br"));
		if (future)
		{
			line2 = newElement("span", address, "");
			showInfo.append(line2);
			showInfo.append(document.createElement("br"));
			line3 = newElement("span", city + ", " + state + " " + zip, "");
		}
		else
		{
			line3 = newElement("span", city + ", " + state, "");
		}
		showInfo.append(line3);
		showInfo.append(document.createElement("br"));
		divMid.append(showInfo);

		if (future)
		{
			line = "";
			if (time != "")
				line = time;
			if (cover != "")
			{
				if (line != "")
					line += ", ";
				line += cover;
			}
			if (ages != "")
			{
				if (line != "")
					line += ", ";
				line += ages;
			}
			showInfo2 = newElement("p", line, "");
			divMid.append(showInfo2);
		}

		// Accompanying bands
		divRight = newElement("div", "" , "right");
		bandList = newElement( "p", "" , "bandList" );
		if (!future && bands.length > 0)
		{
			bandList.append(newElement("span", "with:", ""));
			bandList.append(document.createElement("br"));
		}

		// loop over all bands
		for(var b = 0; b < bands.length; b++)
		{
			bandLink = getElementValue(bands[b], "link");
			bandName = getElementValue(bands[b], "name");
			if (future || bandName != "Killer Canary")
			{
				if (bandLink == "")
				{
					band = newElement("span", bandName, "");
				}
				else
				{
					band = newElement("a", bandName, "");
					band.attr('href', bandLink);
				}
				bandList.append(band);
				bandList.append(document.createElement("br"));
			}
		}

		divRight.append(bandList);

		// Add new elements to page
		show.append(divLeft);
		show.append(divMid);
		show.append(divRight);
		entryT.append(show);

		if (i >= lastShowIdx)
			i++;
		else if (i == 0)
			i = lastShowIdx;
		else
			i--;
	}

	$('#content').append(entryT);
}
/*
<show>
		<date>
			<month>06</month>
			<day>02</day>
			<year>2011</year>
		</date>
		<venueLink>http://www.skylarkcafe.com/</venueLink>
		<venueName>The Skylark Cafe &amp; Club</venueName>
		<address>3803 Delridge Way SW</address>
		<city>Seattle</city>
		<state>WA</state>
		<zipcode>98106</zipcode>
		<time>9 PM</time>
		<cover>???</cover>
		<ages>21+</ages>
		<bands>
			<band>
				<link>http://www.myspace.com/teammascot</link>
				<name>Team Mascot</name>
			</band>
			<band>
				<link>http://www.morningbellonline.com/</link>
				<name>Morningbell</name>
			</band>
			<band>
				<link>http://www.myspace.com/wesaybang</link>
				<name>We Say Bang!</name>
			</band>
			<band>
				<name>Killer Canary</name>
			</band>
		</bands>
	</show>
*/


// Functions for news feed
function showNews(entries){
// Variables for xml processing
	var month; var day; var year; var title; var info; var by;
	var txt; var entryT; var dateT; var dayT; var monthT;
	var titleT; var byT; var entry;
	var CALENDAR = ["","JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEPT", "OCT", "NOV", "DEC"];

	$('#content').empty();

	var length = entries.length;
	for(var i = 0; i < entries.length; i++){

		month = (entries[i].getElementsByTagName("month")[0].childNodes[0].nodeValue);
		day = (entries[i].getElementsByTagName("day")[0].childNodes[0].nodeValue);
		year = (entries[i].getElementsByTagName("year")[0].childNodes[0].nodeValue);
		title = (entries[i].getElementsByTagName("title")[0].childNodes[0].nodeValue);
		by = (entries[i].getElementsByTagName("by")[0].childNodes[0].nodeValue);
		info = (entries[i].getElementsByTagName("p"));

		// Create tags, fill in text and add classes
		entryT = newElement("div", "", "post");
		dateT = newElement("p", "", "newsDate");
		dayT = newElement("span", day, "day");
		monthT = newElement("span", CALENDAR[Number(month)], "month");
		titleT = newElement("h2", title, "");
		var infoT =[""];

		for(var j = 0; j < info.length; j++)
		{
			infoT[j] = newElement("p", info[j].childNodes[0].nodeValue, "");
		}
		j = 0;
		byT = newElement("span", by, "by");

		// add tags as children of the div	to the HTML doc

		// Mike-Edit: All calls to 'appendChild' are replaced by calls to 'append'.
		dateT.append(dayT);
		dateT.append(monthT);
		entryT.append(dateT);
		entryT.append(titleT);

		for(var k = 0; k < infoT.length; k++)
		{
			entryT.append(infoT[k]);
		}

		entryT.append(byT);
		$('#content').append(entryT);
		k = 0;
	}
}

// Must be changed before posting site !!!
function ajaxFailure(ajax, exception) {
	alert("Error making Ajax request:" +
		"\n\nServer status:\n" + ajax.status + " " + ajax.statusText +
		"\n\nServer response text:\n" + ajax.responseText);
	if (exception) {
		throw exception;
	}
}

function newElement(type, content, className){
	return $('<' + type + '/>').addClass(className).html(content);
}

/*
 * Mike-Edit: This function is replaced by the new 'newElement'
 * function directly above.
 *
function newElement(type, content, className){
	var element = document.createElement(type);

	if(content != "")
	{
		element.innerHTML = content;
	}

	if(className != "")
	{
		element.addClass(className);
		//element.addClassName(className);
	}

	return element;
}*/

