var numSelectedSections = 0;
var numCircles = 0;
var circle1 = new Array("a");
var circle2 = new Array("a", "b", "ab");
var circle3 = new Array("a", "b", "c", "ab", "ac", "bc", "abc");
var circle4 = new Array("a", "b", "c", "d", "ab", "ac", "bd", "cd", "abc", "abd", "acd", "bcd", "abcd");
var imageArray = new Array(circle1, circle2, circle3, circle4);

var radius = 50;
var centerPoints1 = new Array("75,75");
var centerPoints2 = new Array("60,75", "110,75");
var centerPoints3 = new Array("50,50", "100,50", "75,100");
var centerPoints4 = new Array("50,50", "100,50", "50,100", "100,100");
var coordinatesArray = new Array(centerPoints1, centerPoints2, centerPoints3, centerPoints4);

var emptyImage = new Image();
var lastSelectedField;
var termsEncoded;
function init()
{
	termsEncoded = false;
	emptyImage.src = "images/Venn Graphics/empty.gif";
	lastSelectedField = null;

	loadImageArray();

	if(document.layers)
		document.captureEvents(Event.MOUSEDOWN);

	document.onmouseup = captureMouseclick;
	document.oncontextmenu = captureRightclick;

	var selectField = 0;
	for(var i = 0; i < 4; i++)
	{
		if(document.queryForm.elements[i].value != "")
		{
			if(window.decodeURIComponent)
				document.queryForm.elements[i].value = window.decodeURIComponent(document.queryForm.elements[i].value);

			if(i < 3)
			{
				document.queryForm.elements[i + 1].readOnly = false;

				if(document.queryForm.elements[i + 1].value == "")
				{
					selectField = i + 1;
				}
			}
		}
	}

	if(selectField == 0 && document.queryForm.elements[0].value != "")
		document.queryForm.elements[0].select();
	else
		document.queryForm.elements[selectField].focus();

	if(document.queryForm.selectedSections.value != "")
	{
		var sections = document.queryForm.selectedSections.value.split(",");

		setNumCircles(sections[0]);
		clearImages();

		for(var i = 1; i < sections.length; i++)
		{
			loadImage(sections[i]);
		}
	}

	setQuery();
}

// Preloads all the images for the Venn diagram into a matrix
function loadImageArray()
{
	var tempArray;
	var baseURL;

	for(var i = 0; i < imageArray.length; i++)
	{
		tempArray = imageArray[i];
		imageArray[i] = new Array();

		for(var j = 0; j < tempArray.length; j++)
		{
			baseURL = "images/Venn Graphics/" + (parseInt(i) + 1) + " Circles/";

			imageArray[i][j] = new Image;
			imageArray[i][j].name = tempArray[j];
			imageArray[i][j].src = baseURL + (parseInt(i) + 1) + tempArray[j] + ".gif";
		}
	}
}

function captureMouseclick(e)
{
	if(typeof(visible) != 'undefined' && visible)
		hideMenu();

	var shiftDown;

	if(window.Event)
	{
		shiftDown = (e.shiftKey || e.ctrlKey || (e.which > 1));
	}
	else
	{
		shiftDown = (window.event.shiftKey || window.event.ctrlKey || (window.event.button > 1));
	}

	if(numCircles > 0)
		checkCircles(e, shiftDown);

	return false;
}

function captureRightclick(e)
{
	// Calling checkCircles in this function for IE and Netscape results in odd behavior because every right
	// click fires both a mouseclick and rightclick event, so only call checkCircles in captureRightclick if
	// the browser is Safari and the control key is not being held down
	if(navigator.appVersion.indexOf("Safari") != -1 && !e.ctrlKey)
	{
		checkCircles(e, true);
	}

	return false;
}

function captureKeypress(fieldIndex)
{
	if(!document.queryForm.elements[fieldIndex].readOnly)
	{
		if(document.queryForm.elements[fieldIndex].value != "")
		{
			if(fieldIndex < 3 && (document.queryForm.elements[fieldIndex + 1].readOnly))
			{
				document.queryForm.elements[fieldIndex + 1].readOnly = false;

				// This prevents a textfield from looking like it has focus when its readOnly status is changed
				// in Netscape, because the textfield doesn't actually have focus but changing readOnly to false
				// will put the cursor there anyway making it appear that it does
				if(navigator.appVersion.indexOf("MSIE") == -1)
				{
					document.queryForm.elements[fieldIndex + 1].focus();
					document.queryForm.elements[fieldIndex].focus();
				}
			}

			if(numCircles < fieldIndex + 1)
			{
				setNumCircles(fieldIndex + 1);
			}

			lastSelectedField = document.queryForm.elements[fieldIndex].name;
		}
		else
		{
			var empty = true;
			for(var i = fieldIndex + 1; i < 4; i++)
			{
				if(document.queryForm.elements[i].value != "")
					empty = false;
			}

			if(empty)
			{
				if(fieldIndex < 3 && !document.queryForm.elements[fieldIndex + 1].readOnly)
				{
					document.queryForm.elements[fieldIndex + 1].readOnly = true;
				}

				// If field is empty, and delete is pressed, set focus to above text field and select its text
				if(fieldIndex > 0 && numCircles == fieldIndex && lastSelectedField == document.queryForm.elements[fieldIndex].name)
				{
					document.queryForm.elements[fieldIndex - 1].focus();
					document.queryForm.elements[fieldIndex - 1].select();
					lastSelectedField = document.queryForm.elements[fieldIndex - 1].name;
				}
				else
				{
					lastSelectedField = document.queryForm.elements[fieldIndex].name;
				}

				if(fieldIndex > -1 && fieldIndex != numCircles)
				{
					setNumCircles(fieldIndex);
				}
			}
			else
			{
				// Shift remaining search terms up to replace the now-empty text field
				for(var i = fieldIndex; i < 3; i++)
				{
					document.queryForm.elements[i].value = document.queryForm.elements[i + 1].value;
					document.queryForm.elements[i + 1].value = "";
				}

				// Make sure that appropriate fields are set to readOnly
				for(var i = fieldIndex; i < 4; i++)
				{
					if(i > 0 && document.queryForm.elements[i - 1].value == "")
						document.queryForm.elements[i].readOnly = true;
				}

				document.queryForm.elements[numCircles - 1].focus();
				lastSelectedField = document.queryForm.elements[numCircles - 1].name;
				setNumCircles(numCircles - 1);
			}
		}
	}

	setQuery();

	return true;
}

// Checks all circles looking to see in which ones the mouse clicked
function checkCircles(e, shiftDown)
{
	var mouseClickX, mouseClickY;

	if(window.Event)
	{
		if(e.target != "[object SELECT]")
		{
			if(e.target.name == "abcd")
			{
				mouseClickX = e.layerX;
				mouseClickY = e.layerY;
			}
		}
	}
	else
	{

		if(window.event.srcElement != "[object SELECT]")
		{
			if(window.event.srcElement.name == "abcd")
			{
				mouseClickX = window.event.offsetX;
				mouseClickY = window.event.offsetY;
			}
		}
	}

	var clickedCircles = "";
	var centerOffsetX, centerOffsetY, coordinates;
	for(var i = 0; i < coordinatesArray[numCircles - 1].length; i++)
	{
		coordinates = coordinatesArray[numCircles -1][i].split(",");

		centerOffsetX = mouseClickX - parseInt(coordinates[0]);
		centerOffsetY = mouseClickY - parseInt(coordinates[1]);

		if((radius * radius) > (centerOffsetX * centerOffsetX + centerOffsetY * centerOffsetY))
		{
			clickedCircles += imageArray[3][i].name;
		}
	}

	if(clickedCircles != "")
	{
		if(!shiftDown)
		{
			clearImages();
		}

		loadImage(clickedCircles);
	}

	setQuery();
}

function setNumCircles(numCircles)
{
	var intersect = "abcd";
	this.numCircles = numCircles;

	clearImages();

	if(numCircles > 0)
	{
		document.base.src = "images/Venn Graphics/" + numCircles + " Circles/" + "empty" + numCircles + ".gif";
		loadImage(intersect.substring(0, numCircles)); // loads the intersect image of all circles as default
	}
}

function loadImage(imageID)
{
	var imageName = numCircles + imageID + ".gif";
	var picArrayIndex = 0;
	var imagesArrayIndex = -1;

	// Find the clicked image in the imageArray matrix
	for(var i = 0; i < imageArray[numCircles - 1].length; i++)
	{
		if(imageArray[numCircles - 1][i].src.indexOf(imageName) != -1)
		{
			picArrayIndex = i;
			break;
		}
	}

	// Find the position to load the image in the document.images array
	for(var i = 0; i < document.images.length; i++)
	{
		if(document.images[i].title == "VennImage" && document.images[i].name == imageID)
		{
			imagesArrayIndex = i;
			break;
		}
	}

	if(imagesArrayIndex == -1)
	{
		imagesArrayIndex = 0;
	}

	if(document.images[imagesArrayIndex].src.indexOf("empty.gif") != -1 || document.images[imagesArrayIndex].src == "")
	{
		document.images[imagesArrayIndex].src = imageArray[numCircles - 1][picArrayIndex].src;
		numSelectedSections++;
	}
	else
	{
		document.images[imagesArrayIndex].src = emptyImage.src;
		numSelectedSections--;
	}
}

function setQuery()
{
	var queryString = "";
	var simpleQueryString = "";
	var andString;
	var notString;
	var tempString;

	if(numCircles > 0 && numSelectedSections < imageArray[numCircles - 1].length)
	{
		for(var i = 0; i < document.images.length; i++)
		{
			tempString = "";
			// checking to see if image loaded in this position is the emptyImage
			if(document.images[i].title == "VennImage" && document.images[i].src.indexOf("empty") == -1 && document.images[i].src != "")
			{
				if(simpleQueryString != "")
					simpleQueryString += ",";

				andString = "";
				notString = "";
				tempString = document.images[i].src.substring(document.images[i].src.lastIndexOf("/") + 2, document.images[i].src.lastIndexOf("."));

				for(var j = 0; j < numCircles; j++)
				{
					if(tempString.indexOf(imageArray[3][j].name) != -1)
					{
						if(andString != "")
						{
							andString += " AND ";
						}

						simpleQueryString += "+";

						andString += document.queryForm.elements[j].value;
					}
					else
					{
						if(notString != "")
						{
							notString += " AND ";
						}

						simpleQueryString += "-";

						notString += "NOT " + document.queryForm.elements[j].value;
					}
				}

				tempString = andString;
				if(notString != "")
				{
					if(andString != "")
					{
						tempString += " AND ";
					}

					tempString += notString;
				}
			}

			if(tempString != "")
			{
				if(queryString != "")
					queryString += " OR ";

				queryString += tempString;
			}
		}
	}
	else
	{
		// all sections of the venn are selected, equating to an OR search of all terms
		for(var i = 0; i < numCircles; i++)
		{
			if(queryString != "")
				queryString += " OR ";

			queryString += document.queryForm.elements[i].value;

			simpleQueryString += "+";

		}
	}

	if(queryString != "")
	{
		document.getElementById("boolisticQuery").innerHTML = "Query:  " + queryString;
		document.queryForm.query.value = simpleQueryString;
	}
	else
		document.getElementById("boolisticQuery").innerHTML = "";
}

function clearImages()
{
	numSelectedSections = 0;

	for(var i = 0; i < document.images.length; i++)
	{
		if(document.images[i].alt.indexOf("Layer") != -1 || document.images[i].alt == "Base image")
		{
			// Leaves base image intact unless numCircles is 0
			if(numCircles == 0 || document.images[i].alt != "Base image")
				document.images[i].src = emptyImage.src;

			// make sure the image size is set to the correct width
			// images for 2 circles are a little wider than the rest of the sets
			// potentially causing a weird effect if not dealt with
			if(numCircles != 2)
				document.images[i].width = 150;
			else
				document.images[i].width = 170;

			document.images[i].height = 150;
		}
	}
}

function setEngineString()
{
	var engineCookieList = document.cookie.split("; ");
	var engineCookie;

	var fullEnginesList = "";
		
	for(var i = 0; i < engineCookieList.length; i++)
	{
		engineCookie = engineCookieList[i].split("=");

		if(engineCookie[0] != " JSESSIONID" && engineCookie[1] != "")
		{
			if(fullEnginesList != "")
				fullEnginesList += ";";

			fullEnginesList += engineCookieList[i];
		}
	}

	document.queryForm.engines.value = fullEnginesList;
}

function setCategory(newCategory)
{
	document.queryForm.engineCategory.value = newCategory;
}

function setRadio(index)
{
	document.queryForm.imageRadio[index].checked=true;
}

function changeCommand(newCommand)
{
	document.queryForm.command.value = newCommand;
}

function encodeTerms()
{
	var unencodedTerm;
	var encodedTerm;
	var specialCharacters = "\'\"!@#$%^&*(),.? ";

	termsEncoded = false;

	for(var i = 0; i < 4; i++)
	{
		if(document.queryForm.elements[i].value != "")
		{
			unencodedTerm = document.getElementsByName("bTerm" + (i + 1))[0];
			encodedTerm = document.getElementsByName("term" + (i + 1))[0];

			for(var j = 0; j < unencodedTerm.value.length && !termsEncoded; j++)
			{
				if(!(unencodedTerm.value.charAt(j) >= 'A' && unencodedTerm.value.charAt(j) <= 'Z') &&
					!(unencodedTerm.value.charAt(j) >= 'a' && unencodedTerm.value.charAt(j) <= 'z') &&
					!(unencodedTerm.value.charAt(j) >= '0' && unencodedTerm.value.charAt(j) <= '9'))
				{
					if(specialCharacters.indexOf(unencodedTerm.value.charAt(j)) == -1)
					{
						termsEncoded = true;
					}
				}
				
			}

			if(window.encodeURIComponent)
				encodedTerm.value = window.encodeURIComponent(unencodedTerm.value);
			else
				encodedTerm.value = unencodedTerm.value;
		}
	}
}

function submitForm(doSearch, isSideSearch, isCategoryChanged)
{
	setQuery();

	var vennSelections = "";

	for(var i = 0; i < document.images.length; i++)
	{
		if(document.images[i].title == "VennImage" && document.images[i].src.indexOf("empty.gif") == -1)
		{
			if(vennSelections != "")
				vennSelections += ",";
			else
				vennSelections = numCircles + ",";

			vennSelections += document.images[i].name;
		}
	}

	encodeTerms();

	if(!termsEncoded)
		setEngineString();
/*	else
	{
		setCategory("Internet");
		document.queryForm.engines.value = "Internet=Boolistic,Google,MSN Search,Overture,Yahoo";
	} */

	if(isSideSearch)
	{
		if(!isCategoryChanged && document.queryForm.target != "viewWindow")
		{
			document.queryForm.target = "viewWindow";
			changeCommand("setQuery, search");
		}
		else
			categoryChanged = false;

		if(termsEncoded)
		{
			document.queryForm.target = "navWindow";
			changeCommand("setQuery, loadEngines, loadPage");
			wasEncoded = false;
		}
	}

	if(document.queryForm.bTerm1.value == "" && doSearch)
	{
		alert("Please enter search terms in the text fields");
		document.queryForm.bTerm1.focus();
	}
	else
	{
		if(vennSelections == "" && doSearch)
		{
			alert("Please select a section of the Venn diagram to define your search");
		}
		else
		{
			document.queryForm.selectedSections.value = vennSelections;
			document.queryForm.submit();
		}
	}
}