/*
#############################################
#
# 利用 xmlhttp 實現的無限級 聯動菜單
#
# alee201@sina.com
#
#############################################

一共只有兩個函數，一個全局變量。
假設頁面裏有多個聯動菜單，
Initialize函數用于初始化  頁面中各個聯動菜單的 一級菜單，
getOption 函數用于在某一級菜單被選擇時，裝載他的下級菜單。
ServerURL 變量用于記錄查詢請求提交的地址。

*/


// ServerURL 在服務器端負責數據查詢的程序的地址。所有查詢請求將提交到該地址。
var ServerURL="/link-query.php";
var defaultStartLoadIdx = 1;


/*
函數 str2unicode
將字符串以轉換成 unicode ，並插入分隔符。
*/
function str2unicode(str)
{
	var strRtn="";
	var separator="z";	//file:用z作分隔符

	for (var i=0;i<str.length;i++)
	{
		strRtn+=str.charCodeAt(i);
		if (i<str.length-1) strRtn+=separator;
	}
	return strRtn;
}

/*
函數 clearMenu

清空一個菜單
第一個參數是菜單
*/
function clearMenu(menu,startIndex)
{
	if( !startIndex && startIndex != 0 )
		startIndex = defaultStartLoadIdx;
	
	for (index=menu.length-1;index>=startIndex;index--)
	{
		//alert("刪除原菜單第"+(index+2)+"項");
		menu.options[index]=null;//刪除下級菜單中原有的選項，前一次裝載的數據需要清空		
	}	
}

function setSelected(menu,selectedValue)
{
	for(var idx=0;idx<menu.options.length;idx++)//裝載新獲取的數據到下級菜單
	{	
		if( selectedValue>0 && selectedValue == menu.options[idx].value )
			menu.options[idx].selected=true

	}
}


/*

函數 getOption

菜單選項的查詢和裝載
參數說明：
Parent		上級菜單（select 對象），
Select_name	所有下級菜單（數組，元素爲 select 對象），數組中的第一個菜單，會根據 Parent 所選擇的內容，被裝載，其余的清空。


*/
function getOption(Parent,Selects,Table,field,queryURL,ifall,startLoadIdx)
{
	parent_option=Parent.selectedIndex;//上級菜單選中的項的序號
	theForm=Parent.form;
	parentKay=null;
	if(!Table)
		Table=Parent.item(parent_option).table;
	if(!startLoadIdx)
		startLoadIdx = defaultStartLoadIdx;

	for(key=0;key<theForm.length;key++)
	{
		if( theForm[key]==Parent )
		{
			parentKay=key;
			break;
		}
		else
			continue;
	}								// 獲得 Parent 在form中的key

	for(var key=0; key<Selects.length; key++)
	{
		if(typeof(Selects[key])=="object")
			continue;
		else if( (typeof(Selects[key])=="string") && (result=Selects[key].match(/^([\-\+])(\d)+$/)) )
		{
			if(result[1]=="+")
				curentKey=parentKay+eval(result[2]);
			else if(result[1]=="-")
				curentKey=parentKay-eval(result[2]);
			else
				return false;

			Selects[key]=theForm[curentKey];
		}
		else
			return false;
	}								//將全部“-2”類型的參數轉換橫實際對象
	
	
	Select=Selects[0];

	for(var key=0; key<Selects.length; key++)
	{
		clearMenu(Selects[key],startLoadIdx);
	}

	var Http = new ActiveXObject("Microsoft.XMLHTTP");//創建xmlhttp對象，用于收發數據到服務器短
	var Dom = new ActiveXObject("Microsoft.XMLDOM");//創建xmldom對象，用于分析、獲取服務器段傳回的xml中的數據
	
	if(queryURL)
		var url=queryURL;
	else
		var url=ServerURL;
	
	if(!ifall)
		ifall=0;

	if( field )
		url+="?value="+escape( str2unicode(Parent.item(parent_option).text) )+"&field="+field+"&"+"table="+Table+"&all="+ifall;
	else
		url+="?parent="+Parent.item(parent_option).parent+"*"+Parent.item(parent_option).value+"&"+"table="+Table+"&all="+ifall;
	//alert(url);
	//out.innerText+=url+"<br>";
	//document.write(url);
	Http.open("GET",url,false);
	Http.setRequestHeader("CONTENT-TYPE","application/x-www-form-urlencoded");//如果需要 get/post 中文參數到服務器，必須出現次行，否則服務器端出現編碼錯誤。
	Http.send();//發送查詢信息
	Dom.async=false //設置爲同步方式獲取數據
	//alert(Http.responseText);
	
	//從服務器端傳回的xml信息中，獲取數據
	Dom.loadXML(Http.responseText);
	Item = Dom.getElementsByTagName("item");
	itemID = Dom.getElementsByTagName("id");
	itemName = Dom.getElementsByTagName("name");
	itemParent = Dom.getElementsByTagName("parent");
	
	//alert("獲取: "+Item.length+"個新的對象");
	
	for(key=0;key<Item.length;key++)//裝載新獲取的數據到下級菜單
	{
		index=key+startLoadIdx;
		//alert(itemID[key].text+itemName[key].text+"("+key+":"+Item.length+")");
		tempoption=new Option(itemName[key].text,itemID[key].text);
        Select.options[index]=tempoption;
		Select.options[index].parent=itemParent[key].text;
		Select.options[index].table=Table;
		Select.options[index].value=itemID[key].text;
	}
}

/*

函數 Initialize

菜單的初始化
可以一次初始化多個菜單，用數組將聯動菜單的第一級菜單 的name，以及所在form傳遞給本函數。
參數說明：
Menus	需要初始化的菜單（數組，元素爲完整的表單對象）；
Table	服務器短 數據庫裏對應的表（字符串）。

Initialize函數 訪問服務器的數據庫，到由 Table 參數所指定的數據表裏 獲取數據，裝載到 數組參數 P 所指定的各個菜單裏。
*/
function Initialize(Menus,Table,selectedValue,startLoadIdx)//初始化第一個關聯菜單
{
	var url=ServerURL+"?table="+Table+"&parent=0";
	//document.write("<br>"+url);
	
	if( !startLoadIdx )
		startLoadIdx = defaultStartLoadIdx;
	
	var Http = new ActiveXObject("Microsoft.XMLHTTP");//創建xmlhttp對象，用于收發數據到服務器短
	var Dom = new ActiveXObject("Microsoft.XMLDOM");//創建xmldom對象，用于分析、獲取服務器段傳回的xml中的數據
	
	Http.open("GET",url,false);
	Http.setRequestHeader("CONTENT-TYPE","application/x-www-form-urlencoded");//如果需要 get/post 中文參數到服務器，必須出現次行，否則服務器端出現編碼錯誤。
	Http.send();//發送查詢信息
	Dom.async=false //設置爲同步方式獲取數據
	
	Dom.loadXML(Http.responseText);
	Item = Dom.getElementsByTagName("item");
	itemID = Dom.getElementsByTagName("id");
	itemName = Dom.getElementsByTagName("name");
	itemParent = Dom.getElementsByTagName("parent");	
	//document.write("<br>"+"對象:"+Item.length+" name節點:"+itemName.length+" id節點:"+itemID+" parent節點:"+itemParent.length);
	
	for(var key=0;key<Item.length;key++)//裝載新獲取的數據到下級菜單
	{	
		index=key + startLoadIdx;	
		for(var menu in Menus)
		{
			tempoption=new Option(itemName[key].text,itemID[key].text);
			Menus[menu].options[index]=tempoption;
			Menus[menu].options[index].parent=itemParent[key].text;
			Menus[menu].options[index].table=Table;
			Menus[menu].options[index].value=itemID[key].text;
			
			if( selectedValue>0 && selectedValue == itemID[key].text )
				Menus[menu].options[index].selected=true
		}
	}
}

function InitMore(Menus,values,DB_table_name)
{
	// 初始化第一個菜單
	Initialize(new Array(Menus[0]),DB_table_name,values[0])
	
	// 循環初始化 以後的菜單
	for(idx=1;idx<Menus.length;idx++)
	{
		// 裝載菜單
		getOption(Menus[idx-1],new Array(Menus[idx]))
		// 默認項
		setSelected(Menus[idx],values[idx])
	}
}