// the current object of AJAXUserSearchConstr
var CURRENT_OBJECT = null;
var TEMP_REF = null;

/**
 * the constructor for the AJAX user search
 *
 * @param string root the root-path
 * @param string inputId the id of the input-field
 * @param string resultId the id of the result-div-area
 * @param string waitId the id of the wait-cursor
 * @param string actionParam the action-parameter-name
 * @param string matchText the text to display at the beginning of the matches
 * @param string linkClass the the class for the username-links
 * @param boolean multiple is it allowed to enter more than one username?
 * @param boolean quotesAllowed are quotes (") allowed?
 * @param string separator the separator for multiple usernames
 */
function AJAXUserSearchConstr(root,inputId,resultId,waitId,actionParam,matchText,
							  linkClass,multiple,quotesAllowed,separator)
{
	this.lastKeyword = '';
	this.root = root;
	this.inputId = inputId;
	this.resultId = resultId;
	this.waitId = waitId;
	this.matchText = matchText;
	this.XMLHTTP = null;
	this.actionParam = actionParam;
	
	if(typeof linkClass == "undefined")
		linkClass = 'bs_main';
	this.linkClass = linkClass;
	
	if(typeof multiple == "undefined")
		multiple = true;
	this.multiple = multiple;

	if(typeof quotesAllowed == "undefined")
		quotesAllowed = true;
	this.quotesAllowed = quotesAllowed;
	
	if(typeof separator == "undefined")
		separator = ' ';
	this.separator = separator;
	
	this.foundUser = new Array();
	
	// methods
	this.displayWaitCursor = displayWaitCursor;
	this.hideWaitCursor = hideWaitCursor;
	this.findMatchingUser = findMatchingUser;
	this.displayFoundUser = displayFoundUser;
}

/**
 * determines the entered username to search for
 * and sends the HTTP-request
 */
function findMatchingUser()
{
	var field = document.getElementById(this.inputId);
	if(field.value == '')
		return;
	
	// determine start-position
	var start = 0;
	if(this.multiple)
	{
		if(this.quotesAllowed && substr_count(field.value,'"') % 2 == 1)
			start = field.value.lastIndexOf('"');
		else
			start = field.value.lastIndexOf(this.separator);
		
		if(start < 0)
			start = 0;
		else
			start++;
	}
	
	var keyword = field.value.substring(start);
	keyword = trim(keyword);
	
	// don't fire the request again if the keyword is the same
	if(keyword == this.lastKeyword)
		return;
	
	this.lastKeyword = keyword;
	this.displayWaitCursor();
	
	this.XMLHTTP = getXmlHttpObject();
	TEMP_REF = this; // very bad, but works :)
	var callback = function() {
		try
		{
			// are we ready?
			if(TEMP_REF.XMLHTTP.readyState == 4 || TEMP_REF.XMLHTTP.readyState == "complete")
			{
				// so display the result
				xmlHttpIsBusy = false;
				TEMP_REF.displayFoundUser(TEMP_REF.XMLHTTP.responseText);
				TEMP_REF.hideWaitCursor();
			}
		}
		catch(e)
		{
			
		}
		
		delete TEMP_REF;
	};
	
	// send our request
	var url = this.root + "standalone.php?" + TEMP_REF.actionParam + "=ajax_check_user&kw=" + keyword;
	sendHTTPRequest(this.XMLHTTP,url,callback);
}

/**
 * displays the wait-cursor
 */
function displayWaitCursor()
{
	var wait = document.getElementById(this.waitId);
	var inputField = document.getElementById(this.inputId);
	var resultField = document.getElementById(this.resultId);
	var fieldLeft = getPageOffsetLeft(inputField);
	var fieldTop = getPageOffsetTop(inputField);
	
	// set position of the element
	wait.style.left = (fieldLeft - (parseInt(wait.style.width) + parseInt(wait.style.padding) * 2 + 4)) + "px";
	wait.style.top = (fieldTop - 10 - inputField.offsetHeight) + "px";
	wait.style.display = 'block';
}

/**
 * hides the wait-cursor
 */
function hideWaitCursor()
{
	document.getElementById(this.waitId).style.display = 'none';
}

/**
 * displays the found user
 */
function displayFoundUser(text)
{
	var inputField = document.getElementById(this.inputId);
	var resultField = document.getElementById(this.resultId);
	var fieldLeft = getPageOffsetLeft(inputField);
	var fieldTop = getPageOffsetTop(inputField);
	
	// set position of the element
	resultField.style.left = fieldLeft + "px";
	resultField.style.top = (fieldTop - 10 - inputField.offsetHeight) + "px";
	
	// generate the string with the user
	this.foundUser = new Array();
	var result = text;
	var resParts = result.split(',');
	var resStr = '';
	for(var i = 0;i < resParts.length;i++)
	{
		if(resParts[i] == '...')
			resStr += resParts[i];
		else
		{
			// store the user in an array for later access
			this.foundUser[i] = resParts[i];
			resStr += '<a class="' + this.linkClass + '" href="javascript:addUserToField(\'' + this.inputId;
			resStr += '\',\'' + this.resultId + '\',' + this.multiple + ',\'' + this.separator;
			resStr += '\',' + this.quotesAllowed + ',\'' + resParts[i] + '\');">';
			resStr += resParts[i] + '</a>';
		}
		
		// add comma?
		if(i < resParts.length - 1)
			resStr += ', ';
	}
	
	if(resParts.length == 0)
		resStr = '&nbsp;-&nbsp;';
	
	// add the close-image
	resStr += '<img src="' + this.root + 'images/delete.gif" alt=""';
	resStr += ' style="padding-left: 5px;" onmouseover="this.style.cursor = \'pointer\';"';
	resStr += ' onmouseout="this.style.cursor = \'default\';" onclick="hideResults(\'';
	resStr += this.resultId + '\');" />';
	
	resultField.innerHTML = this.matchText + ': ' + resStr;
	
	// finally display the element
	resultField.style.display = 'block';
}

/**
 * adds the given username to the specified input-field
 *
 * @param string inputId the input-Id
 * @param string resultId the id of the result-element
 * @param boolean multiple use multiple usernames?
 * @param boolean quotesAllowed are quotes (") allowed?
 * @param string separator the separator for multiple usernames
 * @param string username the username to add
 */
function addUserToField(inputId,resultId,multiple,separator,quotesAllowed,username)
{
	if(!username)
		return;
	
 	var field = document.getElementById(inputId);
 	var usedAlt = false;
 	var start = 0;
 	if(multiple)
 	{
	 	var start = field.value.lastIndexOf(separator);
	 	var altStart = -1;
	 	if(quotesAllowed)
	 	{
		 	altStart = field.value.lastIndexOf('"') + 1;
		 	if(altStart > start)
		 		usedAlt = true;
		}
	 	
	 	start = Math.max(altStart,start);
	 	if(start < 0)
	 		start = 0;
 	}
 	
	field.value = field.value.substring(0,start);
	if(start > 0 && !usedAlt && multiple)
		field.value += separator;
	field.value += username;
	
	document.getElementById(resultId).style.display = 'none';
}

/**
 * hides the div-area with the results
 *
 * @param string resultId the id of the result-element
 */
function hideResults(resultId)
{
	document.getElementById(resultId).style.display = 'none';
	document.getElementById('wait_symbol').style.display = 'none';
}

/**
 * catches the keyup-event
 *
 * @param event pEvent the event-parameter
 */
function keyUp(pEvent)
{
  if(!pEvent)
    pEvent = window.event;
  
  var key = -1;
  if(pEvent.which)
    key = pEvent.which;
  else if(pEvent.keyCode)
    key = pEvent.keyCode;

  // typed in our input-field?
  if(CURRENT_OBJECT != null)
  {
 	// strg + space for autocompletion
  	if(key == 32 && pEvent.ctrlKey)
  	{
		addUserToField(CURRENT_OBJECT.inputId,CURRENT_OBJECT.resultId,
									 CURRENT_OBJECT.multiple,CURRENT_OBJECT.separator,
									 CURRENT_OBJECT.quotesAllowed,CURRENT_OBJECT.foundUser[0]);
  	}
  	// escape to close matches
  	else if(key == 27)
  		hideResults(CURRENT_OBJECT.resultId);
  }
}

document.onkeyup = keyUp;
