// Select Pop
// class to provide a dynamic drop down list which will show potential matches (case insensitive)
// as a user enters characters in the text_field. 

// set up 

function select_pop(){
	select_pop.prototype._textField;
	select_pop.prototype._targetDiv;
	select_pop.prototype._selIndex;
	select_pop.prototype._dataArray;
	select_pop.prototype._currentHover;
}

select_pop.prototype.init = function init(){
		var me = this;
		this._selIndex = false;
		this.createDiv();
		this._targetDiv.style.display = 'none';
		// add listeners
		if(this._textField.addEventListener){
			this._textField.addEventListener("keyup",function(e){me.checkList(e)},false);
			//this._textField.addEventListener("blur",function(){me.hideDiv()},false);
			document.addEventListener("click",function(e){me.hideDivFromClickOut(e)},false);
		} else {
			this._textField.attachEvent("onkeyup",function(){me.checkList()},false);
			//this._textField.attachEvent("onblur",function(){me.hideDiv()});
			document.attachEvent("onclick",function(){me.hideDivFromClickOut()});
			}
		}

select_pop.prototype.hideDivFromClickOut = function hideDivFromClickOut(e){
		var targ = (!e)?window.event.srcElement:e.target;
		if(targ.id != 'suburb'){
			//alert(targ.id);
			this.hideDiv();
			}
		}

select_pop.prototype.checkList = function checkList(e){
	var me = this;
	e = (!e)?window.event:e;
	if(e.keyCode == 38 || e.keyCode == 40 || e.keyCode==13){
			this.navigateList(e.keyCode);
			return;
			} else {
			var keyword = this._textField.value;
			if(keyword.length == 0){
				this.hideDiv();
				return;
				}
			keyword = keyword.toLowerCase();
			var matched = 0;
			var theList = document.createElement('div');
			var maxMatched = 6;
			for(i in this._dataArray){
				var curroption = this._dataArray[i].toLowerCase();
				if(curroption.indexOf(keyword) >= 0 && matched < maxMatched){
					var the_text = this._dataArray[i]
					// if we have an exact match to one of the records, then set this as the current selection
					// note we only check this once as the following record might contain the exact match plus more, so will negate it
					if(keyword == the_text.toLowerCase()){
						this.hideDiv();
						return;
						}
					var list_item_text = document.createTextNode(the_text+"\n");	
					var list_li = document.createElement('li');
					var list_a = document.createElement('a');
					list_a.setAttribute('href','#');
					list_a.setAttribute('id',me._textField.name+"_sel_"+i);
					// add the onclick listener
					if(this._textField.addEventListener){
						list_a.addEventListener("mousedown",function(e){me.insertSelection(e)},false);
						} else {
						list_a.attachEvent("onmousedown",function(){me.insertSelection(e)});
						}
					// add the hover listener
					if(this._textField.addEventListener){
						list_a.addEventListener("mouseover",function(e){me.hoverOver(e)},false);
						list_a.addEventListener("mouseout",function(e){me.hoverOut(e)},false);
						} else {
						list_a.attachEvent("onmouseover",function(){me.hoverOver(e)});
						list_a.attachEvent("onmouseout",function(){me.hoverOut(e)});
						}
					list_a.appendChild(list_item_text);
					list_li.appendChild(list_a);
					theList.appendChild(list_li);			
					matched ++;	
					}
				}
			if(matched > 0){
				// if there are any matches, write them into the display
				// and make the display visible
				this._targetDiv.childNodes[0].parentNode.replaceChild(theList,this._targetDiv.childNodes[0]);
				this._targetDiv.style.display = 'block';
				if(isExplorer6()){
					document.getElementById('ie6fixpopdiv').style.display = 'block';
					}
				} else {
				// otherwise hide it and put a value of "new" in the id field
				this.hideDiv();
			}
		}
	}
		
select_pop.prototype.insertSelection = function insertSelection(e){
	if(window.event){
		var e = window.event;
		var sel = e.srcElement.childNodes[0].nodeValue;
		} else {
		var sel = e.target.childNodes[0].nodeValue;
		}
	this._textField.value = sel;
	this.hideDiv();
	}
		
select_pop.prototype.hoverOver = function hoverOver(e){
		this._currentHover = (window.event)?window.event.srcElement.parentNode:e.target.parentNode;
		this._currentHover.className = 'sel_pop_selected';
		//alert(this._currentHover);
		if(this._selIndex !== false){
			this._targetDiv.childNodes[0].childNodes[this._selIndex].className = '';	
			this._selIndex = false;
			}
	}
select_pop.prototype.hoverOut = function hoverOut(e){
		this._currentHover = (window.event)?window.event.srcElement.parentNode:e.target.parentNode;
		this._currentHover.className = '';
	}


select_pop.prototype.createDiv = function createDiv(){
		this._targetDiv = document.createElement('div');
		this._targetDiv.className = 'sel_pop';
		var span = document.createElement('span');
		this._targetDiv.appendChild(span);
		this._textField.parentNode.appendChild(this._targetDiv);
		// set the width of the div to the width of the text field
		if(this._targetDiv.currentStyle){
			var width = parseInt(this._textField.currentStyle['paddingLeft']);
			width +=  parseInt(this._textField.currentStyle['paddingRight']);
			width +=  parseInt(this._textField.currentStyle['borderRightWidth']);
			width +=  parseInt(this._textField.currentStyle['borderLeftWidth']);
			} else {
			var width = parseInt(getComputedStyle(this._textField,'').paddingLeft);
			width += parseInt(getComputedStyle(this._textField,'').paddingRight);
			width += parseInt(getComputedStyle(this._textField,'').borderRightWidth);
			width += parseInt(getComputedStyle(this._textField,'').borderLeftWidth);
			}
		
		width += parseInt(this._textField.style.width);
		this._targetDiv.style.width = width + "px";
		this._targetDiv.style.zIndex = '1000';
		// offset the left by text fields prev sibling
		this._targetDiv.style.marginLeft = this._textField.previousSibling.style.width;
		if(isExplorer6()){ // fix the ie6 'behind the select boxes' bug
			var iFrame = document.createElement("IFRAME");
			iFrame.setAttribute("src", "");
			iFrame.setAttribute("id", "ie6fixpopdiv");
			//Match IFrame position with divPopup
			iFrame.style.position = "absolute";
			iFrame.style.width = width + "px";
			// height needs to be dynamic, but I've hard coded for now. ie6 shits me. really bad.
			iFrame.style.height = '100px';	
			iFrame.style.zIndex = '999';
			iFrame.style.display = 'none';
			var xy = findPos(this._textField);
			iFrame.style.left = xy[0];
			iFrame.style.top = xy[1];
			document.getElementById('masthead').appendChild(iFrame);
			}

		}
		

select_pop.prototype.hideDiv = function hideDiv(){
		this._targetDiv.style.display = 'none';
		this._selIndex = false;
		if(isExplorer6()){
			document.getElementById('ie6fixpopdiv').style.display = 'none';
			}
		}

select_pop.prototype.navigateList = function navigateList(kc){
		if(this._targetDiv.style.display == 'none'){
			return;	
			}
		// capture an enter event first
		if(kc == 13){
			if(this._selIndex !== false){
				var sel = this._targetDiv.childNodes[0].childNodes[this._selIndex].childNodes[0].childNodes[0].nodeValue;
				this._textField.value = sel;
				this.hideDiv();
				}
			get_num_results.getResults(); // had to add this in for ie, as it was not firing the onchange event
			return false;	
			}
		
		var dir = (kc == 38)?'up':'dn';
		// first check if the mouse is hovering over an element, if so unhighlight that element
		if(this._currentHover){
			this._currentHover.className = '';
			}
		// get number of items in the option list
		var tot = this._targetDiv.childNodes[0].childNodes.length;
		// if no _selIndex, got to start if down pressed, go to end if up pressed
		if(this._selIndex===false){
			this._selIndex = (dir == 'up')?tot-1:0;
			} else {
			this._targetDiv.childNodes[0].childNodes[this._selIndex].className = '';

			if(dir == 'up'){
				this._selIndex -= 1;
			} else {
				this._selIndex += 1;
			}
			
			if(this._selIndex == tot){
				this._selIndex = 0;	
				}
			if(this._selIndex < 0){
				this._selIndex = tot-1;	
				}
			}
		// now we have selection, hilite it
		this._targetDiv.childNodes[0].childNodes[this._selIndex].className = 'sel_pop_selected';
		return false;
	}

function curry (fn, scope) {
    var scope = scope || window;
    var args = [];
    for (var i=2, len = arguments.length; i < len; ++i) {
        args.push(arguments[i]);
    };
    return function() {
	    fn.apply(scope, args);
    };
}

function isExplorer6() {
	var appVer = navigator.appVersion;
	appVer = appVer.split(';');
	if(appVer[1] == ' MSIE 6.0') {
		return true;
	}				
}


// function to find position of object
function findPos(obj) {
	var curleft = 0; //obj.offsetWidth;
	var curtop = obj.offsetHeight;
	if (obj.offsetParent) {
		curleft += obj.offsetLeft;
		curtop += obj.offsetTop;
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop;
		}
	}
	//alert([curleft,curtop])
	curleft -= (nav == 'ie')?10:0; // explorer fudge for li based menus
	return [curleft,curtop];
}
