﻿function focusFirstField(){
    if (document.forms){
		if (document.forms.length==0) return;
    }
    var f=document.forms(0);
    //for(var i=0;i<document.forms(0).elements.length;i++){
    for(var i=0;i<100;i++){
        if(f.elements(i)){
	    if((f.elements(i).type=="text" || f.elements(i).type=="textarea")
	       && !f.elements(i).disabled){
                   f.elements(i).focus();
		   return;
            }
        }
    }
}

function setTextBoxDisabled(f,b){
    if(f.length==0) return;
    for(var i=0;i<f.elements.length;i++){
        if (f.elements(i)){
            if (f.elements(i).type=="text"){
                f.elements(i).disabled=b;
            }
        }
    }
}

function disableMouseRightClick(evt){
	if (event.button==2){
		alert("Mouse right click is disabled");
		return false;
	}
	return true;
}

function toUpperChar(thisfield)
{
thisfield.value = thisfield.value.toUpperCase();
}

function addDate(d,days){
var t=d.getTime();
t+=days*24*60*60*1000;

var d1=new Date();
d1.setTime(t);

return d1;
}

function addMonth(d,months){
var d1=new Date();
d1.setTime(d.getTime());

var m=d.getMonth()+months;

// If the value of numMonth is greater than 11 (January is month 0) or is a negative number,
// the stored year is modified accordingly.
// For example, if the stored date is "Jan 5, 1996" and setMonth(14) is called,
// the date is changed to "Mar 5, 1997."

d1.setMonth(m);
return d1;
}

function addYear(d,years){
var m=d.getYear();

var k=m+years;

var d1=new Date();
d1.setTime(d.getTime());
d1.setYear(k);

return d1;
}


function getDateByPaymentTerm(d,term){
var unit=term.substr(0,1);
var num=parseInt(term.substr(1,term.length-1));
if(unit=="M")	return addMonth(d,num);
if(unit=="D")	return addDate(d,num);
if(unit=="Y")	return addYear(d,num);
return d;
}


function printPage(){
	window.print();
}

function confirmSubmit(f,confirm_msg){
var agree=confirm(confirm_msg);
if(!agree) return;
f.submit();
}

function processReload(f){
	processSubmitForm(f,false,"");
}

function processSubmit(f){
	processSubmitForm(f,true,"");
}

function processSubmitMsg(f,confirm_msg){
	processSubmitForm(f,true,confirm_msg);
}


function processSubmitForm(f,needToConfirm,confirm_msg){
	if(needToConfirm){
		var msg_text="";
		if(USER_SYS_LANG==LANG__ZHO) msg_text="現在提交資料?";
		if(USER_SYS_LANG==LANG__ZHS) msg_text="现在提交数据?";
		if(USER_SYS_LANG==LANG__ENG) msg_text="Submit data?";
		
		if(confirm_msg!=""){
			msg_text=confirm_msg;
		}
		var agree=confirm(msg_text);
		if (!agree){
			return;
		}
	}

	var message=document.all.processing_message.style;
	var cover=document.all.image_cover.style;

	//center the message box, hardcode to align the position
	message.top=(document.body.scrollTop)+(document.body.offsetHeight/2)-65;
	message.left=(document.body.scrollLeft)+(document.body.offsetWidth/2)-115;
	message.visibility='visible';

	//resize the image to cover the whole page
	//(preserve 3px to prevent page overflow)
	cover.height=document.body.scrollHeight-3;
	cover.width=document.body.scrollWidth;
	cover.visibility='visible';

	//override events to prevent further submit
	for(var i=0; i<f.length; i++){
		f.elements[i].onchange=function(){return false;};
		f.elements[i].onclick=function(){return false;};
	}

	//hidden all select menu to prevent overlap with message layer
	for(i=0;i<document.all.tags('SELECT').length;i++){
		obj=document.all.tags('SELECT')[i];
		if(!obj){
			continue;
		}	
		obj.style.visibility="hidden";
	}

	//disable all keyboard events(especially the tab key)
	document.body.onkeydown=function(){return false;};

	//show a wait cursor
	document.body.style.cursor ="wait";

	f.submit();
}

function cancelInput(page){
	var msg_text="";
	if(USER_SYS_LANG==LANG__ZHO) msg_text="取消輸入資料?";
	if(USER_SYS_LANG==LANG__ZHS) msg_text="取消输入数据?";
	if(USER_SYS_LANG==LANG__ENG) msg_text="Cancel input?";

	var agree=confirm(msg_text);

	if (!agree){
		return;
	}
	window.location=page;
}


//since escape() is fail to handle encoding for unicode URI
//below 2 functions are going to encode unicode char(eg.chinese char) to %nn format

function utf8(wide) {
  var c, s;
  var enc = "";
  var i = 0;
  while(i<wide.length) {
    c= wide.charCodeAt(i++);
    // handle UTF-16 surrogates
    if (c>=0xDC00 && c<0xE000) continue;
    if (c>=0xD800 && c<0xDC00) {
      if (i>=wide.length) continue;
      s= wide.charCodeAt(i++);
      if (s<0xDC00 || c>=0xDE00) continue;
      c= ((c-0xD800)<<10)+(s-0xDC00)+0x10000;
    }
    // output value
    if (c<0x80) enc += String.fromCharCode(c);
    else if (c<0x800) enc += String.fromCharCode(0xC0+(c>>6),0x80+(c&0x3F));
    else if (c<0x10000) enc += String.fromCharCode(0xE0+(c>>12),0x80+(c>>6&0x3F),0x80+(c&0x3F));
    else enc += String.fromCharCode(0xF0+(c>>18),0x80+(c>>12&0x3F),0x80+(c>>6&0x3F),0x80+(c&0x3F));
  }
  return enc;
}

function encodeUTF8URI(s) {
  var s = utf8(s);
  var c;
  var enc = "";
  var okURIchars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-";
  var hexchars = "0123456789ABCDEF";
  var tmp="";
  
  for (var i= 0; i<s.length; i++) {
    if (okURIchars.indexOf(s.charAt(i))==-1){
      tmp=s.charCodeAt(i)
	  enc += "%"+hexchars.charAt(tmp>>4)+hexchars.charAt(tmp & 0xF);
    }else{
      enc += s.charAt(i);
	}
  }
  return enc;
}


//convert date format from YYYYMMDD to DD/MM/YYYY
function convertDateFormat(obj){
	if(obj.value.length==8){
		var s=obj.value;
		obj.value=s.substr(6,2)+"/"+s.substr(4,2)+"/"+s.substr(0,4);
	}
	
}

function openModalDialog(url,h,w){
	return window.showModalDialog(
		url
		,""
		,"dialogHeight:"+h+"px;dialogWidth:"+w+"px;dialogTop:100px;dialogLeft:100px;status=yes;resizable=yes;help=no"
		);
}

function checkBeforeGotoPage(ele,ttl_pages){
	if(!isInteger(ele.value)) return false;

	var page_num=parseInt(ele.value);
	if(page_num<=0 || page_num>ttl_pages) return false;

	return true;
}

function clearAllTableRows(table_name) 
{ 
	var table_n = document.getElementById(table_name); 	
	var rownum=table_n.rows.length;
	for(var i=0;i<rownum;i++){
		table_n.deleteRow();
	}
} 
	
function clearDropDownList(select,s) {
	while (select.length > 0) {
		select.remove(0);
	}	
	if(s!=""){
		appendToSelect(select, "", document.createTextNode(s));	
	}
}

function buildDropDownList(select) {	
	var items = req.responseXML.getElementsByTagName("item");							
	
	for (var i = 0; i < items.length; i++) {
		appendToSelect(select			
			,getChildElement("value", items[i], 0)
			,document.createTextNode(getChildElement("key", items[i], 0)));	   
	}
}

function getChildElement(child_name, parentElem, index) {
	var t1=parentElem.getElementsByTagName(child_name);
	if(t1){
		if(index>=0 && index<t1.length){
			var t2=t1[index];
			if(t2){
				if(t2.firstChild){
					return t2.firstChild.nodeValue;
				}
			}
		}
	}
	return "";
	//var result = parentElem.getElementsByTagName(child_name)[index];
	//return result.firstChild.nodeValue;  
}

function appendToSelect(select, value, content) {
	var opt;
	opt = document.createElement("option");
	opt.value = value;
	opt.appendChild(content);
	select.appendChild(opt);	
}

function setPageSelector(page_id){
	var d=document;
	var f=document.thisForm;
	var ID_PREFIX="SID_page_sel_";
	var H_PREFIX="SH_page_sel_";

	var selected=false;
	var selected_idx=-1;
	var prev_tab_selected=false;
	var div_ttl=0;
	var div_nmae="";
	
	for(var i=0;i<f.elements[H_PREFIX+"id_ttl"].value;i++){
		if(f.elements[H_PREFIX+"id"+i].value==page_id){
			selected=true;
			selected_idx=i;
		}else{
			selected=false;
		}
		
		if(i==0){
			d.getElementById(ID_PREFIX+"s"+i).style.display=(!selected?"block":"none");
			d.getElementById(ID_PREFIX+"sx"+i).style.display=(selected?"block":"none");
			d.getElementById(ID_PREFIX+"d"+i).style.display=(!selected?"block":"none");
			d.getElementById(ID_PREFIX+"a"+i).style.display=(!selected?"block":"none");
			d.getElementById(ID_PREFIX+"dx"+i).style.display=(selected?"block":"none");
		}else{
			if(f.elements[H_PREFIX+"id"+(i-1)].value==page_id){
				prev_tab_selected=true;
			}else{
				prev_tab_selected=false;
			}
			
			d.getElementById(ID_PREFIX+"s"+i).style.display=((!prev_tab_selected && !selected)?"block":"none");
			d.getElementById(ID_PREFIX+"sxr"+i).style.display=(prev_tab_selected?"block":"none");
			d.getElementById(ID_PREFIX+"sxl"+i).style.display=(selected?"block":"none");
			d.getElementById(ID_PREFIX+"d"+i).style.display=(!selected?"block":"none");
			d.getElementById(ID_PREFIX+"a"+i).style.display=(!selected?"block":"none");				
			d.getElementById(ID_PREFIX+"dx"+i).style.display=(selected?"block":"none");				
		}

		//disable all div in non-selected tab
		div_ttl=f.elements[H_PREFIX+"id"+i+"_div_ttl"].value;
		for(var j=0;j<div_ttl;j++){
			if(!selected){
				div_name=f.elements[H_PREFIX+"id"+i+"_div"+j].value;
				d.getElementById(div_name).style.display="none";
			}
		}
	}
	d.getElementById(ID_PREFIX+"s"+f.elements[H_PREFIX+"id_ttl"].value).style.display=(!selected?"block":"none");				
	d.getElementById(ID_PREFIX+"sx"+f.elements[H_PREFIX+"id_ttl"].value).style.display=(selected?"block":"none");						

	
	//enable the div in selected-tab	
	div_ttl=f.elements[H_PREFIX+"id"+selected_idx+"_div_ttl"].value;
	for(var j=0;j<div_ttl;j++){
		div_name=f.elements[H_PREFIX+"id"+selected_idx+"_div"+j].value;
		d.getElementById(div_name).style.display="block";
	}

	f.PAGE_ID.value=page_id;
}

function isCheckedAnyBox(f,ele,size){
	for(var i=0;i<size;i++){
        if(f.elements[ele+i]&&f.elements[ele+i].checked){
            return true;
        }
	}
	return false;
}	

function writeElements(){
    var f=document.thisForm;
    var s=new Array();
    for(var i=0;i<f.elements.length;i++){
        s[i]="["+f.elements(i).name+"]="+f.elements(i).value+"\n";
    }
    s.sort();
    alert(s.toString());
}

// Arith functions --- start
//all function support to use direct value and form elements
function Arith_getValue(p){
    if(!isNaN(p)){
        return p;
    }else if(document.thisForm.elements[p]){
	var s=document.thisForm.elements[p].value;
        if(s==""){
            return 0;
        }else{
	    if(isNaN(s)){
	    	//alert("Arith error: "+s+" is not a number");
		return 0;
	    }
            return parseFloat(document.thisForm.elements[p].value);
        }
    }else{
        alert("Arith error: "+p+" is not found");
    }
}

function Arith_add(p1,p2){
    var v1=Arith_getValue(p1);
    var v2=Arith_getValue(p2);
    var b1=new BigDecimal(v1.toString());
    var b2=new BigDecimal(v2.toString());
    return parseFloat(b1.add(b2));
}

function Arith_sub(p1,p2){
    var v1=Arith_getValue(p1);
    var v2=Arith_getValue(p2);
    var b1=new BigDecimal(v1.toString());
    var b2=new BigDecimal(v2.toString());
    return parseFloat(b1.subtract(b2));
}

function Arith_mul(p1,p2){
    var v1=Arith_getValue(p1);
    var v2=Arith_getValue(p2);
    var b1=new BigDecimal(v1.toString());
    var b2=new BigDecimal(v2.toString());
    return parseFloat(b1.multiply(b2));
}

function Arith_div(p1,p2){
    var DEF_DIV_SCALE=10;
    return Arith_div_scale(p1,p2,DEF_DIV_SCALE);
}

function Arith_div_scale(p1,p2,scale){
    if(scale<0){
        alert("Arith.div(): "+"The scale "+scale+ " is not positive or zero");
        return -1;
    }
    var v1=Arith_getValue(p1);
    var v2=Arith_getValue(p2);
    var b1=new BigDecimal(v1.toString());
    var b2=new BigDecimal(v2.toString());
    if(b2==0) return 0;
    return parseFloat(b1.divide(b2,scale,BigDecimal.prototype.ROUND_HALF_UP));
}

function Arith_round(p,scale){
    if (scale<0){
        alert("Arith.round(): "+"The scale "+scale+ " is not positive or zero");
        return -1;
    }
    var v=Arith_getValue(p);
    var b=new BigDecimal(v.toString());
    var one=new BigDecimal("1");
    return parseFloat(b.divide(one,scale,BigDecimal.prototype.ROUND_HALF_UP));
}
//Arith functions --- end

//TextArea Function --- start
function onTextAreaResize(textarea,def_rows){
	var t=textarea.value;
	var k=t.split("\n");
	
	if(textarea.value!=""){
		textarea.wrap="OFF";
	}else{
		textarea.wrap="SOFT";
	}

	if(k.length>def_rows){
		textarea.rows=k.length;
	}else{
		textarea.rows=def_rows;
	}
}

function onTextAreaRestore(textarea,def_rows){
	textarea.rows=def_rows;
	textarea.wrap="SOFT";
}

function onTextAreaKeypress(textarea,def_rows){
	textarea.onkeyup=function(){
		onTextAreaResize(textarea,def_rows);
	}
}
//TextArea Function --- end

function addValidationArray(name,fin){
    var f=document.thisForm;
    for(var i=0;i<fin[3];i++){ //fin[3] is the number of rows
        if(f.elements[name+i+"_fd"]==null) continue;
        
        var row_fd=f.elements[name+i+"_fd"].value.split(";");
        var row_fn=f.elements[name+i+"_fn"].value.split(";");
        var row_fv=f.elements[name+i+"_fv"].value.split(";");
        
        for(var j=0;j<row_fd.length;j++){
            fin[0][fin[0].length]=row_fd[j];
            fin[1][fin[1].length]=row_fn[j];
            fin[2][fin[2].length]=row_fv[j];
        }
    }
}    
    

//Start---------------------Modal Window -----------------
//Usage: ModalDialogShow("xxxx.jsp",850,500);
var ModalDialogWindow;
var ModalDialogInterval;

function ModalDialogMaintainFocus()
{
  try
  {
    if (ModalDialogWindow.opener.closed)
     {
        window.clearInterval(ModalDialogInterval);
	ModalDialogWindow.close();
     }
  }
  catch (everything) {   }
}
        
function ModalDialogShow(url,w,h)
 {
	if(ModalDialogWindow){
		if(!ModalDialogWindow.closed) ModalDialogWindow.close();
	}
   var args='width='+w+',height='+h+',left=100,top=100,toolbar=0,';
       args+='location=0,status=1,menubar=0,scrollbars=1,resizable=0';  

   ModalDialogWindow=window.open(url,"",args); 
   ModalDialogWindow.focus(); 
   ModalDialogInterval = window.setInterval("ModalDialogMaintainFocus()",5);
   return ModalDialogWindow;
 }
function onBodyUnload(){
	if(!ModalDialogWindow) return;
	if(!ModalDialogWindow.closed) ModalDialogWindow.close();
}
//End---------------------Modal Window -----------------

//--------------JSExprList--------------
//-- Provides support to com.js.Common.JSExprList --
function JSExprUpdate(f,op){
	if(!f.op){
		alert("f.elements[op] does not exist");
		return;
	}
	f.op.value=op;
	var s=AjaxRequest.submit(
		f,{
		'url':'../servlet/com.js.Controller.ActionDispatcherAJAXServlet'
		,'onSuccess':
			function(req){
				var f=document.thisForm;
				try{
					eval(req.responseText);
				}catch(e){
					alert(e.description+"\n"+req.responseText);
				}

			}
		,'onError':function(req){alert(req.responseText);}
		});
	return;
}
//-- Provides support to com.js.Common.JSExprList --

var _validateBeforeSubmit_SUBMITTED=false;
function validateBeforeSubmit(f,op,func){
	if(_validateBeforeSubmit_SUBMITTED) return;
	var f=document.thisForm;
	if(!f.op){
		_validateBeforeSubmit_SUBMITTED=false;
		alert("f.elements[op] is not defined");
		return;
	}
	f.op.value=op;
	var s=AjaxRequest.submit(
		f,{
		'url':'../servlet/com.js.Controller.ActionDispatcherAJAXServlet'
		,'onSuccess':
			function(req){
				_validateBeforeSubmit_SUBMITTED=false;
				if(req.responseText==""){
					func.call();
				}else{
					alert(req.responseText);
				}
			}
		,'onError':function(req){
				_validateBeforeSubmit_SUBMITTED=false;
				if(req.status!=12030){
					alert('Error='+req.statusText+'('+req.status+')');
				}else{
					validateBeforeSubmit(f,op,func);
				}
			}
		,'onLoading':function(req){_validateBeforeSubmit_SUBMITTED=true;}
		});
	return;
}

