
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.png'/>
	</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>

	*/
	init: function(elem) {
		var bSkipBlur = false;
		var bMouseOverDropDown = 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.attr('value');
		var defaultName = nameField.attr('value');

		//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');

		//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 bUiMouseoverEvent = false;

		var attachUIMouseOverEvent = function() {
			if (bUiMouseoverEvent == false) {
				$j('.ui-autocomplete-results-with-magnifier').mouseover(function() {
					bMouseOverDropDown = true;
				});
				$j('.ui-autocomplete-results-with-magnifier').mouseout(function() {
					bMouseOverDropDown = false;
				});
				bUiMouseoverEvent = true;
			}
		}

		var ajaxAvailable = Ajax.ajaxAvailable();
		if (ajaxAvailable) {
			var resultsClass = "ui-autocomplete-results";

			if (elem.hasClass("withMagnifier")) {
				resultsClass = "ui-autocomplete-results-with-magnifier";
			}
			nameField.autocomplete({
				addnew: addnew ? addnew : 0,
				resultsClass: resultsClass,
				minChars: minChars ? minChars : 0,
				delay: delay ? parseInt(delay) : 1000,
				highlight: false,
				matchContains: false,
				selectFirst: true,
				mustMatch: false,
				width: width ? width : 300,
				cacheLength: ddlength ? ddlength : 10,
				formatMatch: function(data) {
					return data["0"];
				},
				formatItem: function(data) {
					attachUIMouseOverEvent();
					return data["0"];
				},
				formatResult: function(data) {
					return data["0"];
				},

				//use hardcoded timecard.dll for now. url  DocumentData.isapiName is not ready yet in testing global case
				url: "timecard.dll" + '?GetData' + '&' + $j.param({
					tokenid: 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
				})
			}).autocomplete('result', function(event, data, formatted) {
				bSkipBlur = true;
				bMouseOverDropDown = 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.attr('value', name);
					//set default id value due to the selection has been made
					defaultName = name;

					var id = data['1'];
					if (id) {
						idField.attr('value', 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) {
					//						bMouseOverDropDown = true;
					return AutoComplete.checkIfNeedModalConfirm(idField, nameField, fieldDisplayName, defaultId, defaultName);
				}

				if (DataKeyPressed(event.keyCode)) {
					idField.attr('value', "-1");
					//defaultName = nameField.attr('value');
					defaultId = "-1";
					bSkipBlur = false;
					bMouseOverDropDown = false;
				}
			});
		}

		$j('.autoCompleteDropDown', elem).click(function() {
			bSkipBlur = true;
			bMouseOverDropDown = 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.attr('value');
			nameField.attr('value', '');
			nameField.autocomplete("show");
			nameField.attr('value', temp);
			setDelayedFocus(nameField, { select: true });

		});

		$j('.autoCompleteMagnifier', elem).click(function() {
			$j('.autoCompleteField', elem).select();
		});

		elem.mouseover(function() {
			bMouseOverDropDown = true;
			//			if (addnew == "1") {
			//only make addnew available when
			//				$j('.quickAddSpan').show();
			//			}
		});
		elem.mouseout(function() {
			bMouseOverDropDown = false;
			//			if (addnew == "1") {
			//				$j('.quickAddSpan').hide();
			//			}
		});
		nameField.focus(function() {
			$j('.dropDown_default', elem).removeClass("dropDown_default").addClass("dropDown_default_focus");
			$j('.autoCompleteMagnifier', elem).removeClass("autoCompleteMagnifier").addClass("autoCompleteMagnifier_focus");
			$j('.autoCompleteField', elem).addClass("autoCompleteField_focus");
			$j('.autoCompleteFieldAlone', elem).addClass("autoCompleteFieldAlone_focus");
			bMouseOverDropDown = true;
		});

		nameField.blur(function(event) {
			$j('.dropDown_default_focus', elem).removeClass("dropDown_default_focus").addClass("dropDown_default");
			$j('.autoCompleteMagnifier_focus', elem).removeClass("autoCompleteMagnifier_focus").addClass("autoCompleteMagnifier");
			$j('.autoCompleteField', elem).removeClass("autoCompleteField_focus");
			$j('.autoCompleteFieldAlone', elem).removeClass("autoCompleteFieldAlone_focus");

			if (idField.attr('value') == defaultId && nameField.attr('value') == defaultName) {
				return;
			}
			if (bSkipBlur == true)
				return;
			//if it is mouse down or it is arrow down
			if (bMouseOverDropDown || event.keyCode == '40') {
				//				bMouseOverDropDown = true;
				return;
			}
			AutoComplete.checkIfNeedModalConfirm(idField, nameField, fieldDisplayName, defaultId, defaultName);
		});
	},

	checkIfNeedModalConfirm: function(idField, nameField, fieldDisplayName, defaultId, defaultName) {
		if (idField.attr('value') != '-1')
			return true;

		var message = "";
		var title = "";
		if (nameField.attr('value') != "") {
			message = "<b>" + nameField.attr('value') + "</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.attr('value');
				nameField.attr('value', '');
				nameField.autocomplete("show");
				//				focusElement.attr('value', temp);
				idField.attr('value', defaultId);
				nameField.attr('value', 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.attr('value', idBeforeQuickAdd);
					nameField.attr('value', valueBeforeQuickAdd.replace(/&apos;/gi, "'"));
					nameField.select();
					bMouseOverDropDown = 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.autocomplete('flushCache');

									// set value in dropdown idField and nameField
									idField.attr('value', obj['0']);
									nameField.attr('value', obj['1']);

								} else {
									idField.attr('value', idBeforeQuickAdd);
									nameField.attr('value', 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: false,
				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;
}
