/* 
NOTES:
Requires Prototype 1.6 if using to update options in a select list. IE 6/7 don't allow element.update of options in select

OBJECT: AutoAJAXSelectList: Takes a text box, monitors if you type in it and AJAX updates a results panel.

ATTRIBUTES:
textBoxObj: Text box to monitor (required)
appendObj: Where the results of the AJAX go (required)
dataApp: The address of the AJAX app (required)
hideSchoolResults: A DOM Obj that is made visible when there are results and hides otherwise
progressObj: A DOM Obj that is made visible during the AJAX call and hides otherwise
leftOffset: Offset of results box
topOffset: Offset of results box
defaultAlignment: 'right' (default), 'left' - alignment of results box.

FUNCTIONS:
reset(): Hides and clears the results panel.
*/

function AutoAJAXSchoolFinder(inputType, restrictToInsts, redirectUserTo, textBoxObj, appendObj, dataApp, hideSchoolResults, hideSchoolDisplay, hideNoSchoolFound, progressObj, leftOffset, topOffset, defaultAlignment, optimostTrackingVar) {
	this.inputType = inputType;
	this.restrictToInsts = restrictToInsts;
	this.redirectUserTo = redirectUserTo;
	this.textBoxObj = textBoxObj;
	this.appendObj = appendObj;
	this.dataApp = dataApp;
	this.hideSchoolResults = hideSchoolResults;
	this.hideSchoolDisplay = hideSchoolDisplay;
	this.hideNoSchoolFound = hideNoSchoolFound;
	this.progressObj = progressObj;
 	this.leftOffset = leftOffset;
	this.topOffset = topOffset;
	this.boxAligned = false;
	this.defaultAlignment = defaultAlignment;
	this.optimostTrackingVar = optimostTrackingVar;
	this.currentSubmissionID = 1;

	/* Start monitoring textbox and turn off autocomplete */
	this.init = function () {
		// hide what needs to be hidden at start
		this.hideSchoolResults.hide();
		this.hideSchoolDisplay.hide();
		this.hideNoSchoolFound.hide();
		this.progressObj.hide();
			
		this.textBoxObj.setAttribute("autocomplete","off");
		
		this.CachedTypeHandler = this.checkAdd.bindAsEventListener(this);
		Event.observe(this.textBoxObj, 'keyup', this.CachedTypeHandler);		
		this.CachedFocusHandler = this.focusHandler.bindAsEventListener(this);
		Event.observe(this.textBoxObj, 'focus', this.CachedFocusHandler);

		this.CachedChangeHandler = this.changeHandler.bindAsEventListener(this);
		Event.observe(this.appendObj, 'click', this.CachedChangeHandler);
	}

	/* Hides and clears results panel */
	this.reset = function () {		
		if (this.hideSchoolResults) {
			this.hideSchoolResults.hide();
		}
		
		while(this.appendObj.childNodes.length > 0) {
			this.appendObj.removeChild(this.appendObj.childNodes[0]);
		}
	}

	/* On a successful update, show results and hide progress */
	this.updateSuccess = function(responseTest) {
		currentResponse = responseTest.responseText.split('CurrentSubmissionID');
		
		if (currentResponse[0] == this.currentSubmissionID) {
		
			this.appendObj.update(currentResponse[1]);
		
			if (this.hideSchoolResults) {
				// this.alignResultsBox();
				this.hideSchoolResults.show();
			}

			if(this.progressObj) {
				this.progressObj.hide();
			}	
			
		}
	}.bind(this);
	
	/* on choosing of an option from the appendObj */
	this.changeHandler = function(event) {
		if (this.redirectUserTo == '') {
			// hide the hideSchoolResults Container
			this.hideSchoolResults.hide();
			
			// just display chosen school on the page (ie part of bigger form
			this.hideSchoolDisplay.innerHTML =  this.appendObj.options[this.appendObj.selectedIndex].innerHTML;
			this.hideSchoolDisplay.show();
		} else {
			// redirect the user
			var thePID = this.appendObj.value.toQueryParams().pid;
			document.location.href = this.redirectUserTo + "&pid=" + thePID;
		}		
	}
	
	/* On a keypress this prompts the AJAX */
	this.checkAdd = function(event) {	
		this.keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;

		if(this.keyCode == 13 || this.keyCode == 39 ) { // Keypressed is enter or tab - prevent form submit

			event.cancelBubble = true;
			event.returnValue = false;
			event.stopPropagation(); 

			return false;
			
		} else if (Event.element(event).value.length < 3) {

			this.reset();		
			
		} else if((Event.element(event).value.length) >= 3) {
		
			if(this.progressObj) {
				this.progressObj.show();
			}
			
			this.currentSubmissionID++;
			
			new Ajax.Request(this.dataApp, {
			
				method: 'get',
			
				onSuccess: this.updateSuccess,

				onFailure : function(resp) {
					alert("Oops, there's been an error.");
				},

				parameters : {
					q: Event.element(event).value,
					c: this.inputType,
					returnMode: 'options',
					restrictToInsts: this.restrictToInsts,
					currentSubmissionID: this.currentSubmissionID
				}
			
			});
			
		}

	};


	/* On first focus clear the box, then stop tracking focus. */
	this.focusHandler = function () {
	
		this.textBoxObj.value = "";
		
		Event.stopObserving(this.textBoxObj, 'focus', this.CachedFocusHandler);
	
	}

	this.init();
}



function AutoAJAXSelectList(textBoxObj, appendObj, dataApp, hideSchoolResults, progressObj, leftOffset, topOffset, defaultAlignment, optimostTrackingVar) {

	this.textBoxObj = textBoxObj;

	this.appendObj = appendObj;
	
	this.dataApp = dataApp;
	
	this.hideSchoolResults = hideSchoolResults;
	
	this.progressObj = progressObj;
	
 	this.leftOffset = leftOffset;
 	
 	this.topOffset = topOffset;
	
	this.boxAligned = false;
	
	this.defaultAlignment = defaultAlignment;
	
	this.optimostTrackingVar = optimostTrackingVar;
	
	this.currentSubmissionID = 1;

	/* Start monitoring textbox and turn off autocomplete */
	this.init = function () {
	
		this.textBoxObj.setAttribute("autocomplete","off");
		
		this.CachedTypeHandler = this.checkAdd.bindAsEventListener(this);

		Event.observe(this.textBoxObj, 'keyup', this.CachedTypeHandler);		

		this.CachedFocusHandler = this.focusHandler.bindAsEventListener(this);

		Event.observe(this.textBoxObj, 'focus', this.CachedFocusHandler);
		
	}

	/* Hides and clears results panel */
	this.reset = function () {
		
		if (this.hideSchoolResults) {
			this.hideSchoolResults.hide();
		}
		
		while(this.appendObj.childNodes.length > 0) {
			this.appendObj.removeChild(this.appendObj.childNodes[0]);
		}

	}

	/* On a successful update, show results and hide progress */
	this.updateSuccess = function(responseTest) {
		currentResponse = responseTest.responseText.split('CurrentSubmissionID');
		
		if (currentResponse[0] == this.currentSubmissionID) {

			this.appendObj.update(currentResponse[1]);
		
			if (this.hideSchoolResults) {
				this.alignResultsBox();
				this.hideSchoolResults.show();
			}

			if(this.progressObj) {
				this.progressObj.hide();
			}	
			
		}
		
	}.bind(this);

	/* On a keypress this prompts the AJAX */
	this.checkAdd = function(event) {
		this.keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;

		if(this.keyCode == 13 || this.keyCode == 39 ) { // Keypressed is enter or tab - prevent form submit

			event.cancelBubble = true;
			event.returnValue = false;
			event.stopPropagation(); 

			return false;
			
		} else if (Event.element(event).value.length < 3) {

			this.reset();		
			
		} else if((Event.element(event).value.length) >= 3) {
		
			if(this.progressObj) {
				this.progressObj.show();
			}
			
			this.currentSubmissionID++;
			
			new Ajax.Request(this.dataApp, {
			
				method: 'get',
			
				onSuccess: this.updateSuccess,

				onFailure : function(resp) {
					alert("Oops, there's been an error.");
				},

				parameters : { q: Event.element(event).value, currentSubmissionID: this.currentSubmissionID }
			
			});
			
		}

	};


	/* On first focus clear the box, then stop tracking focus. */
	this.focusHandler = function () {
	
		this.textBoxObj.value = "";
		
		Event.stopObserving(this.textBoxObj, 'focus', this.CachedFocusHandler);
	
	}

	/* This function finds the elements offset from the top left corner of the entire page, no mater what it's nested in */
	this.findPos = function(obj) {

		var curleft = curtop = 0;

		if (obj.offsetParent) {
		
			curleft = obj.offsetLeft

			curtop = obj.offsetTop

			while (obj = obj.offsetParent) {

				curleft += obj.offsetLeft

				curtop += obj.offsetTop

			}
		}

		return [curleft,curtop];

	}

	/* Force the results box to align with an offset as input, no matter what it's nested inside of */
	this.alignResultsBox = function() {
	
		if (!this.boxAligned) {

			this.hideSchoolResults.show();

			this.hideSchoolResults.style.top = this.hideSchoolResults.offsetTop - (this.findPos(this.hideSchoolResults)[1] - this.findPos(this.textBoxObj)[1]) + (this.textBoxObj.offsetHeight - 1) + this.topOffset + 'px';

			if (this.defaultAlignment == 'right') {

				this.hideSchoolResults.style.left = this.hideSchoolResults.offsetLeft - (this.findPos(this.hideSchoolResults)[0] - this.findPos(this.textBoxObj)[0]) + this.leftOffset - (this.hideSchoolResults.offsetWidth - this.textBoxObj.offsetWidth) + 'px';
			
			} else {
			
				this.hideSchoolResults.style.left = this.hideSchoolResults.offsetLeft - (this.findPos(this.hideSchoolResults)[0] - this.findPos(this.textBoxObj)[0]) + this.leftOffset + 'px';			
			
			}
			
			this.hideSchoolResults.hide();
			
			this.boxAligned = true;
			
		}
		
	}

	this.init();

}

/* Monitors an option in a select box. When it's pressed it redirects the page to the options value. Used by ProductQuickFind. */

/* function RedirectingOptionList(selectObj, dataApp) { */
function RedirectingOptionList(selectObj, RedesignMode) {

	this.selectObj = selectObj;
	
	this.dataApp = '/admin/ajax/productRedirect2.cfm?RedesignMode=' + RedesignMode;
	
	this.selectedOption = '';
	
	this.init = function () {
	
		this.CachedChangeHandler = this.changeHandler.bindAsEventListener(this);

		Event.observe(this.selectObj, 'click', this.CachedChangeHandler);
	
	}



	this.redirectByAjaxHandler = function(t) {

		document.location.href = t.responseText;

	}.bind(this);	
	
	
	

	this.changeHandler = function (event) {
		
		this.selectedOption = Event.element(event);
		
		if (this.selectedOption.value.length > 0) {
		
		
			// If result needs further processing look for the AJAX: Flag
			if (this.selectedOption.value.indexOf("AJAX:") == 0) {
				
				new Ajax.Request(this.dataApp, {
				
					method: 'get',

					onSuccess: this.redirectByAjaxHandler,

					onFailure : function(resp) {
						alert("Oops, there's been an error.");
					},

					parameters: { q: this.selectedOption.value }

				});
			
			
			} else {
		
				document.location.href = this.selectedOption.value; 			
				
			}
		
		}
		
	}

	this.init();

}


