var curr_icon = "";
var selected_row = -1;
var selected_bg = "";

var LIST_READING = 0;
var LIST_WISH = 1;
var LIST_COMPLETE = 2;
var LIST_UNFINISHED = 3;
var LIST_HOLD = 4;

function selectRow(sid)
{
	var old_row = -1;
	old_row = selected_row;

	// unselect previous row
	if (selected_row != -1)
	{
		if (sid != selected_row)
		{
			// Check all series between and including
			// sid and selected_row. (which is sid2)
			var myTab = document.getElementById('list_table');

			var inSelectedRegion = 0;
			for (var i = 0; i < myTab.rows.length; i++)
			{
				// Get the sid of the current row.
				var row_sid = myTab.rows[i].id.substring(1);

				if (row_sid == sid || row_sid == selected_row)
				{
					inSelectedRegion++;
					if (inSelectedRegion == 2)
					{
						document.getElementById('cb_'+row_sid).checked = !(document.getElementById('cb_'+row_sid).checked);
						break;
					}
				}

				if (inSelectedRegion == 1)
				{
					document.getElementById('cb_'+row_sid).checked = !(document.getElementById('cb_'+row_sid).checked);
				}

			}

		}

		//Unselect
		document.getElementById('r'+selected_row).style.backgroundColor=selected_bg;
		selected_row = -1;
	}
	else
	{
		//Select
		selected_row = sid;
		selected_bg = document.getElementById('r'+sid).style.backgroundColor;
		document.getElementById('r'+sid).style.backgroundColor='#E4FFBC';
	}

}

function listUpdate2(request)
{
	var resp = request.responseText;
	var colonPos = resp.indexOf(':');
	if (!colonPos || colonPos == -1)
	{
		return;
	}
	var sid = resp.substring(0,colonPos);
	document.getElementById('s'+sid).innerHTML = "<div class='stEdit'><a href='javascript:editVol("+sid+")'><img src='images/edit.gif' alt='edit'></a></div>" + resp.substring(colonPos + 1);
}


function listUpdate(request)
{
	var resp = request.responseText;
	
	var colonPos = resp.indexOf(':');

	if (!colonPos || colonPos == -1)
	{
		return;
	}

	var icon = resp.substring(0,colonPos);

	if (curr_icon != icon)
	{
		curr_icon = icon;
		document.getElementById('list_image').src = "images/listicons/"+icon+".gif";
	}
	
	var link = document.getElementById("listLink");

	switch (icon)
	{
		case "type0":
			link.href="mylist.html?list=read";
			break;
		case "type1":
			link.href="mylist.html?list=wish";
			break;
		case "type2":
			link.href="mylist.html?list=complete";
			break;
		case "type3":
			link.href="mylist.html?list=unfinished";
			break;
		case "type4":
			link.href="mylist.html?list=hold";
			break;
		default:
			link.href="mylist.html";
			break;
	}

	document.getElementById('showList').innerHTML = resp.substring(colonPos + 1);
}


function incrementVolume(sid,amount)
{
	sendHTTPRequest(listUpdate, "ajax/list_update.php?s=" + sid + "&inc_v="+amount);
}

function incrementChapter(sid,amount)
{
	sendHTTPRequest(listUpdate, "ajax/list_update.php?s=" + sid + "&inc_c="+amount);
}


function resetChapter(sid)
{
	sendHTTPRequest(listUpdate, "ajax/list_update.php?s=" + sid + "&reset_c=1");
}

/* Following functions are for incrementing chapter ON LIST */

function incrementVolume2(sid,amount)
{
	sendHTTPRequest(listUpdate2, "ajax/chap_update.php?s=" + sid + "&inc_v="+amount);
}
function incrementChapter2(sid,amount)
{
	sendHTTPRequest(listUpdate2, "ajax/chap_update.php?s=" + sid + "&inc_c="+amount);
}
function resetChapter2(sid)
{
	sendHTTPRequest(listUpdate2, "ajax/chap_update.php?s=" + sid + "&reset_c=1");
}

/* END INCREMENT CHAPTER ON LIST FUNCTIONS */


function remove(sid, list)
{
	sendHTTPRequest(listUpdate, "ajax/list_update.php?s=" + sid + "&l=" + list + "&r=1");
}

function addComplete(sid)
{
	sendHTTPRequest(listUpdate, "ajax/list_update.php?s=" + sid + "&l=" + LIST_COMPLETE);
}

function addReading(sid)
{
	sendHTTPRequest(listUpdate, "ajax/list_update.php?s=" + sid + "&l=" + LIST_READING);
}

function addWish(sid)
{
	sendHTTPRequest(listUpdate, "ajax/list_update.php?s=" + sid + "&l=" + LIST_WISH);
}

function addUnfinished(sid)
{
	sendHTTPRequest(listUpdate, "ajax/list_update.php?s=" + sid + "&l=" + LIST_UNFINISHED);
}

function addHold(sid)
{
	sendHTTPRequest(listUpdate, "ajax/list_update.php?s=" + sid + "&l=" + LIST_HOLD);
}

function addOther(sid, list)
{
	sendHTTPRequest(listUpdate, "ajax/list_update.php?s=" + sid + "&l=" + list);
}

function moveToList(sid, list)
{
	sendHTTPRequest(listUpdate, "ajax/list_update.php?s=" + sid + "&l=" + list);
}


/* This is handling for adding series in list */


var i = 1;

function updateList(event)
{
	var series = document.getElementById("series_name");
	var reason = document.getElementById("series_priority");
	var table = document.getElementById("series_table");

	doClean(series);

	if (series.value == "")
	{
		return;
	}

	if (i == 1)
	{
		deleteHelpRow();
	}

	var rowNum = table.rows.length;

	var newRow = table.insertRow(rowNum);
	newRow.setAttribute("id", "add_row_" + i);

	//Series Name
	var seriesCol = newRow.insertCell(0);
	seriesCol.setAttribute("class", "text list_add1");
	seriesCol["class"] = seriesCol["className"] = "text list_add1";
	seriesCol.setAttribute("id", "add_name_" + i);

	var seriesName = document.createTextNode(series.value);
	seriesCol.appendChild(seriesName);

	//hidden text field
	var seriesInput = document.createElement('input');
	seriesInput.setAttribute("class", "item_delete");
	seriesInput["class"] = seriesInput["className"] = "item_delete";
	seriesInput.type="text";
	seriesInput.name="ADD_SERIES["+i+"]";
	seriesInput.size=1;
	seriesInput.value=series.value;


	//Empty box
	var emptyCol = newRow.insertCell(1);
	emptyCol.appendChild(document.createTextNode(" "));

	//Type
	var typeCol = newRow.insertCell(2);
	typeCol.setAttribute("class", "text list_add2");
	typeCol["class"] = typeCol["className"] = "text list_add2";

	var seriesType = document.createTextNode(reason.options[reason.selectedIndex].innerHTML);
	typeCol.appendChild(seriesType);

	//hidden type field
	var typeInput = document.createElement('input');
	typeInput.setAttribute("class", "item_delete");
	typeInput["class"] = typeInput["className"] = "item_delete";
	typeInput.type="text";
	typeInput.name="ADD_TYPE["+i+"]";
	typeInput.size=1;
	typeInput.value=reason.value;

	
	//store these babies in the type column because it will be unharmed
	typeCol.appendChild(seriesInput);
	typeCol.appendChild(typeInput);


	//Options
	var optionsCol = newRow.insertCell(3);
	optionsCol.setAttribute("class", "text list_add2");
	optionsCol["class"] = optionsCol["className"] = "text list_add2";

	var options = document.createElement("a");
	options.href = "javascript:cancelThis(" + i + ")";
	options.innerHTML = "<u>Cancel Add</u>";
	optionsCol.appendChild(options);

	//make request
	
	var val1 = escape(series.value);
	var val2 = "";
	var pos = 0;
	var loc = 0;
	while ((loc = val1.indexOf('+', pos)) != -1)
	{
		val2 += val1.substring(pos, loc) + "%2B";
		pos = loc + 1;
	}
	val2 += val1.substring(pos);

	sendHTTPRequest(finishFindSeries, "ajax/find_series.php?series=" + val2 + "&id=" + i);
	//reset fields
	series.value = "";
	i = i + 1;
}


function finishFindSeries(request)
{
	var resp = request.responseText;
	
	var colonPos = resp.indexOf(':');
	
	if (!colonPos || colonPos == -1)
	{
		return;
	}

	var idString = resp.substring(0,colonPos);
	var id = parseInt(idString);

	//see if we haven't canceled already;

	var elem = document.getElementById("add_name_" + id);

	if (!elem)
	{
		return;
	}

	elem.innerHTML = resp.substring(colonPos + 1);
}

function deleteHelpRow()
{
	var table = document.getElementById("series_table");
	var elem = document.getElementById("help_row");
	for (var k = 0; k < table.rows.length; k++)
	{
		if (table.rows[k] == elem)
		{
			table.deleteRow(k);
			return;
		}
	}
}


function cancelThis(elem)
{
	var table = document.getElementById("series_table");
	var elem = document.getElementById("add_row_" + elem);
	
	for (var k = 0; k < table.rows.length; k++)
	{
		if (table.rows[k] == elem)
		{
			table.deleteRow(k);
			return;
		}
	}
}

function handleThis(event)
{
	var key = getKeyCode(event);
	
	if (key == 13)
	{
		updateList(event);
		return false;
	}
}


function expandAdd()
{
	document.getElementById("add_series").style.display='block';
	document.getElementById("series_name").focus();
}

function expandBulk()
{
	document.getElementById("bulk_add").style.display='block';
	document.getElementById("bulk_add_field").focus();
}


var selected = -1;

function cPri(sid, amount)
{
	var elem = document.getElementById("r"+sid);
	var table = document.getElementById("list_table");

	for (var k = 2; k < table.rows.length; k++)
	{
		if (table.rows[k] == elem)
		{
			var newK = k - amount;

			//check boundaries

			if (newK >= table.rows.length - 1)
			{
				newK = table.rows.length - 2;
			}

			if (newK < 2)
			{
				newK = 2;
			}
			
			if (k == newK)
			{
				return;
			}

			if (selected != -1)
			{
				document.getElementById("c"+selected).style.backgroundColor='#C0EEFF';
				selected = -1;
			}
			
			//alert(k + "-" + newK);

			swap(k, newK);

			var seriesId = table.rows[newK].id.substring(1);

			selected = seriesId;
			document.getElementById("c"+selected).style.backgroundColor='#FFFF00';

			//send out http request!

			sendHTTPRequest(finishPriority, "ajax/update_priority.php?s=" + sid + "&n=" + (newK - 1));

			return;
		}
	}
}

function finishPriority(request)
{
	//do nothing!
}


function swap(row1, row2)
{
	var table = document.getElementById("list_table");
	
	var temp;

	var startRow = 1;
	var endRow = table.rows.length - 2;

	if (row2 > row1)
	{
		for (var i = row1; i < row2; i++)
		{
			changeRowElements(table.rows[i], table.rows[i+1]);
		}
	}
	else
	{
		for (var i = row1; i > row2; i--)
		{
			changeRowElements(table.rows[i], table.rows[i-1]);
		}
	}
}



function changeRowElements(elem1, elem2)
{
	var sid1 = elem1.id.substring(1);
	var sid2 = elem2.id.substring(1);

	var td1_c = document.getElementById("c"+sid1);
	var td1_d = document.getElementById("d"+sid1);
	var td1_n = document.getElementById("n"+sid1);
	var td1_s = document.getElementById("s"+sid1);
	var td1_k = document.getElementById("k"+sid1);

	var td2_c = document.getElementById("c"+sid2);
	var td2_d = document.getElementById("d"+sid2);
	var td2_n = document.getElementById("n"+sid2);
	var td2_s = document.getElementById("s"+sid2);
	var td2_k = document.getElementById("k"+sid2);


	swapTD(td1_c, td2_c);
	swapTD(td1_d, td2_d);
	swapTD(td1_n, td2_n);
	swapTD(td1_s, td2_s);
	swapTD(td1_k, td2_k);

	//update row id
	var temp = elem1.id;
	elem1.id = elem2.id;
	elem2.id = temp;
}


function swapTD(td1, td2)
{
	var temp = td1.innerHTML;
	td1.innerHTML = td2.innerHTML;
	td2.innerHTML = temp;

	temp = td1.id;
	td1.id = td2.id;
	td2.id = temp;
}

function editVol(sid)
{
	var vol = document.getElementById("s" + sid);
	var str = vol.innerHTML.toLowerCase();
	
	var leftPos = str.indexOf('v.') + 2;
	var rightPos = str.indexOf('</b>',leftPos);
	var volNum = str.substring(leftPos, rightPos);

	var leftPos = str.indexOf('c.') + 2;
	var rightPos = str.indexOf('</b>',leftPos);
	var chapNum = str.substring(leftPos, rightPos);

	vol.innerHTML = "v.<input id='fv"+sid+"' class='inbox volInput' value='"+volNum+"' onKeyDown='return updateVol(event,"+sid+")'>&nbsp;c.<input id='fc"+sid+"' class='inbox volInput' value='"+chapNum+"' onKeyDown='return updateVol(event,"+sid+")'><a href='javascript:doUpdateVol("+sid+")'><img src='images/update.gif' alt='update'></a>";
	document.getElementById('fv'+sid).focus();
	document.getElementById('fv'+sid).select();
}


function doUpdateVol(sid)
{
		var chap = document.getElementById("fc"+sid);
		var vol = document.getElementById("fv"+sid);
		sendHTTPRequest(listUpdate2, "ajax/chap_update.php?s=" + sid + "&set_v=" + vol.value + "&set_c="+chap.value);
}

function updateVol(event, sid)
{
	var key = getKeyCode(event);

	if (key == 13)
	{
		doUpdateVol(sid);
		return false;
	}
}


function addRating(sid)
{
	var rate = document.getElementById("k" + sid);
	var str = rate.innerHTML.toLowerCase();
	var leftPos = str.indexOf('<b>');
	var rightPos = str.indexOf('</b>');
	var currRating = "";
	if (leftPos == -1 || rightPos == -1)
	{
		//do nothing?
	}
	else
	{
		currRating = str.substring(leftPos+3, rightPos);
	}
	rate.innerHTML = "<input id='fr"+sid+"' maxlength='3' class='inbox rateInput' value='"+currRating+"' onKeyDown='return updateRating(event,"+sid+")'><a href='javascript:doUpdateRating("+sid+")'><img src='images/update.gif' alt='update'></a>";

	document.getElementById('fr'+sid).focus();
	document.getElementById('fr'+sid).select();
}

function doUpdateRating(sid)
{
	var rating = document.getElementById("fr"+sid);
	if (!rating)
	{
		return false;
	}
	sendHTTPRequest(finishRating, "ajax/update_rating.php?s=" + sid + "&r=" + rating.value);
}

function updateRating(event, sid)
{
	var key = getKeyCode(event);

	if (key == 13)
	{
		var rating = document.getElementById("fr"+sid);
		if (!rating)
		{
			return false;
		}

		sendHTTPRequest(finishRating, "ajax/update_rating.php?s=" + sid + "&r=" + rating.value);

		return false;
	}
}

function finishRating(request)
{
	var resp = request.responseText;
	var colonPos = resp.indexOf(':');
	if (!colonPos || colonPos == -1)
	{
		return;
	}
	var sid = resp.substring(0,colonPos);

	document.getElementById("k" + sid).innerHTML = resp.substring(colonPos + 1);
	
	var elem = document.getElementById("refreshButton");
	if (elem)
	{
		elem.style.display='block';
	}
}
