﻿var IGTooltipTextBox = Class.create();
IGTooltipTextBox.prototype = {
	initialize: function(controlId, text, clearOnChange, linkedTooltipTextBoxArray) {
		// if clearOnChange is true, the label will be cleared when
		// text is typed as opposed to focus of the text box.
		this.clearOnChange = clearOnChange; 
		
		this.text = text;
		this.textBox = document.getElementById(controlId);
		this.textBox.onblur = this.setTextWithCheck.bind(this);
		if (!this.clearOnChange) this.textBox.onfocus = this.clear.bind(this);
		else {
			this.textBox.onkeypress = this.clear.bind(this);
			this.textBox.onfocus = this.wireUpCheck.bind(this);
		}
		this.label = document.createElement("label");
		
		// use the linked array (which contains IGTooltipTextBox objects
		// to check to clear other tooltips when this IGTooltipTextBox is
		// cleared (like a username/password combo).
		this.linkedTooltipTextBoxArray = linkedTooltipTextBoxArray;
		
		// use window.onload to wire up initial set to allow form
		// auto-population to be done in the browser.
		Event.observe(window, "load", this.initTooltip.bind(this));
	},
	initTooltip: function() {
		var textPos = Element.cumulativeOffset(this.textBox);
		
		this.label.setAttribute("for", this.textBox.id);
		this.label.innerHTML = this.text;
		this.label.style.display = "none";
		this.label.style.position = "absolute";
		this.label.style.top = textPos.top + "px";
		this.label.style.left = textPos.left + "px";
		this.label.style.padding = "3px 5px";
		this.label.style.fontStyle = "italic";
		this.label.style.color = "#A8A8A8";
		this.label.style.zIndex = "9999";
		document.body.appendChild(this.label);
		
		// check if the focus was given before this loaded
		if (!this.clearOnChange 
			&& document.activeElement 
			&& document.activeElement.id == this.textBox.id)
			this.clear();
		else
			this.setTextWithCheck();	
	},
	clear: function() {
		this.label.style.display = "none";
		
		if (this.linkedTooltipTextBoxArray != null && this.linkedTooltipTextBoxArray.length > 0) {
			for(i=0;i<this.linkedTooltipTextBoxArray.length;i++)
				this.linkedTooltipTextBoxArray[i].setTextWithCheck();
		}
	},
	setTextWithCheck: function() {
		if (this.textBox.value == null || this.textBox.value == '') {
			this.label.style.display = "block";
		} else {
			this.clear();
		}
	},
	wireUpCheck: function() {
		if (document.activeElement && document.activeElement.id == this.textBox.id) {	
			if (this.textBox.value != null && this.textBox.value != '') {
				this.clear();
			} else {
				obj = this;
				setTimeout(function(){obj.wireUpCheck.call(obj)}, 250);		
			}
		}
	}
};