﻿// global variables
var _inMyPage = false;

// global AJAX functions
Array.prototype.QueryActions = function(senderLayout,senderDiv,eventName) 
								{   									
									var result = new Array();
									var x;
									for(var i=0;i<this.length;i++)
									{
										x = this[i];
										if (x.EVENTNAME!=eventName)
											continue;
										if ((x.SENDER_DIV == senderDiv) ||
											(x.SENDER_DIV == "" && x.SENDER_LAYOUT == senderLayout) ||
											(x.SENDER_DIV == "" && x.SENDER_LAYOUT == ""))
										{
											result[result.length] = x; 
										}										
									}																		
									return result;											
								};
Array.prototype.RemoveItemByLayout = function(listenerLayout) 
								{ 									
									var x;
									for(var i=this.length-1;i>=0;i--)
									{
										x = this[i];
										if (x.LISTENER_LAYOUT == listenerLayout)									
											this.splice(i,1);
									}									
								};		
Array.prototype.RemoveItemByDiv = function(listenerDiv) 
								{ 									
									var x;
									for(var i=this.length-1;i>=0;i--)
									{
										x = this[i];
										if (x.LISTENER_DIV == listenerDiv)											
											this.splice(i,1);
									}					
								};								
var gRegisterCollection = new Array();

function AJAX_Register(senderLayout,senderDiv,eventName,listenerLayout,listenerDIV,actions)
{	
	var RegisterItem;
	try { 
		RegisterItem = {"SENDER_LAYOUT":senderLayout , "SENDER_DIV":senderDiv , "EVENTNAME":eventName , "LISTENER_LAYOUT":listenerLayout , "LISTENER_DIV":listenerDIV , "ACTIONS":actions} 
		gRegisterCollection[gRegisterCollection.length] = RegisterItem; }
	catch(e) {};
}

function AJAX_Event(senderLayout,senderDiv,eventName,parameters)
{	
	try
	{	
		var eventTarget = gRegisterCollection.QueryActions(senderLayout,senderDiv,eventName);
		if (eventTarget.length <=0) return;
		
		var x;
		var sendAjax ;	

		for( var i=0;i<eventTarget.length;i++)
		{	
			x = eventTarget[i];
			sendAjax = x.ACTIONS;
			if (sendAjax.indexOf("?")>0)
				parameters = parameters.replace("?","&");	
			
			sendAjax = sendAjax.replace("{EventParameters}",parameters);
			eval(sendAjax);	
		}
	}
	catch(e)
	{
		alert(e.number & 0xFFFF + "--" + e.description);
	}
}

function AJAX_Send(url,targetGUID,postAjaxCallBack,data)
{	
	var http_request = false;
	postAjaxCallBack = postAjaxCallBack==null ? "" : postAjaxCallBack;
	
    if (window.XMLHttpRequest) 
    {   // Mozilla, Safari,...
        http_request = new XMLHttpRequest();
        if (http_request.overrideMimeType) 
            http_request.overrideMimeType('text/xml');
    } 
    else if (window.ActiveXObject) 
    {  // IE
        try 
        {
            http_request = new ActiveXObject("Microsoft.XMLHTTP");
        } 
        catch (e) 
        {
            try 
            {
                http_request = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {}
        }
    }

    if (!http_request) 
    {
        alert('Cannot create an XMLHTTP instance.');
        return false;
    }

	url = BuildQS(url);
	//var s_imageFolder = "finance/";
	//if (url.substr(0, 1) != '/' && url.substr(0, 1) != '\\') url = "/Factory/" + url;
	//if (document.all('imageFolder')) s_imageFolder = document.all('imageFolder').value.substr(16);
	//url += "&CH=" + s_imageFolder.substr(0, s_imageFolder.length-1);
	//alert(url);
	
    http_request.onreadystatechange = function() { AJAX_CallBack(http_request,targetGUID,postAjaxCallBack);};
    http_request.open('GET', url, true);
    http_request.send(data);
}

function AJAX_Post(url,targetGUID,postAjaxCallBack,data)
{	
	var http_request = false;
	postAjaxCallBack = postAjaxCallBack==null ? "" : postAjaxCallBack;
	
    if (window.XMLHttpRequest) 
    {   // Mozilla, Safari,...
        http_request = new XMLHttpRequest();
        if (http_request.overrideMimeType) 
            http_request.overrideMimeType('text/xml');
    } 
    else if (window.ActiveXObject) 
    {  // IE
        try 
        {
            http_request = new ActiveXObject("Microsoft.XMLHTTP");
        } 
        catch (e) 
        {
            try 
            {
                http_request = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {}
        }
    }

    if (!http_request) 
    {
        alert('Cannot create an XMLHTTP instance.');
        return false;
    }

	url = BuildQS(url);
	//if (url.substr(0, 1) != '/' && url.substr(0, 1) != '\\') url = "/Factory/" + url;
	//alert(url);
	
    http_request.onreadystatechange = function() { AJAX_CallBack(http_request,targetGUID,postAjaxCallBack);};
    http_request.open('POST', url, true);
    http_request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    http_request.send(data);
}

function AJAX_CallBack(http_request,targetGUID,postAjaxCallBack)
{	
	var iWhere = 0;
	if (http_request.readyState == 4) 
	{
        if (http_request.status == 200) 
        { 
			try
			{	
				var oNewItem;
				var oOldItem = document.getElementById(targetGUID);
				iWhere ++;		// 1
				switch (oOldItem.tagName.toUpperCase())
				{
					case "DIV":
						gRegisterCollection.RemoveItemByDiv(targetGUID);
						break;
					case "TABLE":
						gRegisterCollection.RemoveItemByLayout(targetGUID);
						break;
					default:
						break;
				}
				iWhere ++;		// 2
				
				//==============Trace Response Content====
				/*var fso, f, ts, s;
				var ForReading = 1, ForWriting = 2, ForAppending = 8;
				var TristateUseDefault = -2, TristateTrue = -1, TristateFalse = 0;
				fso = new ActiveXObject("Scripting.FileSystemObject");
				fso.CreateTextFile( "C:\\test1.htm" );           // Create a file.
				f = fso.GetFile("C:\\test1.htm");
				ts = f.OpenAsTextStream(ForWriting, TristateUseDefault);
				ts.Write( http_request.responseText );
				ts.Close( );*/
				//============== 
				
				oOldItem.insertAdjacentHTML("beforeBegin",http_request.responseText);
				//alert("測試訊息\n"+http_request.responseText);
				oNewItem = oOldItem.previousSibling;
				oOldItem.removeNode(true);
				
				iWhere ++;		// 3
				if (postAjaxCallBack.length >0)	
				{	
				   postAjaxCallBack += "('" + oNewItem.id + "')";
				   eval(postAjaxCallBack);
				}
				else
				   oNewItem.style.display="";	
				
				//oOldItem.removeNode(true);	
				
			}
			catch(e)
			{			
				alert("AJAX_CallBack Error:" + e.message + "\nWhere:" + iWhere.toString() + ", targetGUID: "+targetGUID);
			}				                      		   
        }       
    }
}         

function AJAX_Send_byCustomCallback(url,customAjaxCallBack)
{	
	var http_request = false;
		
    if (window.XMLHttpRequest) 
    {   // Mozilla, Safari,...
        http_request = new XMLHttpRequest();
        if (http_request.overrideMimeType) 
            http_request.overrideMimeType('text/xml');
    } 
    else if (window.ActiveXObject) 
    {  // IE
        try 
        {
            http_request = new ActiveXObject("Microsoft.XMLHTTP");
        } 
        catch (e) 
        {
            try 
            {
                http_request = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {}
        }
    }

    if (!http_request) 
    {
        alert('Cannot create an XMLHTTP instance.');
        return false;
    }
	
	if (url.substr(0, 1) != '/' && url.substr(0, 1) != '\\') url = "/Factory/" + url;
    http_request.onreadystatechange = function() { customAjaxCallBack(http_request);};
    http_request.open('GET', url, true);
    http_request.send(null);
}

function AJAX_Post_byCustomCallback(url, customAjaxCallBack, data)
{	
	var http_request = false;
		
    if (window.XMLHttpRequest) 
    {   // Mozilla, Safari,...
        http_request = new XMLHttpRequest();
        if (http_request.overrideMimeType) 
            http_request.overrideMimeType('text/xml');
    } 
    else if (window.ActiveXObject) 
    {  // IE
        try 
        {
            http_request = new ActiveXObject("Microsoft.XMLHTTP");
        } 
        catch (e) 
        {
            try 
            {
                http_request = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {}
        }
    }

    if (!http_request) 
    {
        alert('Cannot create an XMLHTTP instance.');
        return false;
    }
  	//alert(url);
  	
    http_request.onreadystatechange = function() { customAjaxCallBack(http_request);};
    http_request.open('POST', url, true);
    http_request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    http_request.send(data);
}

function SYNC_Send(url,targetGUID,postAjaxCallBack,data)
{
	var http_request = false;
	postAjaxCallBack = postAjaxCallBack==null ? "" : postAjaxCallBack;
	
    if (window.XMLHttpRequest) 
    {   // Mozilla, Safari,...
        http_request = new XMLHttpRequest();
        if (http_request.overrideMimeType) 
            http_request.overrideMimeType('text/xml');
    } 
    else if (window.ActiveXObject) 
    {  // IE
        try 
        {
            http_request = new ActiveXObject("Microsoft.XMLHTTP");
        } 
        catch (e) 
        {
            try 
            {
                http_request = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {}
        }
    }

    if (!http_request) 
    {
        alert('Cannot create an XMLHTTP instance.');
        return false;
    }

	if (url.substr(0, 1) != '/' && url.substr(0, 1) != '\\') url = "/Factory/" + url;
	//alert(url);
	
    http_request.onreadystatechange = function() { AJAX_CallBack(http_request,targetGUID,postAjaxCallBack);};
    http_request.open('GET', url, false);
    http_request.send(data);
}

// validate and build AJAX query string
function BuildQS(url)
{
	var s_imageFolder = "finance/";
	if (url.substr(0, 1) != '/' && url.substr(0, 1) != '\\') url = "/Factory/" + url;
	if (url.indexOf("CH=") < 0)
	{
		if (document.all('imageFolder')) s_imageFolder = document.all('imageFolder').value.substr(16);
		url += "&CH=" + s_imageFolder.substr(0, s_imageFolder.length-1);
	}
	return url;
}

// form routines
function InitForm(asFormName)
{
	var oElements = document.all(asFormName).all;
	var oElement, sRequired, sInit, oLabel;
	
	// scan form fields
	for (var i=0; i<oElements.length; i++)
	{
		// append REQUIRED marks
		oElement  = oElements(i);
		sRequired = oElement.getAttribute("_Required");
		if (sRequired != null && sRequired != "DONE")
		{ 
			try { oLabel = oElement.parentElement.previousSibling; } catch(e) {};
			if (!oLabel) oLabel = oElement;
			oLabel.insertAdjacentHTML("afterBegin", "<span class='b2c_Text_S' style='color:red' _Hide>*&nbsp;</span>");
			oElement._Required = "DONE";
		}
		
		// init special-type fields
		sInit = oElement.getAttribute("_Init");
		if (sInit != null)
		{	
			switch (sInit)
			{
				case "DATE_YEAR":
					init_year_combo(oElement);
					break;
				case "DATE_MONTH":
					init_month_combo(oElement);
					break;
				case "DATE_DAY":
					init_day_combo(oElement);
					break;
			}
		}
	}
}

function ValidateForm(asFormName, bShowMsgBox)
{	
	// validate form fields
	var oElements = document.all(asFormName).all;
	var oElement, sRequired, sCheck, sFixLen, sTo, sResult="";
	var sLI1 = (bShowMsgBox==null || !bShowMsgBox? "<LI>": "");
	var sLI2 = (bShowMsgBox==null || !bShowMsgBox? "</LI>": ""); 
	
	for (var i=0; i<oElements.length; i++)
	{
		oElement =  oElements(i);
		sRequired = oElement.getAttribute("_Required");
		sCheck =    oElement.getAttribute("_Check");
		sFixLen =   oElement.getAttribute("_FixLength");
		sTo =       oElement.getAttribute("_To");
		if (sCheck != null || sRequired != null || sFixLen != null)
		{
			var sError = ValidateField(oElement, sRequired, sCheck, sFixLen);
			if (sError != "")
			{	sResult += sLI1 + sError + sLI2;
				if (bShowMsgBox==null || !bShowMsgBox) showFieldError(oElement, sError);
			}
			else
				clearFieldError(oElement);
		} 
		if (sTo != null) document.all(sTo).innerHTML = oElement.value;
	}
	
	// validation failed
	if (sResult != "")
	{	
		if (bShowMsgBox==null || !bShowMsgBox)
		{
			//form_status.innerHTML = "<span class='b2c_Text_L'><B>資料檢核錯誤，請在下方表單修正!</B></span>" + 
								    //"<br><br>" + 
								    //"<div class='b2c_Text' align='left' style='width:240px'>" + sResult + "</div><br>";
			window.navigate("#form_status");
		}
		else
			alert(sResult);
		return false;
	}
	else
		return true;
}

function ValidateField(aoElement, asRequired, asCheck, asFixLen)
{
	var sName = (aoElement.getAttribute("_Name")==null? "": aoElement.getAttribute("_Name"));
	if (asRequired != null && aoElement.value == "") return sName + "不可為空白!\n";
	if (asFixLen != null && !isNaN(parseInt(asFixLen)) && aoElement.value.length != parseInt(asFixLen)) return sName + "必須為 "+asFixLen+" 碼!\n";
	if (asCheck == null) return "";
	
	// checking special-purpose field
	switch (asCheck)
	{
		case "IDNO":
			if (aoElement.value.length != 10) return sName+"必須為十碼!\n";
			if (!ID_Check(aoElement.value)) return "請輸入正確的"+sName+"!\n";
			break;
		case "NUMERIC":
			var nMin = (aoElement.getAttribute("_Min")==null? "": aoElement.getAttribute("_Min"));
			var nMax = (aoElement.getAttribute("_Max")==null? "": aoElement.getAttribute("_Max"));
			var nValue = parseInt(aoElement.value);
			if (isNaN(nValue))
				return sName + "必須是數值!\n";
			else if (nMin != "" && !isNaN(parseInt(nMin)) && nValue<parseInt(nMin))
				return sName + "不可小於 " + nMin + "!\n";
			else if (nMax != "" && !isNaN(parseInt(nMax)) && nValue>parseInt(nMax))
				return sName + "不可大於 " + nMax + "!\n";
			break;
		case "EMAIL":
			if (aoElement.value != "")
			{	var nAT = aoElement.value.indexOf("@");
				if (nAT<=0 || nAT==aoElement.value.length-1) return sName+"格式錯誤!\n";
			}
			break;
		case "DATE":
			if (!date_check(aoElement.value)) return sName+"日期錯誤!\n";
			break;
		case "PIN":
			var minLength = aoElement.getAttribute("minLength");
			var maxLen = aoElement.getAttribute("maxLength");
			var pin2 = aoElement.getAttribute("_Pin2");
			var newPin = aoElement.getAttribute("_NewPin");
			if (minLength != null && aoElement.value.length < parseInt(minLength)) return sName+"長度不足!\n";
			if (maxLen != null && aoElement.value.length > parseInt(maxLen)) return sName+"長度超過限制!\n";
			if (pin2 != null && aoElement.value != document.all(pin2).value) return sName+"確認錯誤!\n";
			if (newPin != null && aoElement.value == document.all(newPin).value) return "新密碼與舊密碼不可相同!\n";
			break;
		case "URI":
			if (aoElement.value != "")
			{
				var r,re;
				var s = aoElement.value;
				//re = new RegExp("^[http|ftp|wap|https]{3,5}:\//\www\.*.[com|net|gov|edu|mil|org]{2,3}.*$","i");
				re = new RegExp("^[http|ftp|wap|https]{3,5}:\//\*\.*.[com|net|gov|edu|mil|org]{2,3}.*$","i");
				r = re.exec(s);
				if (r == null)
					return sName+"格式錯誤!\n";
			}
			break;
	}
	return "";
}

function showFieldError(aoElement, asError)
{
	var sID = (aoElement.name? aoElement.name: (aoElement.id? aoElement.id: ""));
	if (sID != "")
	{	var oError = document.getElementById("err_" + sID);
		if (!oError)
		{	var sTemp = "<span id='err_"+sID+"' class='b2c_Text' style='color:red'></span>"
			aoElement.insertAdjacentHTML("afterEnd", sTemp);
			oError = document.getElementById("err_" + sID);
		}
		if (oError) oError.innerHTML = "&nbsp;<img src='/resources/images/cancel.gif'>&nbsp;" + asError;
	}
}

function clearFieldError(aoElement)
{
	var sID = (aoElement.name? aoElement.name: (aoElement.id? aoElement.id: ""));
	if (sID != "") 
	{	var oError = document.getElementById("err_" + sID);
		if (oError) oError.innerHTML = "";
	}
}

function ID_Check(asID)
{
	var bOK = false;
	var sID = asID;
	if (sID.length == 10)
	{
		sID = sID.toUpperCase();
		var c1 = sID.charCodeAt(0);
		if (c1 >= 65 && c1 <= 90)
		{
			var c = new Array(11);
			var a = new Array(10,11,12,13,14,15,16,17,34,18,19,20,21,22,35,23,24,25,26,27,28,29,32,30,31,33);        
			
			c[0] = a[c1 - 65] / 10;
			c[0] = parseInt(c[0].toString());
			c[1] = a[c1 - 65] % 10;
			for (var i=1; i<=9; i++) c[i+1] = sID.charCodeAt(i)-48;
			var count = c[0];
			for (var i=1; i<=9; i++) count += c[i] * (10-i);
			if (((count % 10) + c[10]) % 10 == 0) bOK = true;
		}
	}    
	return (bOK);
}

function init_year_combo(aoParent)
{
	var now = new Date;
	var year_begin=now.getFullYear();
	var year_end=1900; 
	var sValue = aoParent.getAttribute("Y");
	for (var i=year_begin; i>=year_end; i--)
	{
		var oOption = document.createElement("OPTION");
		aoParent.options.add(oOption);
		oOption.innerHTML = i;
		oOption.value = i.toString();
		if (sValue == oOption.value)
			oOption.selected = true;
				
		if (i % 10 == 0)
		{
			var oOption = document.createElement("OPTION");
			aoParent.options.add(oOption);
		}
	}
	aoParent.selectedIndex = -1;
}

function init_month_combo(aoParent)
{
	var sValue = aoParent.value;
	for (var i=1; i<=12; i++)
	{
		var oOption = document.createElement("OPTION");
		aoParent.options.add(oOption);
		oOption.innerHTML = i;
		oOption.value = i;
		if (i<10) oOption.value = "0" + oOption.value;
		if (sValue == oOption.value) oOption.selected = true;
	}
	aoParent.selectedIndex = -1;
}

function init_day_combo(aoParent)
{
	var sValue = aoParent.value;
	for (var i=1; i<=31; i++)
	{
		var oOption = document.createElement("OPTION");
		aoParent.options.add(oOption);
		oOption.innerHTML = i;
		oOption.value = i;
		if (i<10) oOption.value = "0" + oOption.value;
		if (sValue == oOption.value) oOption.selected = true;
	}
	aoParent.selectedIndex = -1;
}

function date_changed(aoTarget, aoY, aoM, aoD)
{
	aoTarget.value = aoY.value + "/" + aoM.value + "/" + aoD.value;
}

function date_check(aDate)
{
	var monthLength = new Array(31,28,31,30,31,30,31,31,30,31,30,31);
	var year = parseInt(aDate.substr(0, 4),10);
	var month = parseInt(aDate.substr(5, 2),10);
	var day = parseInt(aDate.substr(8, 2),10);
	
	if (!day || !month || !year)
		return false;

	if (year/4 == parseInt(year/4))
		monthLength[1] = 29;

	if (day > monthLength[month-1])
		return false;

	return true;
}

function BuildXMLDOM(asFormName)
{	
	// Mozilla, Safari,...
	var oDOM;
	if (window.XMLHttpRequest) 
    {	 oDOM = new ActiveXObject("Microsoft.XMLDOM");	}
    
    // IE
    else if (window.ActiveXObject) 
    {	oDOM = new ActiveXObject("Microsoft.XMLDOM");	}
    
    // unsupported
    else
    {	return null;	}
    
    // init DOM
    oDOM.async = false;
    oDOM.loadXML('<?xml version="1.0" encoding="big5"?><Form/>');
        
    // collect form data and build the DOM
    var oElements = document.all(asFormName).all;
	var oElement, oNode, sName, sValue;
	var oRoot = oDOM.documentElement;
	var sTitle;
	
	for (var i=0; i<oElements.length; i++)
	{
		oElement = oElements(i);
		sName = oElement.getAttribute("name");
		sTitle = null;
		if (sName != null && sName != "")
		{
			sValue = oElement.value;
			switch (oElement.type)
			{
				case "radio":
					if (!oElement.checked) continue;
					sTitle = oElement.getAttribute("title");
					break;
				case "checkbox":
					sValue = "YES";
					if (!oElement.checked) sValue = "NO";
					break;
				case "select-one":
					if (oElement.selectedIndex >= 0)
					{
						var oOption = oElement.options(oElement.selectedIndex);
						if (oOption != null) sTitle = oOption.text;
					}
					break;
			}
			
			oNode = oDOM.createElement(sName);
			oNode.text = sValue;
			if (sTitle != null && sTitle != "")
			{
				var oAttribute = oDOM.createAttribute("Title");
				oAttribute.text = sTitle;
				oNode.attributes.setNamedItem(oAttribute);
			}
			oRoot.appendChild(oNode);
		}
	}
	return oDOM;
}

function BuildXML(asFormName, asNodeName)
{	    
    // collect form data and build the DOM
    var oElements = document.all(asFormName).all;
	var oElement;
	var sXML, sName, sValue, sTitle, sNodeName;
	
	// determine xml node name
	sNodeName = "Form";
	if (asNodeName != null && asNodeName != "") sNodeName = asNodeName;
	sXML = "<?xml version='1.0'?><" + sNodeName + ">";
	for (var i=0; i<oElements.length; i++)
	{
		oElement = oElements(i);
		sName = null;
		sName = oElement.getAttribute("name");
		sTitle = null;
		if (sName != null && sName != "")
		{
			// determine value
			switch (oElement.tagName)
			{
				case "TD":
				case "SPAN":
					sValue = oElement.innerText;
					break;
				default:
					sValue = oElement.value;
					break;
			}
			
			// determine title
			switch (oElement.type)
			{
				case "radio":
					if (!oElement.checked) continue;
					sTitle = oElement.getAttribute("title");
					break;
				case "checkbox":
					sValue = (oElement.checked? "YES": "NO");
					break;
				case "select-one":
					if (oElement.selectedIndex >= 0)
					{
						var oOption = oElement.options(oElement.selectedIndex);
						if (oOption != null) sTitle = oOption.text;
					}
					break;
			}
			if (sTitle==null) sTitle = oElement.getAttribute("_title");
			
			// add one field
			sXML += "<" + sName;
			if (sTitle != null && sTitle != "") sXML += " Title='" + sTitle + "'";
			sXML += "><![CDATA[" + sValue + "]]></" + sName + ">";
		}
	}
	sXML += "</" + sNodeName + ">";
	return sXML;
}

function setRadio(asName, asValue)
{
	var oElements = document.getElementsByName(asName);
	for (var i=0; i<oElements.length; i++)
		if (oElements(i).value != null && oElements(i).value == asValue)
		{	oElements(i).checked = true;
			break;
		}
}

function _InitDIV123(asID)
{  
	var o = document.all(asID);
	var _ctop = null;
	var _cleft = null;
	var _cwidth = null;
	var _cheight = null;
	return;
	
	if (o!=null && o.readyState!=null && o.readyState=="complete")
	{ 
		var lo_Children = o.children;
		for (var i=0; i<lo_Children.length; i++)
		{
			_ctop = lo_Children[i].getAttribute("_top");
			_cleft = lo_Children[i].getAttribute("_left");
			_cwidth = lo_Children[i].getAttribute("_width");
			_cheight = lo_Children[i].getAttribute("_height");
			if (_ctop != null) lo_Children[i].style.top = lo_Children[i].parentElement.clientHeight + parseInt(_ctop);
			if (_cleft != null) lo_Children[i].style.left = lo_Children[i].parentElement.clientWidth + parseInt(_cleft); 
			if (_cwidth != null) lo_Children[i].style.width = lo_Children[i].parentElement.clientWidth + parseInt(_cwidth); 
			if (_cheight != null) lo_Children[i].style.height = lo_Children[i].parentElement.clientHeight + parseInt(_cheight);
			window.status = lo_Children[i].parentElement.clientHeight.toString() + "," + lo_Children[i].parentElement.clientHeight.toString();
		}
	}
	else
		window.setTimeout("_InitDIV('" + asID + "');", 1000);
}

<!-- floating toolbar -->
var _floatBar = "" ;
if (document.all.imageFolder) _floatBar = document.all.imageFolder.value;
if (_floatBar == "") _floatBar = "/Polaris/images/finance/";

document.write("<div id='flashLogon12' style='position:absolute; border:0 solid gray; display:none; width:300; left:0; top:75; z-Index:2;'>");
document.write("  <div id='divFlashLogon'></div>");
document.write("</div>");

document.write("<div id='flashLogonHint' style='position:absolute; font-size:13px; color:#ffffff; background-color:#ff7f00; padding:5; border:1 solid #ffffff; display:none; width:200; left:0; top:100; z-Index:2;' align='center'>");
document.write("  請使用網站帳號與密碼登入!!!");
document.write("</div>");

document.write("<div id='floatToolbar' style='position:absolute; display:none; cursor:hand; border:0; left:0; top:50; z-Index:3'>");
document.write("  <img id='floatBar' src='"+_floatBar+"float/closebutton.gif' style='position:relative; left:0; top:0' border=0 onclick='showFloatPanel()'>");
document.write("  <div id='floatMenu' style='position:relative; left:0; top:0; width:202; display:none;'><div id='floatDIV'></div></div>");
document.write("</div>");

document.write("<select id='ajax_History' style='display:none'></select>");

FloatDownload();
FloatInterrelate();
FloatStock();

function adjustToolbarPosition()
{	
	var ieBody = (document.compatMode && document.compatMode!="BackCompat")? document.documentElement : document.body;
	var noFloatPanel = "NO";
	
	document.all.floatToolbar.style.left = ieBody.scrollLeft;
	document.all.floatToolbar.style.top = ieBody.scrollTop + 50;
	
	if (document.getElementById("_NoFloatPanel")) noFloatPanel = document.getElementById("_NoFloatPanel").value; 
	
	// show/hide floar bar and flash logon panel 
	if (document.location.pathname.toUpperCase().indexOf("/FINAIRPORT/DEFAULT")>=0 ||
		document.location.pathname.toUpperCase().indexOf("FINAIRPORTENG")>=0 ||
		document.location.pathname.toUpperCase().indexOf("WIN_PREVIEW.ASP")>=0 ||
		document.location.pathname.toUpperCase().indexOf("WIN_MYPAGE")>=0 ||
		noFloatPanel == "YES")
  	{
		document.all.floatToolbar.style.display = "none";
		document.all.flashLogon12.style.display = "none";
		document.all.flashLogonHint.style.display = "none" ;
	}
	else
	{ 
		document.all.floatToolbar.style.display = "inline";
		document.all.flashLogon12.style.display = "inline";
	}
		
	// adjust flash logon 
	try {
		document.all.flashLogon12.style.left = document.all.tbTop.offsetLeft + 35;
		document.all.flashLogonHint.style.left = document.all.tbTop.offsetLeft + 45;
	} catch (e) {};
	
}

function ajax_History_Add(asURL)
{  
	try {
		var lo_Object = document.all("ajax_History");
		var lo_Option = document.createElement("OPTION");
		lo_Object.options.add(lo_Option);
		lo_Option.innerText = asURL;
	} 
	catch (e) {};
}

function ajax_History_Back(asLayoutGUID)
{
	try {
		var lo_Object = document.all("ajax_History"); 
		alert(lo_Object.options.length);
		if (lo_Object.options.length == 1)
			alert("On Top Now!");
		else 
		{
			alert(asLayoutGUID + "\n" + lo_Object.options(lo_Object.options.length-2).innerText);
			AJAX_Send("svc_Content.asp?" + lo_Object.options(lo_Object.options.length-2).innerText, asLayoutGUID , "", null);
		}
	} 
	catch (e) {};
}

function loadFloatPanel()
{
	AJAX_Send('svc_Content.asp?GUID=E0350532-6E21-415D-9061-14A6910D1ABA&SRC=HTML&_DGUID=floatDIV', 'floatDIV', ''); 
}

function loadFlashLogon()
{
	//AJAX_Send('svc_Content.asp?GUID=A2084326-975C-4CA8-B12B-446E48C7C01D&SRC=FlashLogon&_DGUID=divFlashLogon', 'divFlashLogon', ''); 
	AJAX_Send('Flash_WebLogin.asp?_DGUID=divFlashLogon', 'divFlashLogon', '');
}

function showFloatPanel()
{ 
	if (document.all.floatBar.style.display == "none")
	{
		document.all.floatBar.style.display = "inline";
		document.all.floatMenu.style.display = "none";
		document.all.tabEQPanel.style.display = "none";
	}
	else
	{	
		document.all.floatBar.style.display = "none";
		document.all.floatMenu.style.display = "inline";
	}	
} 

function _Home()
{
	window.location = "/finairport/Chn_1/Chn_1_1/Chn_1_1_1/";
}

function WebLoginProc()
{
	// adjust float logon/logoff menu
	document.all("_logonImg").style.display = "none";
	document.all("_logoffImg").style.display = "inline";
	loadFlashLogon();
} 

function WebLogoffProc()
{
	// adjust float logon/logoff menu
	document.all("_logonImg").style.display = "inline";
	document.all("_logoffImg").style.display = "none";
	loadFlashLogon();
} 

function _webLogoff()
{
	AJAX_Post_byCustomCallback('/Factory/svc_Logoff.asp', _webLogoff_Callback, null);
} 

function _webLogoff_Callback(http_request)
{
	if (http_request.readyState == 4) 
	{
        if (http_request.status == 200) 
        { 
			try
			{	
				// get logon result code.
				var sResult = http_request.responseText;
				
				// logoff failed
				if (sResult != "OK")
				{	alert("登出失敗!");		}
				
				// logoff success
				else {
					AJAX_Post_byCustomCallback('/Polaris/Common/svc_Logoff.aspx', _Home, null);
				}
				
			}
			catch(e)
			{ 	alert(e.message);	}				                      		   
        }       
    }
}

function ResizeIFrame(oIFrameId,addPx,fInsuranceCallBack)
{	
	try
	{	//alert(oIFrameId.height);
		if (oIFrameId.readyState=="complete")
		{			
			if (addPx == null )
				addPx = 30;
			
			if (oIFrameId.contentWindow.document.getElementsByName("frSheet").length != 0 ) //Transfer from Excel file
			{	
				var oFrame = oIFrameId.contentWindow.document.getElementsByName("frSheet")[0];
				oIFrameId.height = oFrame.contentWindow.document.body.scrollHeight + addPx;	
			}
			else
				oIFrameId.height =oIFrameId.contentWindow.document.body.scrollHeight + addPx;		
			//document.getElementById(oIFrameId).height = document.getElementById(oIFrameId).contentWindow.document.body.scrollHeight + addPx;		
			top.scrollTo(0,0);
			//top.focus();			
		}
	}
	catch(e)
	{ 	//alert(e.message);
		if (fInsuranceCallBack !=null)			
			eval(fInsuranceCallBack);
	}
}

var gBgImageHeight = 105;
function ContentDivBlockVisible(pDivID)
{
	try
	{	
		var strContent="";
		var spanID = "MainContent_" + pDivID;	
		var PaddingTRID= "PaddingTR_" + pDivID;
		var oItems = document.getElementById(spanID);		
		var tdCount=0;

		if (oItems !=null)
		{	
			for(itemIndex=0;itemIndex<oItems.children.length;itemIndex++)
			{
				strContent +=oItems.children.item(itemIndex).innerText;			
			}

			tdCount = itemIndex;
		
			if (strContent.length<=0)
			{								
				document.getElementById(pDivID).style.display ="none";				
				return false;
			}
			else
			{	
				var objTR = document.getElementById(PaddingTRID);
				var nHeight = Math.max(0,gBgImageHeight - tdCount*15);
				if (objTR !=null && nHeight >0)
					objTR.height = nHeight;
				
				document.getElementById(pDivID).style.display = "";
				return true;
			}
		} 
	}
	catch(e)
	{
		alert(e.message);
	}
	return false;
}

var gUserDefWidth;
function ResizeContentDivWidth(pDivID)
{	
	var objDiv = document.getElementById(pDivID);		
	if (objDiv != null && gUserDefWidth != null)
	{	
		objDiv.parentElement.width = gUserDefWidth;
	}
}

function InitialContentDivWidth(pDivID)
{	
	var objDiv = document.getElementById(pDivID);
	if (objDiv != null)
	{
		gUserDefWidth = objDiv.parentElement.width;
		objDiv.parentElement.width="100%";				
	}
}

function RedirectSearchPage()
{
	var strCriteria = escape(document.getElementById('txtGoSearch').value);
	window.location.href = "/Finairport/Chn_4/Chn_4_9/default?ty=index&cr=" + strCriteria;
}

function onGoSearchEnterKey()
{
	if (window.event && event.keyCode==13) 
	{	
		RedirectSearchPage();
		event.returnValue=false;
	}
}

// adjust toolbar position during scroll and resize
/*window.onscroll = adjustToolbarPosition;
window.onresize = adjustToolbarPosition;
window.onload = win_onload;*/

// load float menu HTML
//---loadFloatPanel();
//loadFlashLogon(); 

// window onload
function win_onload()
{ 
	adjustToolbarPosition();
}

// AD : S_Left
function _AD_Left()
{
	if (document.all("DIV_AD"))
	{ 
		var ls_Key = _floatBar.substr(16).toUpperCase();
		if (ls_Key == "FINANCE/") ls_Key = "S1_Left";
		if (ls_Key == "PRODUCT/") ls_Key = "S2_Left"; 
		if (ls_Key == "SERVICE/") ls_Key = "S3_Left"; 
		if (ls_Key == "GROUP/") ls_Key = "S4_Left";
		AJAX_Send('svc_Content.asp?GUID=A8C5B31D-B3C7-4FBC-9AC8-8C1AB2B4A0ED&SRC='+ls_Key+'&_LGUID=DIV_AD', 'DIV_AD', '');
	}
	else
		window.setTimeout("_AD_Left()", 250);
}
//_AD_Left();

// flash logon/logoff
function _flashWebLogin()
{
	// validate form
	if ( !ValidateForm("frmFlashLogin", true) ) return;

	// validation success, prepare form xml
	var sXML = BuildXML("frmFlashLogin");
	
	// submit form to server
	var sIDNO = document.all('_flash_ID').value;
	AJAX_Post_byCustomCallback('/Factory/svc_Logon.asp?IDNO=' + sIDNO, FlashLogon_Callback, sXML);

} 

function FlashLogon_Callback(http_request)
{
	if (http_request.readyState == 4) 
	{
        if (http_request.status == 200) 
        { 
			try
			{	
				// get logon result code.
				var sResult = http_request.responseText;
				
				// logon failed
				if (sResult == "")
					alert("登入失敗!");
								
				// logon success
				else
					AJAX_Post_byCustomCallback('/Polaris/Common/svc_Logon.aspx?TOKEN=' + sResult, FlashLogon_Callback_b2c, null);
				
			}
			catch(e) { alert(e.message); }				                      		   
        }       
    }
}

function FlashLogon_Callback_b2c(http_request)
{
	if (http_request.readyState == 4) 
	{
        if (http_request.status == 200) 
        { 
			try
			{
				//WebLoginProc();
				alert("登入成功!");
				window.location.reload(true);
			}
			catch(e){ alert(e.message);	}				                      		   
        }       
    }
}

function _flashWebLogoff()
{
	AJAX_Post_byCustomCallback('/Factory/svc_Logoff.asp', FlashLogoff_Callback, null);
}

function FlashLogoff_Callback(http_request)
{
	if (http_request.readyState == 4) 
	{
        if (http_request.status == 200) 
        { 
			try
			{	
				// get logon result code.
				var sResult = http_request.responseText;
				
				// logon failed
				if (sResult != "OK")
					alert("登出失敗!");
				
				// logon success
				else
					AJAX_Post_byCustomCallback('/Polaris/Common/svc_Logoff.aspx', FlashLogoff_Callback_b2c, null);
			}
			catch(e) {	alert(e.message); }				                      		   
        }       
    }
}

function FlashLogoff_Callback_b2c(http_request)
{
	if (http_request.readyState == 4) 
	{
        if (http_request.status == 200) 
        { 
			try
			{
				alert("登出成功!");
				window.location.reload(true);
			}
			catch(e){ alert(e.message);	}				                      		   
        }       
    }
}

function FlashDonothing()
{}

function FloatDownload()
{
	//document.write("<div id='floatRelative' style='position:absolute; display:none; cursor:hand; border:0; right:10; top:200; z-Index:4'>");
	document.write("<DIV id='floatDownloadDIV' style='BORDER-RIGHT: red 0px dotted; BORDER-TOP: red 0px dotted; BORDER-LEFT: red 0px dotted; WIDTH: 30%; BORDER-BOTTOM: red 0px dotted; POSITION: absolute;display:none;  border:0; right:30; top:50; z-Index:4 ' align=center onmouseenter='onDownloadMouseOver();' onmouseleave='onDownloadMouseOut();'> ");
	document.write("<DIV style='Z-INDEX: -1; BACKGROUND: url(/Resources/images/default/Box301_head_L.gif) no-repeat left top; LEFT: 0px; WIDTH: 83px; POSITION: absolute; TOP: 0px; HEIGHT: 46px'></DIV>");
	document.write("<DIV style='Z-INDEX: -1; BACKGROUND: url(/Resources/images/default/Box301_head_M.gif) repeat-x left top; LEFT: 83px; ; WIDTH: expression(parentElement.clientWidth-161); POSITION: absolute; TOP: 0px; HEIGHT: 46pt'></DIV>");
	document.write("<DIV style='Z-INDEX: -1; BACKGROUND: url(/Resources/images/default/Box301_head_R.gif) no-repeat left top; LEFT: -75px; ; LEFT: expression(parentElement.clientWidth-78); WIDTH: 78px; POSITION: absolute; TOP: 0px; HEIGHT: 46px'></DIV>");
	document.write("<DIV style='Z-INDEX: -1; BACKGROUND: url(/Resources/images/default/Box301_line_L.gif) repeat-y left top; LEFT: 0px; WIDTH: 5px; POSITION: absolute; TOP: 46px; ; HEIGHT: expression(parentElement.clientHeight-60)'></DIV>");
	document.write("<DIV style='Z-INDEX: -1; BACKGROUND: url(/Resources/images/default/Box301_line_M.gif) left top; LEFT: 5px; ; WIDTH: expression(parentElement.clientWidth-10); POSITION: absolute; TOP: 46px; ; HEIGHT: expression(parentElement.clientHeight-60)'></DIV>");
	document.write("<DIV style='Z-INDEX: -1; BACKGROUND: url(/Resources/images/default/Box301_line_R.gif) repeat-y left top; LEFT: -2px; ; LEFT: expression(parentElement.clientWidth-5); WIDTH: 5px; POSITION: absolute; TOP: 46px; ; HEIGHT: expression(parentElement.clientHeight-60)'></DIV>");
	document.write("<DIV style='Z-INDEX: -1; BACKGROUND: url(/Resources/images/default/Box301_foot_L.gif) no-repeat left top; LEFT: 0px; WIDTH: 12px; POSITION: absolute; TOP: -14px; ; TOP: expression(parentElement.clientHeight-14); HEIGHT: 14px'></DIV>");
	document.write("<DIV style='Z-INDEX: -1; BACKGROUND: url(/Resources/images/default/Box301_foot_M.gif) repeat-x left top; LEFT: 12px; ; WIDTH: expression(parentElement.clientWidth-24); POSITION: absolute; TOP: -14px; ; TOP: expression(parentElement.clientHeight-14); HEIGHT: 14px'></DIV>");
	document.write("<DIV style='Z-INDEX: -1; BACKGROUND: url(/Resources/images/default/Box301_foot_R.gif) no-repeat left top; LEFT: -9px; ; LEFT: expression(parentElement.clientWidth-12); WIDTH: 12px; POSITION: absolute; TOP: -14px; ; TOP: expression(parentElement.clientHeight-14); HEIGHT: 14px'></DIV>");
	document.write("  <div id='floatDownloadTable' style='position:relative;  left:0; top:0; width:100%; display:none;' ></div>");
	document.write("</div>");
}

function FloatInterrelate()
{	
	document.write("<DIV id='floatInterrelateDIV' style='BORDER-RIGHT: red 0px dotted; BORDER-TOP: red 0px dotted; BORDER-LEFT: red 0px dotted; WIDTH: 30%; BORDER-BOTTOM: red 0px dotted; POSITION: absolute;display:none;  border:0; right:30; top:50; z-Index:4 ' align=center onmouseenter='onInterrelateMouseOver();' onmouseleave='onInterrelateMouseOut();'> ");
	document.write("<DIV style='Z-INDEX: -1; BACKGROUND: url(/Resources/images/default/Box302_head_L.gif) no-repeat left top; LEFT: 0px; WIDTH: 83px; POSITION: absolute; TOP: 0px; HEIGHT: 46px'></DIV>");
	document.write("<DIV style='Z-INDEX: -1; BACKGROUND: url(/Resources/images/default/Box302_head_M.gif) repeat-x left top; LEFT: 83px; ; WIDTH: expression(parentElement.clientWidth-161); POSITION: absolute; TOP: 0px; HEIGHT: 46pt'></DIV>");
	document.write("<DIV style='Z-INDEX: -1; BACKGROUND: url(/Resources/images/default/Box302_head_R.gif) no-repeat left top; LEFT: -75px; ; LEFT: expression(parentElement.clientWidth-78); WIDTH: 78px; POSITION: absolute; TOP: 0px; HEIGHT: 46px'></DIV>");
	document.write("<DIV style='Z-INDEX: -1; BACKGROUND: url(/Resources/images/default/Box302_line_L.gif) repeat-y left top; LEFT: 0px; WIDTH: 5px; POSITION: absolute; TOP: 46px; ; HEIGHT: expression(parentElement.clientHeight-60)'></DIV>");
	document.write("<DIV style='Z-INDEX: -1; BACKGROUND: url(/Resources/images/default/Box302_line_M.gif) left top; LEFT: 5px; ; WIDTH: expression(parentElement.clientWidth-10); POSITION: absolute; TOP: 46px; ; HEIGHT: expression(parentElement.clientHeight-60)'></DIV>");
	document.write("<DIV style='Z-INDEX: -1; BACKGROUND: url(/Resources/images/default/Box302_line_R.gif) repeat-y left top; LEFT: -2px; ; LEFT: expression(parentElement.clientWidth-5); WIDTH: 5px; POSITION: absolute; TOP: 46px; ; HEIGHT: expression(parentElement.clientHeight-60)'></DIV>");
	document.write("<DIV style='Z-INDEX: -1; BACKGROUND: url(/Resources/images/default/Box302_foot_L.gif) no-repeat left top; LEFT: 0px; WIDTH: 12px; POSITION: absolute; TOP: -14px; ; TOP: expression(parentElement.clientHeight-14); HEIGHT: 14px'></DIV>");
	document.write("<DIV style='Z-INDEX: -1; BACKGROUND: url(/Resources/images/default/Box302_foot_M.gif) repeat-x left top; LEFT: 12px; ; WIDTH: expression(parentElement.clientWidth-24); POSITION: absolute; TOP: -14px; ; TOP: expression(parentElement.clientHeight-14); HEIGHT: 14px'></DIV>");
	document.write("<DIV style='Z-INDEX: -1; BACKGROUND: url(/Resources/images/default/Box302_foot_R.gif) no-repeat left top; LEFT: -9px; ; LEFT: expression(parentElement.clientWidth-12); WIDTH: 12px; POSITION: absolute; TOP: -14px; ; TOP: expression(parentElement.clientHeight-14); HEIGHT: 14px'></DIV>");
	document.write("  <div id='floatInterrelateTable' style='position:relative;  left:0; top:0; width:100%; display:none;' ></div>");
	document.write("</div>");
}

function FloatStock()
{	
	document.write("<DIV id='floatStockDIV' style='BORDER-RIGHT: red 0px dotted; BORDER-TOP: red 0px dotted; BORDER-LEFT: red 0px dotted; WIDTH: 30%; BORDER-BOTTOM: red 0px dotted; POSITION: absolute;display:none;  border:0; right:30; top:50; z-Index:4 ' align=center onmouseenter='onStockMouseOver();' onmouseleave='onStockMouseOut();'> ");
	document.write("<DIV style='Z-INDEX: -1; BACKGROUND: url(/Resources/images/default/Box303_head_L.gif) no-repeat left top; LEFT: 0px; WIDTH: 83px; POSITION: absolute; TOP: 0px; HEIGHT: 46px'></DIV>");
	document.write("<DIV style='Z-INDEX: -1; BACKGROUND: url(/Resources/images/default/Box303_head_M.gif) repeat-x left top; LEFT: 83px; ; WIDTH: expression(parentElement.clientWidth-161); POSITION: absolute; TOP: 0px; HEIGHT: 46pt'></DIV>");
	document.write("<DIV style='Z-INDEX: -1; BACKGROUND: url(/Resources/images/default/Box303_head_R.gif) no-repeat left top; LEFT: -75px; ; LEFT: expression(parentElement.clientWidth-82); WIDTH: 82px; POSITION: absolute; TOP: 0px; HEIGHT: 46px'></DIV>");
	document.write("<DIV style='Z-INDEX: -1; BACKGROUND: url(/Resources/images/default/Box303_line_L.gif) repeat-y left top; LEFT: 0px; WIDTH: 5px; POSITION: absolute; TOP: 46px; ; HEIGHT: expression(parentElement.clientHeight-60)'></DIV>");
	document.write("<DIV style='Z-INDEX: -1; BACKGROUND: url(/Resources/images/default/Box303_line_M.gif) left top; LEFT: 5px; ; WIDTH: expression(parentElement.clientWidth-13); POSITION: absolute; TOP: 46px; ; HEIGHT: expression(parentElement.clientHeight-60)'></DIV>");
	document.write("<DIV style='Z-INDEX: -1; BACKGROUND: url(/Resources/images/default/Box303_line_R.gif) repeat-y left top; LEFT: -2px; ; LEFT: expression(parentElement.clientWidth-8); WIDTH: 5px; POSITION: absolute; TOP: 46px; ; HEIGHT: expression(parentElement.clientHeight-60)'></DIV>");
	document.write("<DIV style='Z-INDEX: -1; BACKGROUND: url(/Resources/images/default/Box303_foot_L.gif) no-repeat left top; LEFT: 0px; WIDTH: 12px; POSITION: absolute; TOP: -14px; ; TOP: expression(parentElement.clientHeight-14); HEIGHT: 14px'></DIV>");
	document.write("<DIV style='Z-INDEX: -1; BACKGROUND: url(/Resources/images/default/Box303_foot_M.gif) repeat-x left top; LEFT: 12px; ; WIDTH: expression(parentElement.clientWidth-28); POSITION: absolute; TOP: -14px; ; TOP: expression(parentElement.clientHeight-14); HEIGHT: 14px'></DIV>");
	document.write("<DIV style='Z-INDEX: -1; BACKGROUND: url(/Resources/images/default/Box303_foot_R.gif) no-repeat left top; LEFT: -9px; ; LEFT: expression(parentElement.clientWidth-16); WIDTH: 13px; POSITION: absolute; TOP: -14px; ; TOP: expression(parentElement.clientHeight-14); HEIGHT: 14px'></DIV>");
	document.write("  <div id='floatStockTable' style='position:relative;  left:0; top:0; width:100%; display:none;' ></div>");
	document.write("</div>");
}

function showProgress(asID)
{
try {
	var oDIV = document.getElementById(asID);
	if (oDIV) oDIV.innerHTML = "<br><br>" + 
							   "<img src='/resources/images/ajax-loader.gif' border='0' align='absmiddle'>&nbsp;&nbsp;" +
							   "<span class='b2c_Text'>讀取資料中...</span>" +
							   "<br><br>";
} catch (e) {};
} 

// xml related routines
function xml_GetAttribute(aoNode, asNodeName, as2ndName)
{ 
	try {
		var ls_data = aoNode.attributes.getNamedItem(asNodeName).text;
		if (ls_data == "" && as2ndName != "") ls_data = aoNode.attributes.getNamedItem(as2ndName).text;
		return ls_data;
	}
	catch (e) { return ""; }

}