
/*
 * 功能：类似GoogleSuggest的下拉提示
 * 作者：杨永国
 */

var req; //定义变量，用来创建xmlHttpRequest对象
var inputField;	//要生成Suggest提示的文本输入框
var suggestListContainer; //下拉提示列表内容所被包含的DIV容器
var suggestListContentTable; //下拉提示列表的内容展示Table
var contentBody; //内容展示Table的<tbody></tbody>
var selItemIndex = -1; //Suggest下拉列表的当前选择项索引
var DEFAULT_SUGGEST_LIST_WIDTH = 180; //下拉提示列表的默认宽度。当为0时，和文本输入框的宽度相同
var remoteUrl = ""; //去后台获取数据的URL地址
var preValue = "";



//创建XMLHttpRequest对象       
function createXMLHttpRequest() {
	if(window.XMLHttpRequest) { //Mozilla 浏览器
		req = new XMLHttpRequest();
	}
	else if (window.ActiveXObject) { // IE浏览器
		try {
			req = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				req = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {}
		}
	}
}

//判断浏览器的类型
function getOs() 
{ 
	var OsObject = ""; 
	if(navigator.userAgent.indexOf("MSIE")>0) { 
		return "MSIE"; 
	} 
	if(isFirefox=navigator.userAgent.indexOf("Firefox")>0){ 
		return "Firefox"; 
	} 
}

String.prototype.trim = function()
{
	var reExtraSpace = /^\s*(.*?)\s+$/;
	return this.replace(reExtraSpace,"$1");
}

/**
 * 发送匹配请求函数（注：必须传入event对象，否则FireFox在获得keyCode时不兼容）
 * 参数：
 *		evt 代表事件状态的event对象
 *		url 根据输入框的值，动态取数据的URL地址
 */
function getSuggestList(evt) {

	var typex = document.getElementById('select').value;
	if(inputField.value.trim().length==0){
		//clearSuggestList();
		return ;
	}

	if(evt.keyCode==13){ //回车键（注：FireFox浏览器keyCode必须大写"C"）
		clearSuggestList();
		inputField.blur();
		inputField.select();
		return;
	}

	if (inputField.value.trim().length > 0) {
      	if(preValue != inputField.value){
			selItemIndex = -1; //如果输入框值变化，则初始化此变量，保证上、下键是从列表头开始选择
			createXMLHttpRequest();
		  if(typex == "bond"){
		   		if(inputField.value.indexOf('请输入')>=0 || inputField.value.indexOf('代码/名称/拼音')>=0) inputField.value='代码/名称/拼音';
				remoteUrl = "/f10.do?method=searchZQDMList&zqdm=" + encodeURIComponent(inputField.value);
				document.getElementById('popupDiv').style.display='';
			}else if(typex == "fund"){
				if(inputField.value.indexOf('请输入')>=0 || inputField.value.indexOf('代码/名称/拼音')>=0) inputField.value='代码/名称/拼音';
				remoteUrl = "/f10.do?method=searchJJDMList&gpdm=" + encodeURIComponent(inputField.value);
				document.getElementById('popupDiv').style.display='';
			}else if(typex == "stock"){
				if(inputField.value.indexOf('请输入')>=0 || inputField.value.indexOf('代码/名称/拼音')>=0) inputField.value='代码/名称/拼音';
				remoteUrl = "/f10.do?method=searchGPDMList&gpdm=" + encodeURIComponent(inputField.value);
				document.getElementById('popupDiv').style.display='';				
			}else if(typex == "help"){
				if(inputField.value.indexOf('请输入')>=0 || inputField.value.indexOf('代码/名称/拼音')>=0) inputField.value='请输入帮助内容';
				remoteUrl = "/question.do?method=searchByKeyWord&keyWord=" + encodeURIComponent(inputField.value);
				document.getElementById('popupDiv').style.display='';
			}else if(typex == "caixun"){
				if(inputField.value.indexOf('请输入')>=0 || inputField.value.indexOf('代码/名称/拼音')>=0) inputField.value='请输入财讯内容';
				remoteUrl = "/question.do?method=searchByKeyWord&keyWord=" + encodeURIComponent(inputField.value);
				document.getElementById('popupDiv').style.display='';
			}
			req.open("GET", remoteUrl, true);
			req.onreadystatechange = processMatchResponse;//指定响应函数
			req.send(null); // 发送请求
		}
	} else {
    	clearSuggestList();
	}
}

//处理返回匹配信息函数
function processMatchResponse() {
	if (req.readyState == 4) { // 判断对象状态
    	if (req.status == 200) { // 信息已经成功返回，开始处理信息
    		
			createSuggestList();
			
        }else { //页面不正常
            window.alert("您所请求的页面有异常。");
        }
    }
}

//生成Suggest下拉列表
function createSuggestList() {
	clearSuggestList(); //先清除先前的下拉列表
	
	var bonds;
	var size = 0;
	if(req.responseXML==null){ //当没有数据返回时，FireFox这里要特殊处理
		return;
	}else{
		
		bonds = req.responseXML.getElementsByTagName("gpjj");
		size = bonds.length;
		if(size==0)
			return;
	}
	
	 //JSON格式数据
	//if(req.responseText==null){ //当没有数据返回时，FireFox这里要特殊处理
	//	return;
	//}else{
	//	bonds = eval( req.responseText); //JSON格式数据
	//}
    
    renderContainer();
    
    var row, cell, txtNode;
    for (var i = 0; i < size; i++) {
        var nextNode = bonds[i].firstChild.data;
        row = document.createElement("tr");
        row.onmouseout = function() {this.style.backgroundColor ='#FFFAFA';};
        row.onmouseover = function() {this.style.backgroundColor ='#f4a460';};
        row.onmousedown = function() { itemSelected(this);};

        cell = document.createElement("td");
        txtNode = document.createTextNode(nextNode);
        cell.appendChild(txtNode);
        row.appendChild(cell);
        contentBody.appendChild(row);
    }
}
//设置Suggest下拉列表的显示位置及显示样式                
function renderContainer() {
	if(DEFAULT_SUGGEST_LIST_WIDTH == 0){
		suggestListContentTable.width = inputField.clientWidth;
	}else{
		suggestListContentTable.width = DEFAULT_SUGGEST_LIST_WIDTH;
    }

   var left = calculateOffset(inputField,"offsetLeft")-20;
   if(document.body.offsetWidth>1000) left=675;
    var top = calculateOffset(inputField,"offsetTop") + inputField.offsetHeight;
    suggestListContainer.style.width = suggestListContentTable.width;
    suggestListContainer.style.border = "black 1px solid";
    suggestListContainer.style.left = left +20 + "px";
    suggestListContainer.style.top = top + "px";
    suggestListContainer.style.width = suggestListContentTable.width;
}

/**
 * 计算相对于文本输入框的显示位置
 * 参数：
 *		attr 要计算数值的属性名，'offsetLeft'、'offsetTop'等
 */
function calculateOffset(field,attr) {
	var offset = 0;
	while(field) {
		offset += field[attr]; 
		field = field.offsetParent;
	}
	return offset;
}

/**
 * 下拉列表某行被选中的动作
 * 参数：
 *		row 被选中的下拉列表行
 */
function itemSelected(row) {
	inputField.value = row.firstChild.firstChild.nodeValue.split(" ")[0];
	preValue = inputField.value;
	//toF10(); //执行查询, 需要调用的页面实现此方法
	clearSuggestList();
}
    
//清除Suggest下拉列表
function clearSuggestList(){
	suggestListContainer.style.displsy = "none";
	if(inputField.value.trim().length==0){
		if(document.getElementById('select').value == "stock"){
			inputField.value='代码/名称/拼音';
		}else if(document.getElementById('select').value == "fund"){
			inputField.value='代码/名称/拼音';
		}else if(document.getElementById('select').value == "bond"){
			inputField.value='代码/名称/拼音';
		}else if(document.getElementById('select').value == "help"){
			inputField.value='请输入帮助内容';
		}else if(document.getElementById('select').value == "caixun"){
			inputField.value='请输入财讯内容';
		}
	 
	}else{
		
		var ind = contentBody.childNodes.length;
	    for (var i = ind - 1; i >= 0 ; i=i-1) {
	        contentBody.removeChild(contentBody.childNodes[i]);
	    }
	   
	    suggestListContainer.style.border = "none";
	}
}
/**
 * 处理键盘按下动作
 * 参数：
 * 		evt event对象
 *		functionName 键盘按下后需要执行的函数名
 */
function keyDownProcess(evt,functionName)
{/*
	if(evt.keyCode == 13)
	{
		//toF10(); //执行查询, 需要调用的页面实现此方法
		event.srcElement.select();
	}else{
		if(evt.keyCode == 38 || evt.keyCode == 40){
			selectChange(evt.keyCode);
		}
	}*/
}

/**
 * 按上、下方向键进行选择
 * 参数：
 *		eventkey 键盘的key值
 */
function selectChange(eventkey){
	var size = contentBody.childNodes.length;
    if(size == null || size == 0)
        return;
        
    if(eventkey == 40){ //向下键
    	if(selItemIndex == size - 1){ //到达列表最底部，重新从顶部开始选择
    		selItemIndex = 0;
    	}else{
        	selItemIndex++;
        }
    }else if(eventkey == 38){ //向上键
    	if(selItemIndex == 0 || selItemIndex == -1){ //到达列表最顶部，重新从最底部开始选择
    		selItemIndex = size - 1;
    	}else{
        	selItemIndex--;
        }
    }
    
    for(var j=0; j<size; j++){
		contentBody.childNodes[j].style.backgroundColor = '#FFFAFA';
	}
	
    for(var i=0; i<size; i++){
		if(selItemIndex == -1){
			return;
		}
		if(i == selItemIndex){
            contentBody.childNodes[i].style.backgroundColor = '#f4a460';
            inputField.value = contentBody.childNodes[i].childNodes[0].innerHTML.split(" ")[0];
		}
    }
    preValue = inputField.value;
}

//执行表单验证并查询
function toF10(){
	var type = document.getElementById('select').value;
	var url = "";
	if(type == "bond" && inputField.value!="代码/名称/拼音"){
		if(inputField.value.trim().length==0){
			alert("请输入债券代码");
			return false;
		}
		if(inputField.value.match(/^[a-zA-Z0-9]*$/)==null){
			alert("债券代码只能包含字母和数字");
			return false;
		}
		
		url = "/qn_search/zq.jsp?gpdm="+inputField.value;
	}else if(type == "caixun" && inputField.value!="请输入财讯内容"){
		if(inputField.value.trim().length==0){
			alert("请输入搜索条件");
			return false;
		}
		url = "/qn_search/cxzl_ss.jsp?searchWord="+encodeURIComponent(inputField.value);
	}else if(type == "fund" && inputField.value!="代码/名称/拼音"){
		if(inputField.value.trim().length==0){
			alert("请输入基金代码");
			return false;
		}
		if(inputField.value.match(/^[0-9]\d*$/)==null){
			alert("基金代码只能包含数字");
			return false;
		}
		if(inputField.value.length !=6 ){
			alert("基金代码长度应该为6位");
			return false;
		}
		
		url = "/qn_search/jj.jsp?gpdm="+inputField.value;
	}else if(type == "stock" && inputField.value!="代码/名称/拼音"){
		if(inputField.value.trim().length==0){
			alert("请输入股票代码");
			return false;
		}
		if(inputField.value.match(/^[0-9]\d*$/)==null){
			alert("股票代码只能包含数字");
			return false;
		}
		if(inputField.value.length !=6 ){
			alert("股票代码长度应该为6位");
			return false;
		}
		
		url = "/qn_search/f10_all.jsp?gpdm="+encodeURIComponent(inputField.value);
	}else if(type=="help"){
		url = "/qn_search/help.jsp?keyWord="+encodeURIComponent(inputField.value);
	}else{
		alert("请输入搜索内容");
		return false;
	}
	if(url != '' ){
		window.open(url);
	}
}
//我要报错
function wybc(){
	var url;
	var urlnew="";
	url=window.mainframe.location.href;
	var urlcs=url.split("&");
	for(var i=0; i<urlcs.length; i++)
	{
		urlnew+=urlcs[i]+"$";
	}
	window.open('/admin/advice/wybc.jsp?source='+urlnew);
}

//投资咨询
function openInvestmentConsultation() {
    window.open("http://chat.gtja.com/webcall/client/otherIndex.jsp?from=webcallft&userId=<%=userId%>&realName=<%=realName%>&branchName=总部&formenu=tzzx&islogin=1&account=0&provinceId=4411","newwindow","height=550, width=680, top=0, left=0, toolbar=no, menubar=no, scrollbars=no,resizable=no,location=no, status=no");
	

}

//业务咨询
function openBusinessConsultation() {

 window.open("http://chat.gtja.com/webcall/client/otherIndex.jsp?from=webcallft&userId=<%=userId%>&realName=<%=realName%>&branchName=总部&formenu=ywzx&islogin=1&account=0&provinceId=4411","newwindow","height=550, width=680, top=0, left=0, toolbar=no, menubar=no, scrollbars=no,resizable=no,location=no, status=no");

}

//客户经理
function openCustomerManager() {
   window.open("http://chat.gtja.com/webcall/client/otherIndex.jsp?from=webcallft&userId=<%=userId%>&realName=<%=realName%>&branchName=总部&formenu=khjl&islogin=1&account=0&provinceId=4411","newwindow","height=550, width=680, top=0, left=0, toolbar=no, menubar=no, scrollbars=no,resizable=no,location=no, status=no");
}
