
//**********************************************************************
//功能說明 : 選擇的日期是否正確				                           '
//傳入參數 : 選擇的日期					                               '
//傳回參數 : Boolean : 若結果為True ,表示輸入值正確                    '
//                     若結果為False,表示輸入值不正確                  '
//**********************************************************************
function CheckDate(pYear,pMonth,pDay)
{
	theDate = new Date();
	YYYY = theDate.getFullYear();
	MM   = theDate.getMonth()+1; //javascript所傳回的月份會比實際少1，所以加1
	DD   = theDate.getDate();
    
	var tYY
	var tMM
	var tDay

	tYY  = pYear   //取得所選年份
	tMM  = pMonth  //取得所選月份
	tDay = pDay    //取得所選取的日期

	if (tYY == "" || tMM == "" || tMM > 12 || tMM < 0 || tDay == "")
	{
	    alert("日期有錯喔！請您重新選擇日期。");
	    return false;
	}	
		
	MonthDays = getDays(tYY, tMM);//取得當月的天數
	if (tDay > MonthDays)//所選的日期比當月天數大(例如在2月時選取30號)
	{   
	    alert(tMM+"月沒有"+tDay+"號喔！請您重新選擇日期。");
	    return false;
    	}
	return true;
}

//取得當月的天數
function getDays(pYear, pMM)
{
    var Days;
    pYear = parseInt(pYear);
	pMM = parseInt(pMM);
	switch(pMM)
    {
         case 1:
         case 3:
         case 5:
         case 7:
         case 8:
         case 10:
         case 12:
              Days = 31;
              break;
         case 4:
         case 6:
         case 9:
         case 11:
              Days = 30;
              break;
         case 2://考慮閏年及閏月
              //if (((YYYY % 4 == 0) && (YYYY % 100 != 0)) || (YYYY % 400 == 0))
              if (((pYear % 4 == 0) && (pYear % 100 != 0)) || (pYear % 400 == 0))
              {  Days = 29;}
              else
              {  Days = 28;}
              break;
    }
	return Days;
}


//**********************************************************************
//功能說明 : 選擇的日期是否正確(沒有提示訊息的)				                           '
//傳入參數 : 選擇的日期					                               '
//傳回參數 : Boolean : 若結果為True ,表示輸入值正確                    '
//                     若結果為False,表示輸入值不正確                  '
//**********************************************************************
function CheckDateNone(pYear,pMonth,pDay)
{
	theDate = new Date();
	YYYY = theDate.getFullYear();
	MM   = theDate.getMonth()+1; //javascript所傳回的月份會比實際少1，所以加1
	DD   = theDate.getDate();
    
	var tYY
	var tMM
	var tDay

	tYY  = pYear   //取得所選年份
	tMM  = pMonth  //取得所選月份
	tDay = pDay    //取得所選取的日期

	if (tYY == "" || tMM == "" || tMM > 12 || tMM < 0 || tDay == "")
	{
	    //alert("日期有錯喔！請您重新選擇日期。");
	    return false;
	}	
		
	MonthDays = getDays(tYY, tMM);//取得當月的天數
	if (tDay > MonthDays)//所選的日期比當月天數大(例如在2月時選取30號)
	{   
	    //alert(tMM+"月沒有"+tDay+"號喔！請您重新選擇日期。");
	    return false;
    	}
	return true;
}

//取得當月的天數
function getDays(pYear, pMM)
{
    var Days;
    pYear = parseInt(pYear);
	pMM = parseInt(pMM);
	switch(pMM)
    {
         case 1:
         case 3:
         case 5:
         case 7:
         case 8:
         case 10:
         case 12:
              Days = 31;
              break;
         case 4:
         case 6:
         case 9:
         case 11:
              Days = 30;
              break;
         case 2://考慮閏年及閏月
              //if (((YYYY % 4 == 0) && (YYYY % 100 != 0)) || (YYYY % 400 == 0))
              if (((pYear % 4 == 0) && (pYear % 100 != 0)) || (pYear % 400 == 0))
              {  Days = 29;}
              else
              {  Days = 28;}
              break;
    }
	return Days;
}




//================================================================================'
//功能說明 : 編審輸入的值是否為數字				                                  '
//傳入參數 : 要編審的欄位值					                                      '
//傳回參數 : Boolean : 若結果為True ,表示輸入值正確                               '
//                     若結果為False,表示輸入值不正確                             '
//================================================================================'
function gfcChkNum(pValue)
{
	var strValue = pValue.toUpperCase( );
	var intlen = strValue.length;
	
	for (var i = 0;i<intlen;i++) 
	{
		if(((strValue.charAt(i) >= "0") && (strValue.charAt(i) <= "9")) == false)
		{
			alert('輸入的欄位, 必需為數字!!')                        
			return false;
		}  
	}
	return true;
}


//========================================================================='
//功能說明 : 編審數值欄位的輸入值                                          '
//傳入參數 : 1.pNumStr : 數值                                              '
//           2.pChkZero使用功能(0,1,2)                                     '
//             若pChkZero = 0 : 不Check欄位值正負數                        '
//             若pChkZero = 1 : Check欄位值必須大於0                       '
//             若pChkZero = 2 : Check欄位值必須 >=0                        '
//           2.pChkInt使用功能(0,1)                                        '
//             若pChkInt = 0 : 不Check欄位值為整數                         '
//             若pChkInt = 1 : Check欄位值為整數                           '
//傳回參數 : Boolean : 若結果為True ,表示輸入值正確                        '
//                     若結果為False,表示輸入值不正確                      '
//========================================================================='
function gfcChkNumValue(pNumStr,pChkZero,pChkInt)
{   
    if (pNumStr == "") return true;

    if (isNaN(pNumStr) == true)
    {         
        alert("欄位值須為數值 !");
        return false;
    }
    switch(pChkZero)
    {
        case 0:
           break;
        case 1:
           if (pNumStr <= 0)
           {
               alert("數值必須大於 0 !");
               return false;
           }
           break;
        case 2:
           if (pNumStr < 0)
           {
               alert("數值必須大於等於 0 !");
               return false;
           }
           break;
    }
    if (pChkInt == 1)
    {     
        if (parseInt(pNumStr) != pNumStr)
        {				
            alert("欄位值須為整數 !");
            return false;
        }	
    }       
    return true;
}















//LTrim(string) : Returns a copy of a string without leading spaces.
//==================================================================
        function LTrim(str)
        /***
                PURPOSE: Remove leading blanks from our string.
                IN: str - the string we want to LTrim

                RETVAL: An LTrimmed string!
        ***/
        {
                var whitespace = new String(" \t\n\r");

                var s = new String(str);

                if (whitespace.indexOf(s.charAt(0)) != -1) {
                    // We have a string with leading blank(s)...

                    var j=0, i = s.length;

                    // Iterate from the far left of string until we
                    // don't have any more whitespace...
                    while (j < i && whitespace.indexOf(s.charAt(j)) != -1)
                        j++;


                    // Get the substring from the first non-whitespace
                    // character to the end of the string...
                    s = s.substring(j, i);
                }

                return s;
        }

//RTrim(string) : Returns a copy of a string without trailing spaces.
//==================================================================
        function RTrim(str)
        /***
                PURPOSE: Remove trailing blanks from our string.
                IN: str - the string we want to RTrim

                RETVAL: An RTrimmed string!
        ***/
        {
                // We don't want to trip JUST spaces, but also tabs,
                // line feeds, etc.  Add anything else you want to
                // "trim" here in Whitespace
                var whitespace = new String(" \t\n\r");

                var s = new String(str);

                if (whitespace.indexOf(s.charAt(s.length-1)) != -1) {
                    // We have a string with trailing blank(s)...

                    var i = s.length - 1;       // Get length of string

                    // Iterate from the far right of string until we
                    // don't have any more whitespace...
                    while (i >= 0 && whitespace.indexOf(s.charAt(i)) != -1)
                        i--;


                    // Get the substring from the front of the string to
                    // where the last non-whitespace character is...
                    s = s.substring(0, i+1);
                }

                return s;
        }

//Trim(string) : Returns a copy of a string without leading or
//               trailing spaces
//=============================================================
        function Trim(str)
        /***
                PURPOSE: Remove trailing and leading blanks from our string.
                IN: str - the string we want to Trim

                RETVAL: A Trimmed string!
        ***/
        {
                return RTrim(LTrim(str));
        }

//Len(String) : Returns the number of characters in a string
//===========================================================

        function Len(str)
        /***
                IN: str - the string whose length we are interested in

                RETVAL: The number of characters in the string
        ***/
        {  return String(str).length;  }

//Left(string, length): Returns a specified number of characters from the
//                      left side of a string
//========================================================================

        function Left(str, n)
        /***
                IN: str - the string we are LEFTing
                    n - the number of characters we want to return

                RETVAL: n characters from the left side of the string
        ***/
        {
                if (n <= 0)     // Invalid bound, return blank string
                        return "";
                else if (n > String(str).length)   // Invalid bound, return
                        return str;                // entire string
                else // Valid bound, return appropriate substring
                        return String(str).substring(0,n);
        }

//Right(string, length): Returns a specified number of characters from the
//                       right side of a string
//========================================================================

        function Right(str, n)
        /***
                IN: str - the string we are RIGHTing
                    n - the number of characters we want to return

                RETVAL: n characters from the right side of the string
        ***/
        {
                if (n <= 0)     // Invalid bound, return blank string
                   return "";
                else if (n > String(str).length)   // Invalid bound, return
                   return str;                     // entire string
                else { // Valid bound, return appropriate substring
                   var iLen = String(str).length;
                   return String(str).substring(iLen, iLen - n);
                }
        }

//Mid(string, start, length): Returns a specified number of characters from a
//                            string
//============================================================================

        function Mid(str, start, len)
        /***
                IN: str - the string we are LEFTing
                    start - our string's starting position (0 based!!)
                    len - how many characters from start we want to get

                RETVAL: The substring from start to start+len
        ***/
        {
                // Make sure start and len are within proper bounds
                if (start < 0 || len < 0) return "";

                var iEnd, iLen = String(str).length;
                if (start + len > iLen)
                        iEnd = iLen;
                else
                        iEnd = start + len;

                return String(str).substring(start,iEnd);
        }

	
//================================================================================'
//功能說明 : 將數字的Format轉換有 "," 的Format		                          '
//傳入參數 : 數字				                                  '
//傳回參數 : 數字                             					  '
//================================================================================'
	function formatCurrency(num) {
		num = num.toString().replace(/\$|\,/g,'');
		if(isNaN(num))
		num = "0";
		sign = (num == (num = Math.abs(num)));
		num = Math.floor(num*100+0.50000000001);
		cents = num%100;
		num = Math.floor(num/100).toString();
		if(cents<10)
		cents = "0" + cents;
		for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
		num = num.substring(0,num.length-(4*i+3))+','+
		num.substring(num.length-(4*i+3));
	
		return (((sign)?'':'-') + num);
//		return (((sign)?'':'-') + num + '.' + cents);
	//	return (((sign)?'':'-') + '$' + num + '.' + cents);
	}	
	
	
	
	
	
//**********************************************************************
//功能說明 : 檢查必填欄位是否空白				                       '
//傳入參數 : 將要檢查的欄位用逗號組合起來傳入			               '
//傳回參數 : Boolean : 若結果為True ,表示輸入值正確                    '
//                     若結果為False,表示輸入值不正確                  '
//**********************************************************************
function CheckEmpty(param){
   var ss
   ss = param.split(",");
	for(var icount = 0; icount < ss.length; icount++) 
	{ 
	   if(ss[icount]=="")
	   {
	     alert('有必填欄位空白喔'); 
	     return false;
	   }  
	}
	return true;
}
	
//**********************************************************************
//功能說明 : 檢查必填欄位是否空白				                       '
//傳入參數 : 將要檢查的欄位用逗號組合起來傳入			               '
//傳回參數 : Boolean : 若結果為True ,表示輸入值正確                    '
//                     若結果為False,表示輸入值不正確                  '
//**********************************************************************
function CheckEmptyNoneAlert(param){
   var ss

   ss = param.split(",");
	for(var icount = 0; icount < ss.length; icount++) 
	{ 
	   if(ss[icount]=="")
	   {
	   alert('有必填欄位空白喔'); 
	     return false;
	   }  
	}
	return true;
}	
	
	

//================================================================================'
//功能說明 : 檢查輸入的值是否為數字			                          '
//傳入參數 : 要檢查的欄位值					                  '
//傳回參數 : Boolean : 若結果為True ,表示輸入值正確                               '
//                     若結果為False,表示輸入值不正確                             '
//================================================================================'
function CheckInt(field)
{
	var strValue = field.toUpperCase( );
	var intlen = strValue.length;
	
	for (var i = 0;i<intlen;i++) 
	{
		if(((strValue.charAt(i) >= "0") && (strValue.charAt(i) <= "9")) == false)
		{
			alert("輸入的數字有問題喔");                       
			return false;
		}  
	}
            return true;
}




//**********************************************************************
//功能說明 : 檢查起始日期不能小於結束日期
//傳入參數 : 起始日西元年月日 終止日西元年月日
//傳回參數 : Boolean : 若結果為True ,表示輸入值正確                    '
//                     若結果為False,表示輸入值不正確                  '
//**********************************************************************
function CheckBetweenDate(strsd,stred)
{
	if(strsd =="//" || stred == "//"){
		return false;
	}
	var sd = new Date(strsd);
	var ed = new Date(stred);

	if((sd.getTime() - ed.getTime()) > 0){
		alert("起始日不得小於終止日");
		return false;
	}
            return true;
}



//**********************************************************************
//功能說明 : 檢查起始日期不能小於結束日期(沒有提示錯誤訊息)
//傳入參數 : 起始日西元年月日 終止日西元年月日
//傳回參數 : Boolean : 若結果為True ,表示輸入值正確                    '
//                     若結果為False,表示輸入值不正確                  '
//**********************************************************************
function CheckBetweenDateNone(strsd,stred)
{
	if(strsd =="//" || stred == "//"){
		return false;
	}
	var sd = new Date(strsd);
	var ed = new Date(stred);

	if((sd.getTime() - ed.getTime()) > 0){
		//alert("起始日不得小於終止日");
		return false;
	}
        return true  
}


//**********************************************************************
//功能說明 : 檢查身分證		  		                       '
//傳入參數 : 將要檢查的欄位用逗號組合起來傳入			       '
//傳回參數 : Boolean : 若結果為True ,表示輸入值正確                    '
//                     若結果為False,表示輸入值不正確                  '
//**********************************************************************
function CheckNationID(FormName,ItemName,ErrMsg)
{
   var thisID=eval("document."+FormName+"."+ItemName);
   if (thisID.value=="" || thisID.value.length!=10 || isNaN(thisID.value.substring(1,10))) 
   {
      thisID.focus();
      return ErrMsg;
   }
   else 
   {
      var id=thisID.value;
      idarray=new Array();
      for (i=0;i<=9;i++) 
      {
         if (i==0) idarray[i]=id.charAt(i);
         else idarray[i]=parseInt(id.charAt(i));
      }
      var id1=idarray[0].toUpperCase();
      if      (id1=="A") d1="10";
      else if (id1=="B") d1="11";
      else if (id1=="C") d1="12";
      else if (id1=="D") d1="13";
      else if (id1=="E") d1="14";
      else if (id1=="F") d1="15";
      else if (id1=="G") d1="16";
      else if (id1=="H") d1="17";
      else if (id1=="I") d1="34"; 
      else if (id1=="J") d1="18";
      else if (id1=="K") d1="19";
      else if (id1=="L") d1="20";
      else if (id1=="M") d1="21";
      else if (id1=="N") d1="22";
      else if (id1=="O") d1="35"; // New Add
      else if (id1=="P") d1="23";
      else if (id1=="Q") d1="24";
      else if (id1=="R") d1="25";
      else if (id1=="S") d1="26";
      else if (id1=="T") d1="27";
      else if (id1=="U") d1="28";
      else if (id1=="V") d1="29";
      else if (id1=="W") d1="32";
      else if (id1=="X") d1="30";
      else if (id1=="Y") d1="31";
      else if (id1=="Z") d1="33";
	  else
	  {
		 thisID.focus();
         return ErrMsg;
	  }
	  var x1=d1.charAt(0);
      var x2=d1.charAt(1);
      x1=parseInt(x1)
      x2=parseInt(x2)
      sum=x1+x2*9+idarray[1]*8+idarray[2]*7+idarray[3]*6+idarray[4]*5+idarray[5]*4+idarray[6]*3+idarray[7]*2+idarray[8]+idarray[9]
      if (sum%10!=0) 
      {
         thisID.focus();
         return ErrMsg;
      }
   }
   return '';
}




//**********************************************************************
//功能說明 : 檢查mail欄位是否空白				       '
//傳入參數 : 將要檢查的欄位值傳入				       '
//傳回參數 : Boolean : 若結果為True ,表示輸入值正確                    '
//                     若結果為False,表示輸入值不正確                  '
//**********************************************************************

function CheckEmail(email){
	var testresults
	var str=email;
	var filter=/^.+@.+\..{2,3}$/
	if (filter.test(str)){
		testresults=true;
	}else{
		alert("不正確的mail格式");
		testresults=false;
	}
	return (testresults);
}


function CheckBrowser(){
	var agt=navigator.userAgent.toLowerCase(); 
	var bVer = parseInt(navigator.appVersion); 
	var NN = (navigator.appName == "Netscape") ? true : false; 
	var IE = (navigator.appName == "Microsoft Internet Explorer") ? true : false; 
	var brws; 
	bVer = (IE && (bVer == 4) && (agt.indexOf("msie 5.0")!=-1)) ? 5 : bVer; 
	
	if(IE){ 
		brws="Microsoft Internet Explorer"; 
		return true;
	}else if(NN){ 
		brws="Netscape Navigator"; 
		alert("你所使用的非IE版本的瀏覽器類型, 會造成問題...!!");
		return false;
	}else{ 
		brws="Nothing"; 
		alert("你所使用的非IE版本的瀏覽器類型, 會造成問題...!!");
		return false;
	}
}



//**********************************************************************
//功能說明 : 日期加減函數(同VB的 DateAdd函數)					       '
//傳入參數 :start --> 日期					       '
//	    interval-->D(Days),H(Hours),M(Minutes),S(Seconds)	       '
//	    number-->加減數	
//傳回參數 : Date 						       '
//**********************************************************************
function DateAdd( start, interval, number ) {
	
    // Create 3 error messages, 1 for each argument. 
    var startMsg = "Sorry the start parameter of the dateAdd function\n"
        startMsg += "must be a valid date format.\n\n"
        startMsg += "Please try again." ;
		
    var intervalMsg = "Sorry the dateAdd function only accepts\n"
        intervalMsg += "d, h, m OR s intervals.\n\n"
        intervalMsg += "Please try again." ;

    var numberMsg = "Sorry the number parameter of the dateAdd function\n"
        numberMsg += "must be numeric.\n\n"
        numberMsg += "Please try again." ;
		
    // get the milliseconds for this Date object. 
    var buffer = Date.parse( start ) ;
	
    // check that the start parameter is a valid Date. 
    if ( isNaN (buffer) ) {
        alert( startMsg ) ;
        return null ;
    }
	
    // check that an interval parameter was not numeric. 
    if ( interval.charAt == 'undefined' ) {
        // the user specified an incorrect interval, handle the error. 
        alert( intervalMsg ) ;
        return null ;
    }

    // check that the number parameter is numeric. 
    if ( isNaN ( number ) )	{
        alert( numberMsg ) ;
        return null ;
    }

    // so far, so good...
    //
    // what kind of add to do? 
    switch (interval.charAt(0))
    {
        case 'd': case 'D': 
            number *= 24 ; // days to hours
            // fall through! 
        case 'h': case 'H':
            number *= 60 ; // hours to minutes
            // fall through! 
        case 'm': case 'M':
            number *= 60 ; // minutes to seconds
            // fall through! 
        case 's': case 'S':
            number *= 1000 ; // seconds to milliseconds
            break ;
        default:
        // If we get to here then the interval parameter
        // didn't meet the d,h,m,s criteria.  Handle
        // the error. 		
        alert(intervalMsg) ;
        return null ;
    }
    return new Date( buffer + number ) ;
}


//**********************************************************************
//功能說明 : 日期相差函數(同VB的 DateDiff函數)			       '
//傳入參數 :start --> 開始日期					       '
//	    end-->結束日期
//	    interval-->D(Days),H(Hours),M(Minutes),S(Seconds)	       '
//	    rounding-->
//傳回參數 : 相差數						       '
//**********************************************************************
function DateDiff( start, end, interval, rounding ) {

    var iOut = 0;
    
    // Create 2 error messages, 1 for each argument. 
    var startMsg = "Check the Start Date and End Date\n"
        startMsg += "must be a valid date format.\n\n"
        startMsg += "Please try again." ;
		
    var intervalMsg = "Sorry the dateAdd function only accepts\n"
        intervalMsg += "d, h, m OR s intervals.\n\n"
        intervalMsg += "Please try again." ;

    var bufferA = Date.parse( start ) ;
    var bufferB = Date.parse( end ) ;
    	
    // check that the start parameter is a valid Date. 
    if ( isNaN (bufferA) || isNaN (bufferB) ) {
        alert( startMsg ) ;
        return null ;
    }
	
    // check that an interval parameter was not numeric. 
    if ( interval.charAt == 'undefined' ) {
        // the user specified an incorrect interval, handle the error. 
        alert( intervalMsg ) ;
        return null ;
    }
    
    var number = bufferB-bufferA ;
    
    // what kind of add to do? 
    switch (interval.charAt(0))
    {
        case 'd': case 'D': 
            iOut = parseInt(number / 86400000) ;
            if(rounding) iOut += parseInt((number % 86400000)/43200001) ;
            break ;
        case 'h': case 'H':
            iOut = parseInt(number / 3600000 ) ;
            if(rounding) iOut += parseInt((number % 3600000)/1800001) ;
            break ;
        case 'm': case 'M':
            iOut = parseInt(number / 60000 ) ;
            if(rounding) iOut += parseInt((number % 60000)/30001) ;
            break ;
        case 's': case 'S':
            iOut = parseInt(number / 1000 ) ;
            if(rounding) iOut += parseInt((number % 1000)/501) ;
            break ;
        default:
        // If we get to here then the interval parameter
        // didn't meet the d,h,m,s criteria.  Handle
        // the error. 		
        alert(intervalMsg) ;
        return null ;
    }
    
    return iOut ;
}
