function selectTableRow(row) {
	if(hasClass(row, "selected"))
		return; // already selected

	if(!row.getAttribute("rowid"))
		return; // not selectable

	addClass(row, "selected");

	/*
		We also need to go through this table and unselect the others
	*/

	var children = row.parentNode.childNodes;
	for(i = 0; i < children.length; i++)
		if(children[i].tagName == "TR" && children[i] != row)
			removeClass(children[i], "selected");

	var par = row;
	do {
		if(par.tagName == "TABLE") {
			var onchange = par.getAttribute("onchange");
			if(onchange == null)
				break;
			par.selectedValue = row.getAttribute("rowid");
			var func = eval(onchange);
			if(row.cells && row.cells[0] && row.cells[0].childNodes && row.cells[0].childNodes[0])
				func(par.selectedValue, row.cells[0].childNodes[0].nodeValue);
			else
				func(par.selectedValue);
		}
	} while ( par = par.parentNode );
}

function makeSelectTableRow(row) {
	return function() {
		selectTableRow(row);
	}
}

var loadedContactItem;

function loadOneContact(contactId) {
	var idiotic = document.getElementById("contact-selection");
	var f = idiotic.getElementsByTagName("INPUT");
//	var f = document.forms["contact-selection"].contactIds;
	var i;
	if(f)
	for(i = 0; i < f.length; i++) {
		if(f[i].value == contactId)
			f[i].checked = true;
		else
			f[i].checked = false;
	}

	showOnlyMailingListEditBlock();

	get("newsletter.cgi?mode=get-contact-info-form&id=" + contactId, function(t) {
		var ce = document.getElementById("contact-edit");
		ce.style.display = "block";

		ce.innerHTML = t;
	});
}

function stopEvent(e) {
	if(!e) var e = window.event;
	e.cancelBubble = true;
	if(e.stopPropagation) e.stopPropagation();
}

function makeHelperFunctionForTdOnclickInTheContactList(lid) {
	return function(e) {
		//var stupid = document.getElementById("contact-selection").contactIds;
		var idiotic = document.getElementById("contact-selection");
		var stupid = idiotic.getElementsByTagName("INPUT");

		var roflI;
		if(stupid)
		for(roflI = 0; roflI < stupid.length; roflI++)
			if(stupid[roflI].value == lid)
				stupid[roflI].checked = !stupid[roflI].checked;

		contactCheckboxesChanged(lid);

		stopEvent(e);
	}
}

function contactCheckboxesChanged(lastTouched) {
//	var f = document.forms["contact-selection"].contactIds;
		var idiotic = document.getElementById("contact-selection");
		var f = idiotic.getElementsByTagName("INPUT");
	var selectedCount = numOfMultipleOptionsSelected(f);

	var i;
	var ct = document.getElementById("contacts");
	var cl = ct.getElementsByTagName("TR");

	var activeId;

	if(selectedCount == 0) {
		selectedCount = 1;
		for(i = 0; i < f.length; i++)
			if(f[i].value == lastTouched)
				f[i].checked = true;
	}
	if (selectedCount == 1) {
		var activeId;
		for(i = 0; i < f.length; i++)
			if(f[i].checked) {
				activeId = f[i].value;
				break;
			}
		for(i = 0; i < cl.length; i++)
			if(cl[i].getAttribute("rowid") == activeId)
				addClass(cl[i], "selected");
			else
				removeClass(cl[i], "selected");

			loadOneContact(activeId);
	} else {
		for(i = 0; i < cl.length; i++)
			removeClass(cl[i], "selected");

		// actually do something about the multiple select situation.....
		showOnlyMailingListEditBlock("multiple-edit");
		var ai = document.getElementById("multiple-edit");
	}
}

function showOnlyMailingListEditBlock(name) {
	var a = document.getElementById("list-edit");
	a.style.display = "none";

	a = document.getElementById("contact-edit");
	a.style.display = "none";

	a = document.getElementById("multiple-edit");
	a.style.display = "none";

	if(name) {
		a = document.getElementById(name)
		a.style.display = "block";
	}
}

function loadContacts(listId) {
	if(!listId)
		listId = 0;
	
	var le = document.getElementById("list-edit");
	showOnlyMailingListEditBlock();
	le.style.display = "block";

	var ce = document.getElementById("contact-edit");
	ce.style.display = "none";

	var e = document.getElementById("active-list-id");
	e.value = listId;

	if(listId) {
		get("newsletter.cgi?mode=get-mailing-list-info&id=" + listId, function(t) {
			var l = eval( "(" + t + ")" );
			var n = document.getElementById("list-name-field");
			if(n) {
				n.value = l.name;
			}
		});
	}

	get("newsletter.cgi?mode=get-contacts-from-list&list-id=" + listId, function(t) {
		var tbl = document.getElementById("contacts");
		var list = eval( "(" + t + ")" );

		var count = tbl.rows.length;
		for(i = 0; i < count; i++)
			tbl.deleteRow(0);

		if(list.length)
		for(i = 0; i < list.length; i++) {
			var l = list[i];

			var row = tbl.insertRow(-1);
			row.setAttribute("rowid", l.id);
			var td;
			td = row.insertCell(0);
			td.onclick = makeHelperFunctionForTdOnclickInTheContactList(l.id);

			var fuckYouSideways = document.createElement("INPUT");
			fuckYouSideways.setAttribute("type", "checkbox");
			fuckYouSideways.setAttribute("name", "contactIds");
			fuckYouSideways.setAttribute("value", l.id);
			fuckYouSideways.onclick = function(e) {
				this.checked = !this.checked;
				//contactCheckboxesChanged(this.value);
				//stopEvent(e);
				//return false;
			}
			td.appendChild(fuckYouSideways);

			td = row.insertCell(1);
			td.appendChild(document.createTextNode(l.first));
			td = row.insertCell(2);
			td.appendChild(document.createTextNode(l.last));
			td = row.insertCell(3);
			td.appendChild(document.createTextNode(l.company));

			row.onclick = makeSelectTableRow(row);
		} else {
			var row = tbl.insertRow(-1);
			var td = document.createElement("TD");
			td.setAttribute("colspan", 4);
			td.innerHTML = "This list has no subscribers.";
			row.appendChild(td);
		}
	});
}

function numOfMultipleOptionsSelected(field) {
	if(!field)
		return -1;
	if(!field.length)
		return -2;
	var i;
	
	var count = 0;
	for(i = 0; i < field.length; i++) {
		if(field[i].checked)
			count++;
	}

	return count;
}

function loadLetters(responderId) {
	var e = document.getElementById("active-responder-id");
	if(e == null)
		e = document.getElementById("rid");
	e.value = responderId;
	get("newsletter.cgi?mode=get-autoresponder-letters&responder-id=" + responderId, function(t) {
		var tbl = document.getElementById("letters");
		var list = eval( "(" + t + ")" );

		var count = tbl.rows.length;
		for(i = 0; i < count; i++)
			tbl.deleteRow(0);

		if(list.length)
		for(i = 0; i < list.length; i++) {
			var l = list[i];

			var row = tbl.insertRow(-1);
			var td;
			td = row.insertCell(0);
			td.appendChild(document.createTextNode(l.stage));
			td = row.insertCell(1);
			var randomDiv = document.createElement("DIV");
			randomDiv.appendChild(document.createTextNode(l.subject));
			randomDiv.style.verticalAlign = "middle";
			randomDiv.style.lineHeight = "28px";
			randomDiv.style.height = "24px";
			//randomDiv.style.backgroundColor = "red";

			var link = document.createElement("A");
			link.href = "newsletter.cgi?mode=view-newsletter&letter-id=" + l.letterId;
			link.target = "_BLANK";
			link.className = "button";
			link.innerHTML = "<img src=\"/site-icons/preview.png\" alt=\"\" /> Preview";
			link.setAttribute("style", "float: right;");
			link.onclick = function() {
				popinLink(this, l.subject);
				return false;
			}
			td.appendChild(link);

			td.appendChild(randomDiv);

			td = row.insertCell(2);
			td.appendChild(document.createTextNode((l.interval / 3600 / 1000 / 24) + " day" + ((l.interval / 3600 / 1000 / 24) == 1 ? "" : "s")));
			td = row.insertCell(3);
			td.appendChild(document.createTextNode(l.time + ":00"));

			row.onclick = makeSelectTableRow(row);
		} else {
			var row = tbl.insertRow(-1);
			var td;
			td = row.insertCell(0);
			td.setAttribute("colspan", 5);
			td.style.color = "red";
			td.innerHTML = "This responder has no letters!";
		}
	});
}

function createMailingList(e) {
	var name = prompt("What is the name of the new mailing list?");
	if(name == null)
		return;
	if(name.length < 1) {
		alert("Sorry, mailing lists need to have names.");
		return;
	}

	post("newsletter.cgi", {
		"mode" : "create-mailing-list",
		"name" : name
	}, function(t) {
		if(t.length == 0 || t == "0") {
			alert("List creation failed");
			return;
		}
		var tbl = document.getElementById("mailing-lists");
		if(tbl) {
			var row = tbl.insertRow(-1);
			var td = row.insertCell(0);

			td.appendChild(document.createTextNode(name));
			row.setAttribute("rowid", t);
			row.onclick = makeSelectTableRow(row);

			selectTableRow(row);
		}
		if(e) {
			var list = document.createElement("OPTION");
			list.setAttribute("value", t);
			list.appendChild(document.createTextNode(name));
			e.appendChild(list);
			e.selectedIndex = e.options.length - 1;
		}
	});
}

function previewSubscription() {
	var s = document.getElementById("subscription-form-preview");

	s.style.display = "block";

	var message = document.getElementById("message").value;

	s.innerHTML = "<h3>Preview</h3> <p>" + message  + "</p> <input type=\"submit\" value=\"Subscribe\" />";
}

function makeSubscription() {
	var s = document.getElementById("subscription-form-preview");

	s.style.display = "block";

	var message = document.getElementById("message").value;

	s.innerHTML = "";

	s.appendChild(document.createTextNode("<p>" + message  + "</p> <form method=\"POST\" action=\"http://socialrevolucion.com/newsletter.cgi\"><table><tr><th>First name:</th><td><input name=\"first\" /></td></tr><td>Last name:</td><td><input name=\"last\" /></td></tr><tr><td>Email:</td><td><input name=\"email\" /></td></tr><tr><td></td><td><input type=\"submit\" value=\"Subscribe\" /></td></table></form>"));
}


function addArLetter(letterId, letterSubject, preInterval, preTime) {
	var table = document.getElementById("ar-letters");

	if(table.rows.length == 1 && table.rows[0].cells.length == 1) // the intro message
		table.deleteRow(0);


	var latestStage = table.rows.length;

	var row = table.insertRow(-1);
	var cell;

	var th = document.createElement("TH");
	th.style.borderBottom = "none";
	th.appendChild(document.createTextNode(latestStage + 1));
	row.appendChild(th);

	cell = row.insertCell(1);
	cell.appendChild(document.createTextNode(letterSubject));

	cell = row.insertCell(2);
	var selectedInterval = latestStage == 0 ? 0 : (3600*24*1000);
	if(preInterval)
		selectedInterval = preInterval;
	cell.appendChild(createIntervalDropdown(selectedInterval));

	cell = row.insertCell(3);
	cell.appendChild(createTimeDropdown(preTime ? preTime : 12));

	cell = row.insertCell(4);
	cell.setAttribute("align", "center");
	var viewButton = document.createElement("BUTTON");
	viewButton.setAttribute("type", "button");
	viewButton.onclick = function() {
		window.open("newsletter.cgi?mode=view-newsletter&letter-id=" + letterId);
	}
//	viewButton.href = "newsletter.cgi?mode=view-newsletter&letter-id=" + letterId;
	viewButton.appendChild(document.createTextNode("View"));
	cell.appendChild(viewButton);

	var deleteButton = document.createElement("BUTTON");
	deleteButton.appendChild(document.createTextNode("Delete"));
	deleteButton.setAttribute("type", "button");
	deleteButton.onclick = deleteArLetter(row);
	cell.appendChild(deleteButton);

	cell.appendChild(document.createElement("BR"));

	var upButton = document.createElement("BUTTON");
	upButton.innerHTML = "&uarr; Up";
	upButton.setAttribute("type", "button");
	upButton.onclick = moveArLetterUp(row);
	cell.appendChild(upButton);

	var downButton = document.createElement("BUTTON");
	downButton.innerHTML = "&darr; Down";
	downButton.setAttribute("type", "button");
	downButton.onclick = moveArLetterDown(row);
	cell.appendChild(downButton);

	var info;
	info = document.createElement("INPUT");
	info.setAttribute("type", "hidden");
	info.setAttribute("name", "letterId");
	info.setAttribute("value", letterId);
	cell.appendChild(info);

	info = document.createElement("INPUT");
	info.setAttribute("type", "hidden");
	info.setAttribute("name", "ordering");
	info.setAttribute("value", latestStage + 1);
	cell.appendChild(info);
}

function updateOrdering(row, newOrdering) {
	var h = row.getElementsByTagName("TH");
	h = h[0];
	h.innerHTML = newOrdering;

	var i = row.getElementsByTagName("INPUT");
	for(a = 0; a < i.length; a++) {
		if(i[a].getAttribute("name") == "ordering") {
			i[a].value = newOrdering;
		}
	}
}

function moveArLetterUp(row) {
	return function() {
		var table = document.getElementById("ar-letters");
		var rowIndex = 0;
		for(i = 0; i < table.rows.length; i++) {
			if(table.rows[i] == row) {
				rowIndex = i;
				break;
			}
		}
		if(rowIndex == 0) {
			alert("This letter is alread on the top of the list.");
			return;
		}
		if(table.rows.length == 1) {
			alert("Add more letters to the autoresponder by clicking on them to the left.");
			return;
		}

		var oldRow = table.rows[rowIndex];
		var oldOtherRow = table.rows[rowIndex - 1];

			var h = oldRow.getElementsByTagName("TH");
			h = h[0];

			var stage = new Number(h.innerHTML);

			updateOrdering(oldRow, stage - 1);

			h = oldOtherRow.getElementsByTagName("TH");
			h = h[0];

			stage = new Number(h.innerHTML);

			updateOrdering(oldOtherRow, stage + 1);

		swapNodes(oldRow, oldOtherRow);

	}
}


function moveArLetterDown(row) {
	return function() {
		var table = document.getElementById("ar-letters");
		var rowIndex = 0;
		for(i = 0; i < table.rows.length; i++) {
			if(table.rows[i] == row) {
				rowIndex = i;
				break;
			}
		}
		if(rowIndex + 1 == table.rows.length) {
			alert("This letter is alread on the bottom of the list.");
			return;
		}
		if(table.rows.length == 1) {
			alert("Add more letters to the autoresponder by clicking on them to the left.");
			return;
		}

		var oldRow = table.rows[rowIndex];
		var oldOtherRow = table.rows[rowIndex + 1];

			var h = oldRow.getElementsByTagName("TH");
			h = h[0];

			var stage = new Number(h.innerHTML);
			updateOrdering(oldRow, stage + 1);

			h = oldOtherRow.getElementsByTagName("TH");
			h = h[0];

			stage = new Number(h.innerHTML);
			updateOrdering(oldOtherRow, stage - 1);

		swapNodes(oldRow, oldOtherRow);

	}
}

function deleteArLetter(row) {
	return function() {
		var table = document.getElementById("ar-letters");
		var rowIndex = 0;
		for(i = 0; i < table.rows.length; i++) {
			if(table.rows[i] == row) {
				rowIndex = i;
				break;
			}
		}

		for(i = rowIndex; i < table.rows.length; i++) {
			var cr = table.rows[i];
			var h = cr.getElementsByTagName("TH");
			h = h[0];

			var stage = new Number(h.innerHTML);
			updateOrdering(cr, stage - 1);
		}

		table.deleteRow(rowIndex);

		if(table.rows.length == 0) {
			var r = table.insertRow(-1);
			var d = document.createElement("TD");
			d.setAttribute("colspan", 5);
			d.innerHTML = "Add letters to this responder by clicking on them to the left.";
			r.appendChild(d);
		}
	}
}

function createIntervalDropdown(selected) {
	var select = document.createElement("SELECT");
	select.name = "interval";

	var option;

	option = document.createElement("OPTION");
	option.value = 3600*1000   * 0;
	option.appendChild(document.createTextNode("Instantly"));
	select.appendChild(option);

	option = document.createElement("OPTION");
	option.value = 3600*1000   * 24;
	option.appendChild(document.createTextNode("1 day"));
	select.appendChild(option);

	for(a = 2; a < 7; a++) {
		option = document.createElement("OPTION");
		option.value = 3600*1000   * 24 * a;
		option.appendChild(document.createTextNode(a + " days"));
		select.appendChild(option);
	}

	option = document.createElement("OPTION");
	option.value = 3600*1000   * 24 * 7;
	option.appendChild(document.createTextNode("1 week"));
	select.appendChild(option);

	option = document.createElement("OPTION");
	option.value = 3600*1000   * 24 * 14;
	option.appendChild(document.createTextNode("2 weeks"));
	select.appendChild(option);

	option = document.createElement("OPTION");
	option.value = 3600*1000   * 24 * 30;
	option.appendChild(document.createTextNode("1 month"));
	select.appendChild(option);


	if(typeof selected != "undefinied")
	for(a = 0; a < select.options.length; a++) {
		if(select.options[a].value == selected)
			select.selectedIndex = a;
	}

	return select;
}

function createTimeDropdown(selected) {
	var select = document.createElement("SELECT");
	select.name = "time";

	var option;

	for(a = 0; a <= 23; a++) {
		option = document.createElement("OPTION");
		option.value = a;
		option.appendChild(document.createTextNode(
			a < 12
			? (( a == 0 ? "12:00 AM"
				:(a + ":00 AM"))
			) : (
				a == 12 ? "12:00 PM"
				:
				(a - 12 + ":00 PM")
			)
		));
		select.appendChild(option);

		if(typeof selected != "undefined")
		if(a == selected) {
			select.selectedIndex = a;
		}
	}

	return select;
}

function selectNewsletter(id) {
	var e = document.getElementById("active-newsletter-id");
	e.value = id;

	document.getElementById("control-message").style.display = "none";
	document.getElementById("controls").style.visibility = "visible";

	get("newsletter.cgi?mode=get-letter-info&id=" + id, function(t) {
		var d = eval("(" + t + ")");

		var ls = document.getElementById("lsubject");

		ls.innerHTML = "";

		ls.appendChild(document.createTextNode(d.subject.length ? d.subject : "[ No Subject ]"));
	});

	get("newsletter.cgi?mode=get-letter-schedule&id=" + id, function(t) {
		var d = eval("(" + t + ")");

		var st = document.getElementById("schedule");
		var i;
		for(i = 0; i < st.rows.length; i++)
			st.deleteRow(i);

		for(i = 0; i < d.length; i++) {
			var s = d[i];
			var row = st.insertRow(-1);
			var td;

			td = row.insertCell(0);
			td.innerHTML = (
				s["status"] == 1 ?
					'<img src="/site-icons/letter-sent.png" alt="Sent" />'
					:
					'<img src="/site-icons/letter-not-sent.png" alt="Pending" />'
			);

			td = row.insertCell(1);
			td.appendChild(document.createTextNode(s["date"]));

			td = row.insertCell(2);
			td.appendChild(document.createTextNode(s.mailingList));

			td = row.insertCell(3);
			td.appendChild(document.createTextNode(s.time));

			td = row.insertCell(4);
			td.innerHTML = "<form method=\"POST\">" +
				"<input type=\"hidden\" name=\"mode\" value=\"cancel-letter-schedule\" />" +
				"<input type=\"hidden\" name=\"id\" value=\""+s.id+"\" />" +
				"<input type=\"submit\" value=\"Cancel\" />" +
			"</form>";
		}

		if(d.length == 0) {
			var row = st.insertRow(-1);
			var td = document.createElement("TD");
			td.setAttribute("colspan", 4);

			row.appendChild(td);
			td.innerHTML = "This letter is not currently scheduled to be sent.";
		}
	});


}

function addNewsletterCategory() {
	var name = prompt("Category name?");
	if(name && name.length > 0) {
		post("/newsletter.cgi", {
			"mode" : "create-newsletter-category",
			"name" : name
		}, function(t) {
			var s = document.getElementById("nlcategories");
			var o = document.createElement("OPTION");
			o.value = t;
			o.appendChild(document.createTextNode(name));
			s.appendChild(o);
			s.selectedIndex = s.options.length - 1;
		});
	}
}

function fillInMultipleContactData(formToFill, dataToFill) { // the data argument is 1 == contact IDs, 2 == list ID, OR'd together
	var e;

	if(dataToFill & 2) {
		e = document.getElementById("active-list-id");
		var listId = e.value;

		formToFill.listId.value = listId;
	}

	if(dataToFill & 1) {
		e = document.getElementById("contact-selection");
		var cids = e.contactIds;
		var a;

		var res = "";
		var outputted = false;
		for(a = 0; a < cids.length; a++) {
			if(cids[a].checked) {
				if(outputted)
					res += ",";
				else
					outputted = true;

				res += cids[a].value;
			}
		}

		formToFill.contactIds.value = res;
	}
}

