// DOM Ready code
(function(){
    var DomReady = window.DomReady = {};
	// Everything that has to do with properly supporting our document ready event. Brought over from the most awesome jQuery.
    var userAgent = navigator.userAgent.toLowerCase();
    // Figure out what browser is being used
    var browser = {
    	version: (userAgent.match( /.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/ ) || [])[1],
    	safari: /webkit/.test(userAgent),
    	opera: /opera/.test(userAgent),
    	msie: (/msie/.test(userAgent)) && (!/opera/.test( userAgent )),
    	mozilla: (/mozilla/.test(userAgent)) && (!/(compatible|webkit)/.test(userAgent))
    };

	var readyBound = false;
	var isReady = false;
	var readyList = [];

	// Handle when the DOM is ready
	function domReady() {
		// Make sure that the DOM is not already loaded
		if(!isReady) {
			// Remember that the DOM is ready
			isReady = true;
	        if(readyList) {
	            for(var fn = 0; fn < readyList.length; fn++) {
	                readyList[fn].call(window, []);
	            }
	            readyList = [];
	        }
		}
	};

	// From Simon Willison. A safe way to fire onload w/o screwing up everyone else.
	function addLoadEvent(func) {
	  var oldonload = window.onload;
	  if (typeof window.onload != 'function') {
	    window.onload = func;
	  } else {
	    window.onload = function() {
	      if (oldonload) {
	        oldonload();
	      }
	      func();
	    };
	  }
	};

	// does the heavy work of working through the browsers idiosyncracies (let's call them that) to hook onload.
	function bindReady() {
		if(readyBound) {
		    return;
	    }
		readyBound = true;

		// Mozilla, Opera (see further below for it) and webkit nightlies currently support this event
		if (document.addEventListener && !browser.opera) {
			// Use the handy event callback
			document.addEventListener("DOMContentLoaded", domReady, false);
		}

		// If IE is used and is not in a frame
		// Continually check to see if the document is ready
		if (browser.msie && window == top) (function(){
			if (isReady) return;
			try {
				// If IE is used, use the trick by Diego Perini
				// http://javascript.nwbox.com/IEContentLoaded/
				document.documentElement.doScroll("left");
			} catch(error) {
				setTimeout(arguments.callee, 0);
				return;
			}
			// and execute any waiting functions
		    domReady();
		})();

		if(browser.opera) {
			document.addEventListener( "DOMContentLoaded", function () {
				if (isReady) return;
				for (var i = 0; i < document.styleSheets.length; i++)
					if (document.styleSheets[i].disabled) {
						setTimeout( arguments.callee, 0 );
						return;
					}
				// and execute any waiting functions
	            domReady();
			}, false);
		}

		if(browser.safari) {
		    var numStyles;
			(function(){
				if (isReady) return;
				if (document.readyState != "loaded" && document.readyState != "complete") {
					setTimeout( arguments.callee, 0 );
					return;
				}
				if (numStyles === undefined) {
	                var links = document.getElementsByTagName("link");
	                for (var i=0; i < links.length; i++) {
	                	if(links[i].getAttribute('rel') == 'stylesheet') {
	                	    numStyles++;
	                	}
	                }
	                var styles = document.getElementsByTagName("style");
	                numStyles += styles.length;
				}
				if (document.styleSheets.length != numStyles) {
					setTimeout( arguments.callee, 0 );
					return;
				}

				// and execute any waiting functions
				domReady();
			})();
		}

		// A fallback to window.onload, that will always work
	    addLoadEvent(domReady);
	};

	// This is the public function that people can use to hook up ready.
	DomReady.ready = function(fn, args) {
		// Attach the listeners
		bindReady();

		// If the DOM is already ready
		if (isReady) {
			// Execute the function immediately
			fn.call(window, []);
	    } else {
			// Add the function to the wait list
	        readyList.push( function() { return fn.call(window, []); } );
	    }
	};

	bindReady();

})();

function $(id){
	return document.getElementById(id);
};

// 返回元素绝对地址
function findPos(obj) {
    var curleft = curtop = 0;
    if (obj.offsetParent) {
        while (obj.offsetParent) {
            curleft += obj.offsetLeft;
            curtop += obj.offsetTop;
            obj  = obj.offsetParent;
       }
   }
   curleft += document.body.offsetLeft + document.documentElement.offsetLeft;
   curtop += document.body.offsetTop + document.documentElement.offsetTop;
   //alert(curleft + ',' + curtop);
   return [curleft,curtop];
}

if (typeof(g_tip) == "undefined") {
	var g_tip = "输入中文/全拼/缩写/上下键选择";
}

function initSuggest(suggest_id) {
	$('tip' + suggest_id).innerHTML = g_tip;

	var keyword = $('searchgrouptitle' + suggest_id);
	var sug_group_id = $('searchgroupid' + suggest_id);
	var suggestion = $('Suggestion' + suggest_id);

	var pos = findPos(keyword);
	var listElement = $('viewcont' + suggest_id);
	listElement.style.left = pos[0] + 'px';
	listElement.style.top  = pos[1] + 20 + 'px';

	suggestion.rows[0].cells[0].style.backgroundRepeat = 'repeat-x';
	suggestion.rows[0].cells[0].style.backgroundPosition = 'center';

	keyword.oncontextmenu = function() {return false;}

	var text = ''; //临时保存文本值, 值变化了才去请求接口
	var index = 0; //提示层被选中的项

	keyword.onkeydown = function(ev) {
		var suggestion = $('Suggestion' + suggest_id);
		ev = ev || window.event;
		if (ev.keyCode == 32) {
			return false;
		}
	}

	keyword.onkeyup = function(ev) {
        if (this.getAttribute('suggestion')!='y') {
            return false;
        }
		var suggestion = $('Suggestion' + suggest_id);
		ev = ev || window.event;
		if (__IsInput(ev)) {
			if (suggestion.style.display == '') {
				if (ev.keyCode == 40) {
					//down
					if (suggestion.rows.length > 1) {
						suggestion.rows[index].className = 'item';
						index ++;
						if (index == suggestion.rows.length) index = 1;
						suggestion.rows[index].className = 'itemFocus';
						this.value = suggestion.rows[index].cells[0].innerHTML;
            			sug_group_id.value = suggestion.rows[index].cells[0].id;
					}
				} else if (ev.keyCode == 38) {
					//up
					if (suggestion.rows.length > 1) {
						suggestion.rows[index].className = 'item';
						index --;
						if (index < 1) index = suggestion.rows.length - 1;
						suggestion.rows[index].className = 'itemFocus';
						this.value = suggestion.rows[index].cells[0].innerHTML;
            			sug_group_id.value = suggestion.rows[index].cells[0].id;
					}
				} else if (ev.keyCode == 27) {
					//esc
					suggestion.style.display = 'none';
				} else if (ev.keyCode != 13) {
					//不是回车键
           			sug_group_id.value = 0;
				}
			} else {
			 	if (ev.keyCode == 40) {
					//down
					suggestion.style.display = '';
				} else if (ev.keyCode != 13) {
					//不是回车键
           			sug_group_id.value = 0;
				}
			}
		} else {
			if (this.value != text) {
				text = this.value;
				if (text != '') {
					var url = '/common/modules/dmc/suggestion/check.php?q_word=' + encodeURIComponent(this.value)+"&type="+this.getAttribute('suggestiontype');
					Xml.Request(url, null, showHint);
				} else {
					for (var i = suggestion.rows.length-1; i>0; i--){
						suggestion.tBodies[0].removeChild(suggestion.rows[i]);
					}
				}
			}
		}
	}

	keyword.onfocus = function() {
		if (this.value == this.getAttribute('suggestiondefval')) {
			var suggestion = $('Suggestion' + suggest_id);
			this.value = '';
			this.style.color = '#000000';
			if (this.getAttribute('suggestion')!='y') {
				return;
			}
			suggestion.style.display = '';
		}
	}

	keyword.onblur = function() {
		var suggestion = $('Suggestion' + suggest_id);
		if (this.value == '') {
			this.value = this.getAttribute('suggestiondefval');
			this.style.color = '#999999';
			suggestion.style.display = 'none';
		}
	}

	function addRow(text, type) {
		var suggestion = $('Suggestion' + suggest_id);
		var tr = document.createElement('TR');
		tr.setAttribute('index', suggestion.rows.length);
		tr.onmouseover = function() {
			var i = parseInt(this.getAttribute('index'));
			if (i != index) {
				if (index != -1) suggestion.rows[index].className = 'item';
				this.className = 'itemFocus';
				index = i;
				keyword.value = suggestion.rows[index].cells[0].innerHTML;
    			sug_group_id.value = suggestion.rows[index].cells[0].id;
			}
		}
		var td = document.createElement('TD');
		td.id = type;
		td.innerHTML = text;
		td.style.color = '#333333';
		td.style.height = '18px';
        td.style.overflow='hidden';
		tr.appendChild(td);
		td = document.createElement('TD');
		td.align = 'right';
		td.style.color = '#999999';

		tr.appendChild(td);
		suggestion.tBodies[0].appendChild(tr);
	}

	function showHint() {
		var suggestion = $('Suggestion' + suggest_id);
		for (var i=suggestion.rows.length-1; i>0; i--) {
			suggestion.tBodies[0].removeChild(suggestion.rows[i]);
		}
		var xml = new XmlSource(this, 'projname', 'type');

		for (var i=0; i<xml.projname.length; i++) {
			addRow(xml.projname[i].data, xml.type[i].data);
		}

		if (suggestion.rows.length > 1) {
			suggestion.style.display = '';
			index = 0;
			//suggestion.rows[1].className = 'itemFocus';
		}
	}

	suggestion.onclick = function(ev) {
		var keyword = $('searchgrouptitle' + suggest_id);
		keyword.focus();
		ev = ev || window.event;
		var target = ev.target || ev.srcElement;
		index = parseInt(target.parentNode.getAttribute('index'));
		if (index > 0) {
			keyword.value = target.parentNode.cells[0].innerHTML;
   			sug_group_id.value = target.parentNode.cells[0].id;
		}
		this.style.display = 'none';
	}

	var bodies = [document, document.body, document.documentElement];
	for (var i=0; i<bodies.length; i++) {
		if (bodies[i].onclick == null) {
			bodies[i].onclick = function(ev) {
				ev = ev || window.event;
				var target = ev.target || ev.srcElement;
				if (suggestion.style.display == '' && target != keyword)
				{
					suggestion.style.display = 'none';
				}
			}
			break;
		}
	}
} // 函数结束

__IsSelect = function(ev) {
	if (ev.shiftKey || (ev.ctrlKey && ev.shiftKey)) {
		return (ev.keyCode >=35 && ev.keyCode <=40);
	} else if (ev.ctrlKey && !ev.shiftKey) {
		return ev.keyCode == 65;
	} else {
		return false;
	}
}

__IsMove = function(ev) {
	return (ev.keyCode >=35 && ev.keyCode <=40);
}

__IsInput = function(ev) {
	return __IsSelect(ev) || __IsMove(ev) || ev.keyCode == 9 || ev.keyCode == 8 || ev.keyCode == 27;
}

//Ajax Class
Xml = new Object();
Xml.Request = function(url, data, command, args) {
	url += (url.indexOf('?') > 0)? '&':'?';
	url += Math.random();
	var xmlRequest = null;
	if (window.XMLHttpRequest){
		xmlRequest = new XMLHttpRequest();
		if(xmlRequest.overrideMimeType){
			xmlRequest.overrideMimeType('text/xml');
		}
	} else if (window.ActiveXObject){
		var MSXML = new Array('MSXML2.XMLHTTP', 'Microsoft.XMLHTTP', 'MSXML2.XMLHTTP.3.0', 'MSXML2.XMLHTTP.4.0', 'MSXML2.XMLHTTP.5.0');
		for (var i=0; i<MSXML.length; i++) {
			try {
				xmlRequest = new ActiveXObject(MSXML[i]);
				break;
			} catch(e){
				xmlRequest = null;
			}
		}
	}

	if (xmlRequest != null) {
		xmlRequest.onreadystatechange = function() {
				if (xmlRequest.readyState == 4){
					if(xmlRequest.status == 0 || (xmlRequest.status >= 200 && xmlRequest.status < 300)){
						if (command != null){
							if (typeof(command) == 'function') {
								if(args != null &&  args instanceof Array) {
									command.apply(xmlRequest, args);
								}else{
									command.call(xmlRequest, args);
								}
							} else if (typeof(command) == 'string') {
								command = command.replace('[Xml]', 'xmlRequest.responseXML');
								command = command.replace('[Text]', 'xmlRequest.responseText');
								eval(command);
							} else if (typeof(command) == 'object') {
								if(args == null){
									if(command.id && command.innerHTML){
										command.innerHTML = xmlRequest.responseText;
									}
								} else if(command[args]){
									command[args](xmlRequest);
								}
							}
						}
					} else {
						window.alert('ErrorCode:' + xmlRequest.status + '\r\n' + 'ErrorMessage:' + xmlRequest.statusText);
						window.open(url);
					}
				}
		};
		if (data == null){
			xmlRequest.open('GET',url,true);
			xmlRequest.send(null);
		}else{
			xmlRequest.open('POST',url,true);
			xmlRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded;");
			xmlRequest.send(data);
		}
	}else{
		window.alert('SORRY: YOUR BROWSER IS NOT SUPPORT AJAX!');
	}
}


//XML CLASS
XmlSource = function(xml) {
	this.Xml = xml.responseXML;
	var nodeList;
	for(var i=1; i<arguments.length; i++){
		nodeList = this.Xml.getElementsByTagName(arguments[i]);
		this[arguments[i]] = new Array();
		for (var j=0; j<nodeList.length; j++)
		{
			this[arguments[i]][j] = new XmlNode(nodeList[j]);
		}
	}
}

XmlNode = function(node) {
	this.nodeName = node.nodeName;
	this.data = (node.firstChild && (node.firstChild.nodeName == '#text' || node.firstChild.nodeName == '#cdata-section')) ? node.firstChild.data : '';
	this.getAttribute =
		function(attName) {
			return node.getAttribute(attName);
		}
	var nodeName, xmlNode;
	for (var i=0; i<node.childNodes.length; i++) {
		if (node.childNodes[i].nodeType == 1) {
			nodeName = node.childNodes[i].nodeName;
			if (this[nodeName]) {
				if(this[nodeName] instanceof Array) {
					this[nodeName][this[nodeName].length] = new XmlNode(node.childNodes[i]);
				} else {
					xmlNode = this[nodeName];
					this[nodeName] = new Array();
					this[nodeName][0] = xmlNode;
					this[nodeName][1] = new XmlNode(node.childNodes[i]);
				}
			} else {
				this[nodeName] = new XmlNode(node.childNodes[i]);
			}
		}
	}
}

DomReady.ready(function() {
	for(var i=1,max=g_suggest_id;i<=max;++i) {
        initSuggest(g_suggest_ary[i]);
	}
	g_suggest_id = 0;
});
//window.onload = ;