


// 每增加一個檔案自動給下一個可 upload file 的元件
function addFile(Container, width){
    var str = '<INPUT id="File" name="File" type="file" size="50" style="width:' + width + ';" onchange="addFile(\'' + Container + '\',\'' + width + '\')">' ;
    document.getElementById(Container).insertAdjacentHTML("beforeEnd",str) ;
}

// 檢查必要的輸入值
function checkFormFields(obj1, obj2, obj3, obj4, obj5, obj6, obj7, obj8, obj9){
var sErrorMsg = "";
	if (obj1.value == "")
		sErrorMsg += "\n" + obj1.errorMsg;
	if (obj2 != null && obj2.value == "")
		sErrorMsg += "\n" + obj2.errorMsg;
	if (obj3 != null && obj3.value == "")
		sErrorMsg += "\n" + obj3.errorMsg;
	if (obj4 != null && obj4.value == "")
		sErrorMsg += "\n" + obj4.errorMsg;
	if (obj5 != null && obj5.value == "")
		sErrorMsg += "\n" + obj5.errorMsg;
	if (obj6 != null && obj6.value == "")
		sErrorMsg += "\n" + obj6.errorMsg;
	if (obj7 != null && obj7.value == "")
		sErrorMsg += "\n" + obj7.errorMsg;
	if (obj8 != null && obj8.value == "")
		sErrorMsg += "\n" + obj8.errorMsg;
	if (obj9 != null && obj9.value == "")
		sErrorMsg += "\n" + obj9.errorMsg;
	
	if ( sErrorMsg != ""){
		alert ( "Lack of below values :\n\n" + sErrorMsg.substring(1));
		return false;
	}
	else
		return true;
}


function getDomainName(){
	url=window.location
	url=url.toString()
	url=url.substring(7,url.length)
	tmp=url.search('/')
	url=url.substring(0,tmp)
	tmp=url.search(':')
	if(tmp>-1){
		url=url.substring(0,tmp)
	}
	
	return url;
}


function rzCC(s){
	// thanks http://www.ruzee.com/blog/2006/07/\
	// retrieving-css-styles-via-javascript/
	for(var exp=/-([a-z])/; 
	exp.test(s); 
	s=s.replace(exp,RegExp.$1.toUpperCase()));
	return s;
}
function _setStyle(element, declaration) {
	if (declaration.charAt(declaration.length-1)==';')
	declaration = declaration.slice(0, -1);
	var k, v;
	var splitted = declaration.split(';');
	for (var i=0, len=splitted.length; i<len; i++) {
	k = rzCC(splitted[i].split(':')[0]);
	v = splitted[i].split(':')[1];
	eval("element.style."+k+"='"+v+"'");

	}
}


function getURLAttributes( sAtt){
	if (sAtt.length > 0){
		if (sAtt.substring(0,1) == "?")
			sAtt = sAtt.substring(1);
		
		var arAttItems = sAtt.split("&");
		for (var i=0; i< arAttItems.length; i++){
			arAttItems[i] = arAttItems[i].split("=");
		}
		
		return arAttItems;
	}
}


function $(element) {
	return element = document.getElementById(element);
};


// 取小數點後的位數
function formatFloat(src, pos){
	return Math.round(src*Math.pow(10, pos))/Math.pow(10, pos);
}


function trim(str){
    //if(!str || typeof str != 'string')
    //   return null;

    return str.replace(/^[\s]+/,'').replace(/[\s]+$/,'').replace(/[\s]{2,}/,' ');
}





// ///////////////////////////////////////////////////////////////////////
//	==========  Start Validation
// ///////////////////////////////////////////////////////////////////////
var dtCh= "/";
var tmCh= ":";
var minYear=1900;
var maxYear=2100;

function isInteger(s){
	var i;
    for (i = 0; i < s.length; i++){   
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}

function stripCharsInBag(s, bag){
	var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++){   
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function daysInFebruary (year){
	// February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}
function DaysArray(n) {
	for (var i = 1; i <= n; i++) {
		this[i] = 31
		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
		if (i==2) {this[i] = 29}
   } 
   return this
}

function isDate(dtStr){
	var daysInMonth = DaysArray(12)
	var pos1=dtStr.indexOf(dtCh)
	var pos2=dtStr.indexOf(dtCh,pos1+1)
	var strYear=dtStr.substring(0,pos1)
	var strMonth=dtStr.substring(pos1+1,pos2)
	var strDay=dtStr.substring(pos2+1)
	strYr=strYear
	if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
	if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
	for (var i = 1; i <= 3; i++) {
		if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
	}
	month=parseInt(strMonth)
	day=parseInt(strDay)
	year=parseInt(strYr)
	if (pos1==-1 || pos2==-1){
		alert("The date format should be : mm/dd/yyyy")
		return false
	}
	if (strMonth.length<1 || month<1 || month>12){
		alert("Please enter a valid month")
		return false
	}
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
		alert("Please enter a valid day")
		return false
	}
	if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
		alert("Please enter a valid 4 digit year between "+minYear+" and "+maxYear)
		return false
	}
	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
		alert("Please enter a valid date")
		return false
	}
return true
}

function isTime(tmStr){
	var pos1=tmStr.indexOf(tmCh)
	var pos2=tmStr.indexOf(tmCh,pos1+1)
	var strHour=tmStr.substring(0,pos1)
	var strMinute=tmStr.substring(pos1+1,pos2)
	var strSecond=tmStr.substring(pos2+1)
	
	try{
		var iHour = parseInt( strHour);
		var iMinute = parseInt( strMinute);
		var iSecond = parseInt( strSecond);

		if ( iHour < 0 || iHour > 23 || iMinute < 0 || iMinute > 59 || iSecond < 0 || iSecond > 59)
			return false;
		else
			return true;
	}
	catch(e){
		return false;
	}
}


function ValidateDateTime(datetime){
	var emposi=datetime.indexOf(" ");
	if (emposi == -1){
		return false;
	}
	else{
		return isDate( datetime.substring(0,emposi)) && isTime( datetime.substring(emposi+1));
	}

}
// ///////////////////////////////////////////////////////////////////////
//	==========  End Validation
// ///////////////////////////////////////////////////////////////////////


// ///////////////////////////////////////////////////////////////////////
//	==========  For PSC
// ///////////////////////////////////////////////////////////////////////
function MouseHoverURL(obj, type, objAnchor){
	if (type == 0){
		obj.className = "linkURL_MouseOut";
		if ( objAnchor != null)
			objAnchor.className="formatLink";
	}
	else if (type == 1){
		obj.className = "linkURL_MouseOver";
		if ( objAnchor != null)
			objAnchor.className="formatLink_MouseOver";
	}
	
}
// automatic change tool by module and casename in client
function change_ddlTool(comFAB, comModule, comTool, haveAll){
	var sFAB;
	var sModule;
	comFAB == null ? sFAB = "--ALL--" : sFAB = comFAB.options[comFAB.selectedIndex].value;
	comModule == null ? sModule = "--ALL--" : sModule = comModule.options[comModule.selectedIndex].value;

	var iCount = data.length;
	var iOTCount = comTool.length;
	obj = document.createElement('option');
	if (haveAll){
		obj.text = "--ALL--";
		obj.value = "--ALL--";
	}
	else{
		obj.text = "";
		obj.value = "";
	}

	
	comTool.document.clear();
	while(iOTCount--){
		comTool.options[iOTCount] = null;
	}
	comTool.add(obj);
	for (i=0; i<iCount; i++){
		if ((sFAB == "--ALL--" || data[i][0] == sFAB) &&
			(sModule == "--ALL--" || data[i][1] == sModule)){
			obj = document.createElement('option');
			obj.text = data[i][2];
			obj.value = data[i][2];
			comTool.add(obj);
		}
	}
}
// ========== End For PSC
// ///////////////////////////////////////////////////////////////////////



// ///////////////////////////////////////////////////////////////////////
//	========== Ajax object 
// ///////////////////////////////////////////////////////////////////////
// Ajax 變數
var xmlHttp;
var requestURL = ''; 
var is_ie = (navigator.userAgent.indexOf('MSIE') >= 0) ? 1 : 0; 
var is_ie5 = (navigator.appVersion.indexOf("MSIE 5.5")!=-1) ? 1 : 0; 
var is_opera = ((navigator.userAgent.indexOf("Opera 6")!=-1)||(navigator.userAgent.indexOf("Opera/6")!=-1)) ? 1 : 0; 
//netscape, safari, mozilla behave the same??? 
var is_netscape = (navigator.userAgent.indexOf('Netscape') >= 0) ? 1 : 0; 

requestURL = 'http://' + getDomainName() + '/FDC/Ajax_DataQuery.aspx?';

function GetXmlHttpObject(handler) { 
	var objXmlHttp = null;    //Holds the local xmlHTTP object instance 

	//Depending on the browser, try to create the xmlHttp object 
	if (is_ie){ 
		//The object to create depends on version of IE 
		//If it isn't ie5, then default to the Msxml2.XMLHTTP object 
		var strObjName = (is_ie5) ? 'Microsoft.XMLHTTP' : 'Msxml2.XMLHTTP'; 
	        
		//Attempt to create the object 
		try{ 
			objXmlHttp = new ActiveXObject(strObjName); 
			objXmlHttp.onreadystatechange = handler; 
		} 
		catch(e){ 
		//Object creation errored 
			alert('IE detected, but object could not be created. Verify that active scripting and activeX controls are enabled'); 
			return; 
		} 
	} 
	else if (is_opera){ 
		//Opera has some issues with xmlHttp object functionality 
		alert('Opera detected. The page may not behave as expected.'); 
		return; 
	} 
	else{ 
		// Mozilla | Netscape | Safari 
		objXmlHttp = new XMLHttpRequest(); 
		objXmlHttp.onload = handler; 
		objXmlHttp.onerror = handler; 
	} 
	    
	//Return the instantiated object 
	return objXmlHttp; 
} 

// XMLHttp send GET request 
function xmlHttp_Get(xmlhttp, url) { 
	xmlhttp.open('GET', url, true); 
	xmlhttp.send(null); 
} 


function AJAX_ReturnAddToOptions( ObjSel, oXMLTag, AssignEmptyAtFirst, ReturnAllValue){
	clearSelectOptions(ObjSel);
	var Data = "";
	
	if ( AssignEmptyAtFirst){
		obj = document.createElement('option');
		obj.text = "";
		obj.value = "";
		ObjSel.add(obj);
	}
	
	for(i=0; i< oXMLTag.length; i++){
		if (oXMLTag[i].firstChild != null){ // 如果是空字串則此處為 null
			var sText = oXMLTag[i].firstChild.data;
			obj = document.createElement('option');
			obj.text = sText;
			obj.value = sText;
			ObjSel.add(obj);
			
			if ( ReturnAllValue)
				Data += "," + sText;
		}
	}
	
	if (Data.length > 0)
		Data = Data.substring(1);
	return Data;
}
function AJAX_ReturnXMLTagValue( oXMLTag){
	var Data = "";
	
	for(i=0; i< oXMLTag.length; i++){
		if (oXMLTag[i].firstChild != null){ // 如果是空字串則此處為 null
			var sText = oXMLTag[i].firstChild.data;
			Data += "," + sText;
		}
	}
	
	if (Data.length > 0)
		Data = Data.substring(1);
	return Data;
}
// ========== End  Ajax object
// ///////////////////////////////////////////////////////////////////////


// ///////////////////////////////////////////////////////////////////////
// =========================== Select object =============================
// ///////////////////////////////////////////////////////////////////////
function insertByLocation(oSelect, newText, newValue)
{
  if (oSelect.length == 0) {
    var newOpt1 = new Option(newText, newValue);
    oSelect.options[0] = newOpt1;
    oSelect.selectedIndex = 0;
  } else if (oSelect.selectedIndex != -1) {
    var selText = new Array();
    var selValues = new Array();
    var selIsSel = new Array();
    var newCount = -1;
    var newSelected = -1;
    var i;
    for(i=0; i<oSelect.length; i++)
    {
      newCount++;
      if (newCount == oSelect.selectedIndex) {
        selText[newCount] = newText;
        selValues[newCount] = newValue;
        selIsSel[newCount] = false;
        newCount++;
        newSelected = newCount;
      }
      selText[newCount] = oSelect.options[i].text;
      selValues[newCount] = oSelect.options[i].value;
      selIsSel[newCount] = oSelect.options[i].selected;
    }
    for(i=0; i<=newCount; i++)
    {
      var newOpt = new Option(selText[i], selValues[i]);
      oSelect.options[i] = newOpt;
      oSelect.options[i].selected = selIsSel[i];
    }
  }
}

// =======================================================================
// SelectOption 物件中新增一項目到指定的位置
// =======================================================================
function appendByLocation(oSelect, newText, newValue)
{
  if (oSelect.length == 0) {
    var newOpt1 = new Option(newText, newValue);
    oSelect.options[0] = newOpt1;
    oSelect.selectedIndex = 0;
  } else if (oSelect.selectedIndex != -1) {
    var selText = new Array();
    var selValues = new Array();
    var selIsSel = new Array();
    var newCount = -1;
    var newSelected = -1;
    var i;
    for(i=0; i<oSelect.length; i++)
    {
      newCount++;
      selText[newCount] = oSelect.options[i].text;
      selValues[newCount] = oSelect.options[i].value;
      selIsSel[newCount] = oSelect.options[i].selected;
      
      if (newCount == oSelect.selectedIndex) {
        newCount++;
        selText[newCount] = newText;
        selValues[newCount] = newValue;
        selIsSel[newCount] = false;
        newSelected = newCount - 1;
      }
    }
    for(i=0; i<=newCount; i++)
    {
      var newOpt = new Option(selText[i], selValues[i]);
      oSelect.options[i] = newOpt;
      oSelect.options[i].selected = selIsSel[i];
    }
  }
}

// =======================================================================
// SelectOption 物件中插入一項目並與舊的項目做排序
// =======================================================================
function insertAndSortASC(oSelect, newText, newValue){
	if (newText == "" || newValue == "")
		return;
	if (oSelect.length == 1 && oSelect.options[0].text == ''){
		oSelect.remove(0);
	}
	
	if (oSelect.length == 0) {
		var newOpt1 = new Option(newText, newValue);
		oSelect.options[0] = newOpt1;
		oSelect.selectedIndex = 0;
	} 
	else {
		var selText = new Array();
		var selValues = new Array();
		var selIsSel = new Array();
		var newCount = -1;
		var SelectedIndex = -1;
		var i;
		for (i=0; i<oSelect.length; i++){
			if (newText == oSelect.options[i].text)
			return;

			newCount++;
			if ( newCount == i && newText < oSelect.options[i].text){
				selText[newCount] = newText;
				selValues[newCount] = newValue;
				SelectedIndex = newCount;
				newCount++;
			}
			selText[newCount] = oSelect.options[i].text;
			selValues[newCount] = oSelect.options[i].value;
		}
		if ( newCount == oSelect.length -1){
			newCount++;
			selText[newCount] = newText;
			selValues[newCount] = newValue;
			SelectedIndex = newCount;
		}
	}
	
	for(i=0; i<=newCount; i++){
		var newOpt = new Option(selText[i], selValues[i]);
		oSelect.options[i] = newOpt;
		oSelect.selectedIndex = SelectedIndex;
	}
}


// =======================================================================
// SelectOption 物件中內容的清除 (By index)
// =======================================================================
function removeByIndex(oSelect, removeIndex){
  var selIndex = oSelect.selectedIndex;
  if (selIndex != -1) {
    for(i=oSelect.length-1; i>=0; i--)
    {
      if(oSelect.options[i].selected)
      {
        oSelect.options[i] = null;
      }
    }
    if (oSelect.length > 0) {
      oSelect.selectedIndex = selIndex == 0 ? 0 : selIndex - 1;
    }
  }
}
// =======================================================================
// SelectOption 物件中內容的清除 (By selected location)
// =======================================================================
function removeByLocation(oSelect){
  var selIndex = oSelect.selectedIndex;
  if (selIndex != -1) {
    for(i=oSelect.length-1; i>=0; i--)
    {
      if(oSelect.options[i].selected)
      {
        oSelect.options[i] = null;
      }
    }
    if (oSelect.length > 0) {
      oSelect.selectedIndex = selIndex == 0 ? 0 : selIndex - 1;
    }
  }
}
// =======================================================================
// SelectOption 物件中內容的清除 (全部)
// =======================================================================
function clearSelectOptions(obj){
	while (obj.length > 0){
		obj.options.remove(0);
	}
}


// =======================================================================
// 二個 SelectOption 物件中內容的移動 (選取/移除)
// OperationNum=1 -> 從 List 選到 Selected
// OperationNum=2 -> 從 Selected 選到 List
// =======================================================================
function ListAndSelectedOperation( ObjAllList, ObjSelected, OperationNum, MaxCount){
	var arAllList;
	var sToList="";
	var arSelected;
	var sToSelected="";

	if ( MaxCount == null || MaxCount <=0)
		MaxCount = 10000;
	if ( OperationNum == 1)
		MaxCount = MaxCount - ObjSelected.length;
	else if ( OperationNum == 2)
		MaxCount = MaxCount - ObjAllList.length;


	// -------- 取得 List 物件上的值 ----------------------
	if ( ObjAllList.length >= 1){
		// initial array
		arAllList = new Array(ObjAllList.length);
		
		var i=0;
		for (i; i< ObjAllList.length; i++){
			// 目前 List 物件上值的陣列
			arAllList[i] = ObjAllList.options[i].value;
			
			// List 物件上選擇的項目
			if (ObjAllList.options[i].selected){
				if ( MaxCount > 0)
					sToSelected += "," + ObjAllList.options[i].value;
				else
					ObjAllList.options[i].selected = false;
					
				MaxCount--;
			}
		}
		if ( sToSelected.length > 0)
			sToSelected = sToSelected.substring(1);
	}
	else{
		// initial array
		arAllList = new Array ();
	}
	// ----------------------------------------------
	
	// -------- 取得 Selected 物件上的值 ----------------------
	if ( ObjSelected.length >= 1){
		// initial array
		arSelected = new Array(ObjSelected.length);

		var i=0;
		for (i; i< ObjSelected.length; i++){
			// 目前 Selected 物件上值的陣列
			arSelected[i] = ObjSelected.options[i].value;

			// Selected 物件上選擇的項目
			if (ObjSelected.options[i].selected){
				if ( MaxCount > 0)
					sToList += "," + ObjSelected.options[i].value;
				else
					ObjSelected.options[i].selected = false;
					
				MaxCount--;
			}
		}
		if ( sToList.length > 0)
			sToList = sToList.substring(1);
	}
	else{
		// initial array
		arSelected = new Array();
	}
	// ----------------------------------------------

	var arTemp;
	if ( OperationNum == 1 && arAllList.length > 0){		// 從 List 選到 Selected
		var arNew;
		if ( sToSelected.length > 0){
			arTemp = sToSelected.split(",");
			arNew = arSelected.concat(arTemp);
		}
		else
			arNew = arSelected;
		arNew.sort();
		clearSelectOptions(ObjSelected);

		var svTmp = "";
		for (i=0; i< arNew.length; i++){
			if ( svTmp != arNew[i]){
				ObjSelected.options.add(new Option(arNew[i], arNew[i]));
				svTmp = arNew[i];
			}
		}
		
		// 移除來源選取的項目
		removeByLocation (ObjAllList);
	}
	else if ( OperationNum == 2 && arSelected.length > 0){	// 從 Selected 選到 List
		var arNew;
		if ( sToList.length > 0){
			arTemp = sToList.split(",");
			arNew = arAllList.concat(arTemp);
		}
		else
			arNew = arAllList;
		arNew.sort();
		clearSelectOptions(ObjAllList);
		
		var svTmp = "";
		for (i=0; i< arNew.length; i++){
			if ( svTmp != arNew[i]){
				ObjAllList.options.add(new Option(arNew[i], arNew[i]));
				svTmp = arNew[i];
			}
		}
		
		// 移除來源選取的項目
		removeByLocation (ObjSelected);
	}
}

// ==========================================
// 取得 SelectOption 物件上的值
// ==========================================
function getSelectionValue( obj, SperateSign){
	var sRtn = "";
	
	if ( obj.length >= 1){
		for (i=0; i< obj.length; i++){
			// 目前 Selected 物件上值的陣列
			sRtn += "," + obj.options[i].value;
		}
		if ( sRtn.length > 0)
			sRtn = sRtn.substring(1);
	}
	
	return sRtn;
}

// ========== End Select Object
// ///////////////////////////////////////////////////////////////////////




// ///////////////////////////////////////////////////////////////////////
// =========================== Radio object =============================
// ///////////////////////////////////////////////////////////////////////
function getRadioSelectedIndex(oRadio){
	var iSelectedIndex = 0;
	for(iSelectedIndex; iSelectedIndex< oRadio.length; iSelectedIndex++){
		if (oRadio[iSelectedIndex].checked)
			break;
	}

	return iSelectedIndex;
}
// ========== End Radio Object
// ///////////////////////////////////////////////////////////////////////

