
var AutoComplete = {

	/*	//template format of autocomplete
	//with id, type=2 means two column, which is id and name.
	<div class="autoComplete" Command="List" type="2" table="CreditCardBank" field="Name" ddlength="25" filter="Active = 1" user="false" delay="300">
	<input type='hidden' name='id' class='autoCompleteId' value='-1'/><span class='field'/> 
	<input class='autoCompleteField' name='name' title='type Name' type='text' size='20' tabindex='1'/>
	<a class='autoCompleteDropDown icon'>
	<img class='icon dropDown_default' title='Select dropdown' src='assets/images/icon_dropdown_default.gif'/>
	</a>
	</div>

	//without Id
	<span class="autoComplete" Command="List" type="1" table="ExpenseLine" field="City"  ddlength="10" filter="" user="true" delay="300" width="148">
	<INPUT NAME="city" class='city autoCompleteField' TYPE="text" SIZE="25" MAXLENGTH="50" VALUE="" class='fill' onKeyUp="oku_dirty(event, this);" onChange="inputChanged(this);">
	</span>

	*/
	sending: false,
	init: function(elem) {
		var bSkipBlur = false;
		var mousein = false;

		// dataRowPattern should depend on the how many inputs in the div
		var idField = $j('.autoCompleteId', elem);
		var nameField = $j('.autoCompleteField', elem);
		var command = elem.attr('command');

		//default value of elem
		var defaultId = idField.val();
		var defaultName = nameField.val();

		//fileds that used by sql query
		//CString type, table, field, ddlength, filter, user;
		var fieldDisplayName = elem.attr('name');
		var type = elem.attr('type');
		var table = elem.attr('table');
		var field = elem.attr('field');
		var ddlength = elem.attr('ddlength');
		var filter = elem.attr('filter');
		var user = elem.attr('user');
		var addnew = elem.attr('addnew');
		var addblank = elem.attr('addblank');
		var selectfirst = elem.attr('selectfirst');

		//fileds that used by autocomplete UI
		var delay = elem.attr('delay');
		var minChars = elem.attr('minChars');
		//width is always the size of the input - 2 (left and right border, 1 each)
		var width = elem.attr('width');

		var resultsClass = "ac_results";

		if (elem.hasClass("withMagnifier")) {
			resultsClass = "ui-autocomplete-results-with-magnifier";
		}

		var bUiMouseoverEvent = false;

		var attachUIMouseOverEvent = function() {
			//for ie only. there is a problem that if we clicked the scroll bar, the screen won't disappear when out focus
			$j('.' + resultsClass).blur(function() {
				$j('.' + resultsClass).hide();
				//return false; //no false here. it might happen that the highlight is still on screen
			});

			if (bUiMouseoverEvent == false) {
				$j('.' + resultsClass).mouseover(function() {
					mousein = true;
				});
				$j('.' + resultsClass).mouseout(function() {
					mousein = false;
				});
				bUiMouseoverEvent = true;
			}
			return false;
		}

		var ajaxAvailable = Ajax.ajaxAvailable();

		$j('.autoCompleteDropDown', elem).click(function() {
			bSkipBlur = true;
			mousein = true;
			//if no ajax, disable autocomplete drop down
			if (!ajaxAvailable) {
				var fieldTitle = $j('.dropDown_default', this).attr('title');
				if (fieldTitle == "")
					fieldTitle = "this feature";
				else
					fieldTitle = "\"" + fieldTitle + "\"";
				modalAlert("Your browser does not currently support Ajax.",
					"To enable Ajax, please verify the following settings:<br/><br/>" +
					"<ul>" +
					"<li>Trusted sites contains " + 'http://' + window.location.hostname + "</li>" +
					"<li>The internet security setting for this zone is set to enable \"Run ActiveX controls and plug-ins\", or</li>" +
					"<li>The Advanced tab of Internet Options has the setting \"Enable native XMLHTTP support\" checked.\n\n</li>" +
					"</ul><br/>If you need assistance with these settings, or are still having difficulty, please contact your<br/>" +
					"Company IT Department and/or your Virtual Time+Expense administrator.",
					{ cssClass: 'message_box info' });
				return false;
			}
			// Note this is not an anchor element to prevent it from getting focus, which will prevent autocomplete from
			//  being able to open when it's clicked. For accessibility, if using the keyboard, this button is superfluous, 
			//  and really should be considered part of the input control.
			// Blank out and open up the autocomplete menu

			//first set the nameField value empty and then set it back after autocomplete long list all showed
			//this is to help user to still keep its current value when browsing other dropdown options			
			var temp = nameField.val();
			nameField.val('');
			nameField.display();
			nameField.val(temp);
			setDelayedFocus(nameField, { select: true });

		});

		$j('.autoCompleteMagnifier', elem).click(function() {
			$j('.autoCompleteField', elem).select();
			return;
		});

		elem.mouseenter(function() {
			mousein = true;
			return;
		});
		elem.mouseleave(function() {
			mousein = false;
			return;
		});

		if (!ajaxAvailable)
			return false;

		//use hardcoded timecard.dll for now. url  DocumentData.isapiName is not ready yet in testing global case
		var url = "timecard.dll" + '?GetData' + '&' + $j.param({
			tokenid: window.DocumentData.tokenid,
			//			need more security inputs here, userid, expenseuserid etc.
			//					eid: DocumentData.eid,
			//					userid: DocumentData.expenseuserid,
			command: command,
			type: type,
			table: table,
			field: field,
			ddlength: ddlength,
			filter: filter,
			user: user
		});

		nameField.autocomplete(url, {
			addblank: addblank != undefined ? addblank : true,
			addnew: addnew ? addnew : 0,
			resultsClass: resultsClass,
			minChars: minChars ? minChars : 0,
			delay: delay ? parseInt(delay) : 1000,
			scroll: true,
			highlight: false,
			matchContains: false,
			selectFirst: selectfirst != undefined ? selectfirst : true,
			mustMatch: false,
			width: width ? width : 300,
			cacheLength: ddlength ? ddlength : 10,
			attachedToInput: false,
			formatMatch: function(data) {
				return data[0];
			},
			formatItem: function(data) {
				attachUIMouseOverEvent();
				return data[0];
			},
			formatResult: function(data) {
				return data[0];
			}
		}).result(function(event, data, formatted) {
			bSkipBlur = true;
			mousein = true;
			//from server, 0 always be the data to display, which is name
			//1 always be the id of the data. in some case, it might not have id
			if (data != undefined) {
				//data[1] == -2 means select quick add column
				if (data[1] == "-2") {
					//we need default one so quick add when cancel the field wouldn't be set to the empty value of quick add
					AutoComplete.quickAddLinkClicked(elem, defaultId, defaultName);
					return;
				}
				var name = data[0];
				nameField.val(name.replace(/&nbsp;/gi, ""));//make sure &nbsp; is not showing.
				//set default id value due to the selection has been made
				defaultName = name;

				var id = data[1];
				if (id) {
					idField.val(id);
					//set default id value due to the selection
					defaultId = id;
				}
				return name;
			}
			return "";
		}).keydown(function(event) {
			//special case for tab and enter
			//if we have a good input then allow tab and enter
			if (event.keyCode == 9 || event.keyCode == 13) {
				//						mousein = true;
				return AutoComplete.checkIfNeedModalConfirm(idField, nameField, fieldDisplayName, defaultId, defaultName);
			}
			if (event.ctrlKey || event.altKey) {
				return;
			}
			if (DataKeyPressed(event.keyCode)) {
				idField.val("-1");
				//defaultName = nameField.val();
				defaultId = "-1";
				bSkipBlur = false;
				mousein = false;
				return true;
			}
			//continue with other keydowns.
			return;
		})/* not needed here. keydown should covered all the change event
		.change(function() {
			idField.val("-1");
			//defaultName = nameField.val();
			defaultId = "-1";
			bSkipBlur = false;
			mousein = false;
			return true;
		})*/.focus(function() {
			$j('.dropDown_default', elem).removeClass("dropDown_default").addClass("dropDown_default_focus");
			$j('.autoCompleteMagnifier', elem).removeClass("autoCompleteMagnifier").addClass("autoCompleteMagnifier_focus");
			nameField.addClass("autoCompleteField_focus");
			$j('.autoCompleteFieldAlone', elem).addClass("autoCompleteFieldAlone_focus");
			mousein = true;
			return false;
		}).blur(function() {
			$j('.dropDown_default_focus', elem).removeClass("dropDown_default_focus").addClass("dropDown_default");
			$j('.autoCompleteMagnifier_focus', elem).removeClass("autoCompleteMagnifier_focus").addClass("autoCompleteMagnifier");
			nameField.removeClass("autoCompleteField_focus");
			$j('.autoCompleteFieldAlone', elem).removeClass("autoCompleteFieldAlone_focus");

			if (idField.val() == defaultId && nameField.val() == defaultName) {
				return false;
			}
			if (bSkipBlur == true) {
				nameField.focus();
				return false;
			}
			//if it is mouse down or it is arrow down
			if (mousein || event.keyCode == '40') {
				//				mousein = true;
				nameField.focus();
				return false;
			}
			mousein = false;
			AutoComplete.checkIfNeedModalConfirm(idField, nameField, fieldDisplayName, defaultId, defaultName);
			return false;
		});

		return;
	},

	checkIfNeedModalConfirm: function(idField, nameField, fieldDisplayName, defaultId, defaultName) {
		if (idField.val() != '-1')
			return true;

		var message = "";
		var title = "";
		if (nameField.val() != "") {
			message = "<b>" + nameField.val() + "</b> is an incorrect value for the " + "<b>" + fieldDisplayName + "</b> field";
			AutoComplete.modalConfirmWithSetFocus(title, message, idField, nameField, defaultId, defaultName);
			//if open modal then stop the event
			return false;
		}
		return true;
	},

	modalConfirmWithSetFocus: function(title, message, idField, nameField, defaultId, defaultName) {
		modalAlert(title, message, {
			onOk: function() {
				//				var temp = focusElement.val();
				nameField.val('');
				nameField.display();
				//				focusElement.val(temp);
				idField.val(defaultId);
				nameField.val(defaultName);
				setDelayedFocus(nameField, { select: true });
				$j.modal.close();
			}
		});
	},

	quickAddLinkClicked: function(elem, idBeforeQuickAdd, valueBeforeQuickAdd) {
		var idField = $j('.autoCompleteId', elem);
		var nameField = $j('.autoCompleteField', elem);
		var table = elem.attr('table');
		var field = elem.attr('field');
		var ddlength = elem.attr('ddlength');
		var filter = elem.attr('filter');
		var ajaxOptions = {};

		if (Ajax.ajaxAvailable()) {
			//if it is regular ajax available, do following

			ajaxOptions.afterReplaceElements = function(dialogElem, options) {
				$j('thead', $j('.admin_data_edit.primary', dialogElem)).hide();
				var dialogCloseEvent = function() {
					idField.val(idBeforeQuickAdd);
					nameField.val(valueBeforeQuickAdd.replace(/&apos;/gi, "'"));
					nameField.select();
					mousein = true;
				};

				$j('.quickaddcancel', dialogElem).click(function() {
					dialogCloseEvent();
					$j.modal.close();
				});

				var dialogAjaxSubmit = function() {
					$j('.quickadd_flash_box', dialogElem).hide();

					var form = dialogElem.find('form#editForm');

					var afterOnComplete = function(xhr, textStatus) {
						if (textStatus == 'success') {
							if (xhr.responseText != '') {
								var obj = eval(xhr.responseText);
								//check if quick add success added
								if (obj != "fail") {
									//flush autocomplete cache so the newer succesfully added field would show up on the dropdown if user clicked again
									nameField.flushCache();

									// set value in dropdown idField and nameField
									idField.val(obj['0']);
									nameField.val(obj['1']);

								} else {
									idField.val(idBeforeQuickAdd);
									nameField.val(valueBeforeQuickAdd);
								}
								if (obj != "fail") {
									$j.modal.close();
								}
							}

						}
					};
					//hack for now, so always use quick add
					$j('#operation', dialogElem)[0].value = "Quick Add";

					var ajaxQuickAddOptions = {
						modalInProgress: false,
						url: DocumentData.isapiName + '?SaveAdminData&',
						data: form.serialize(true),
						afterOnComplete: afterOnComplete
					};
					Ajax.send(ajaxQuickAddOptions);
					return false; // Ajax successful
				}
				dialogElem.keydown(function(event) {
					if (event.keyCode == '13') {
						dialogAjaxSubmit();
						return false;
					}
				});

				$j('.quickaddsubmit', dialogElem).click(function() {
					dialogAjaxSubmit();
				});

				bindAutoCompletes(dialogElem);
			};

			Popup.ajaxSend(elem, $j.extend(ajaxOptions, {
				hasCloseButton: true,
				shrinkToContents: true,
				fill: true,
				height: 0.95,
				width: 0.95,
				widthPadding: 10,
				title: 'Quick Add ' + table,
				table: table,
				url: DocumentData.isapiName + '?QuickAdd&' + $j.param({
					tokenid: DocumentData.tokenid,
					dataname: table,
					filter: filter
				})
			}));
		} else {
			//if no ajax available, redirect to:
			//example: http://localhost/vt/timecard.dll?Admin&tokenid=vte&command=Edit&data=Project&item=-1
			var url = DocumentData.isapiName + '?Admin&' + $j.param({
				tokenid: DocumentData.tokenid,
				command: "Edit",
				data: table,
				item: "-1"
			});
			window.open(url);
		}
		return;
	}
}

function quickadd_displayFlash(message, options) {

	var quickadd_flash_box = $j('#quickadd_flash_box');
	if (quickadd_flash_box.length != 0) {
		var quickadd_message_box = quickadd_flash_box.is('.quickadd_message_box') ? quickadd_flash_box : $j('.quickadd_message_box', quickadd_flash_box);
		var quickadd_flash_message = $j('#quickadd_flash_message');

		quickadd_message_box.removeClass('info attention error success icon_32_info icon_32_attention icon_32_error icon_32_success');
		if (options && options.cssClass) {
			//flash_box.addClass('message_box ' + options.cssClass);
			quickadd_message_box.addClass(options.cssClass);
			if (options.cssClass.match(/info/)) quickadd_message_box.addClass('icon_32_info');
			else if (options.cssClass.match(/attention/)) quickadd_message_box.addClass('icon_32_attention');
			else if (options.cssClass.match(/error/)) quickadd_message_box.addClass('icon_32_error');
			else if (options.cssClass.match(/success/)) quickadd_message_box.addClass('icon_32_success');
		}
		if (options && options.header)
			quickadd_flash_message.html("<h1>" + options.header + "</h1>");
		quickadd_flash_message.append(message);

		quickadd_flash_box.show();

		//if ($j.isFunction(window.pngfix)) {
		//	pngfix(quickadd_flash_box); // IE6 only
		//}
		return true;
	}
	return false;
}

