﻿// JScript File

//document.write('<script src="/WebPages/Pross/GetJsGlobalVariable.aspx" language="javascript"></script>');

/*****************************************************************
DESCRIPTION: Validates that a string contains only valid date.
RETURNS:   Returns alert if date string does not matches format of format string and is a valid date. 
******************************************************************/
function initDateCtrl()
{
    getDateElement();
}

function getDateElement()
{
    var elem = document.getElementsByTagName("input");
        for(var i=0;i<elem.length;i++)
        {  
        var formElem = elem[i]; 
            if(formElem.getAttribute('IsDateField')!=null)
            {        
                if(formElem.type == "text")
                {                         
                     formElem.onkeyup = function() {
				       showDateSeparator(this);
			        }
			        formElem.onblur = function() {			  			    		    		   
			            isValidDate(this);				
			        }
			        formElem.onfocus = function() {
				        this.select();
			        }
            }
        }
    }
}

function setDay(dayForm,dayNum) {
	var restoreIndex = 0;
	if (dayForm.selectedIndex < dayNum) {
		restoreIndex = dayForm.selectedIndex;
	} else {
		restoreIndex = dayNum;
	}
	dayForm.length = dayNum+1;
	dayForm.options[0].index = 1;
	dayForm.options[0].value = '';
	dayForm.options[0].text = ' - ';		

	for (i=1;i<=dayNum;i++) {
		dayForm.options[i].index = i;
		dayForm.options[i].value = i;
		dayForm.options[i].text = (i).toString();
	}
	dayForm.selectedIndex = restoreIndex;
	return;
}

function isValidDate(formElem) {
	var strDate = formElem.value;
	if(strDate == ""){
        return;
    }
    var rYear = "(\\d{4})";
    var rMonth = "(0{0,1}[1-9]|1[0-2])";
    var rDay = "(0{0,1}[1-9]|[1-2]\\d|3[0-1])";
    var rStr = _cp_DateTimeFormat.replace("yyyy",rYear);
    rStr = rStr.replace("MM",rMonth);
    rStr = rStr.replace("dd",rDay);
    rStr = rectifyFromatString(rStr);
    var re = new RegExp("^"+rStr+"$","g","i")
    if(!re.test(strDate)){      
       alert(invaliddatemessage +_cp_DateTimeFormat);	
       formElem.focus(); 
    }
}

function showDateSeparator(formElem) {
	var intKeyCode = window.event.keyCode;
	var strValue = "";
	
	if(intKeyCode!=37 && intKeyCode!=39 &&
		intKeyCode!=8 && intKeyCode!=46 &&
		intKeyCode!=13 && intKeyCode!=9) {
		
		strValue = formElem.value;
		strValue = strValue.replace(/[^0-9]+/g,'');
		if(strValue.length>8){
		    strValue = strValue.substring(0,8);
		}
				    
		var intDay = null;
		var intMonth = null;
		var intYear = null;
		var tmpformat = null;
		var separator = null;
		
		tmpformat = _cp_DateTimeFormat.substring(0,2);
    	
    	if (tmpformat =="dd"){			
            if(strValue.length>0){		      
                intDay = strValue.substring(0,2);		            
		    }
		    if(strValue.length>2){		       
		        intMonth = strValue.substring(2,4);		            
		    }
		    if(strValue.length>4){		        
		        intYear = strValue.substring(4,strValue.length);			            	    
		    }
		    separator = _cp_DateTimeFormat.substring(2,3);
		        
		    strValue = "";		                                   
		    if(intDay!=null){			           		            	            
		        if(intDay.length==2){			                                
		            strValue +=intDay + separator;  
		        }else{
		            strValue +=intDay;
		        }
		    }		        
		    if(intMonth!=null){
		        if(intMonth.length==2){
		            strValue +=intMonth + separator;		                 
		        }else{
		            strValue +=intMonth;		                 
		        }		            
		    }
		    if(intYear!=null){		        
		        strValue +=intYear;
		    }
		}else if(tmpformat =="MM"){	  
		    if(strValue.length>0){		      
		        intDay = strValue.substring(2,4);		            
		    }
		    if(strValue.length>2){		       
		        intMonth = strValue.substring(0,2);		            
		    }
		    if(strValue.length>4){		        
		        intYear = strValue.substring(4,strValue.length);			            	    
		    }
		    separator = _cp_DateTimeFormat.substring(2,3);	
		        
		    strValue = "";
		    if(intMonth!=null){
		        if(intMonth.length==2){   
		            strValue +=intMonth + separator;		                 
		        }else{
		            strValue +=intMonth;
		        }		           	
		    }
		    if(intDay!=null){
		        if(intDay.length==2){
		            strValue +=intDay + separator
		        }else{
		            strValue +=intDay;		                 
		        }	
		    }		        
		    if(intYear!=null){		        
		        strValue +=intYear;
		    }		       
		}else{		       
		    separator =  _cp_DateTimeFormat.substring(4,5);		        
		        
		    if(strValue.length>0){		        
		        intYear =strValue.substring(0,4);		         
		    }
		        
		        if (_cp_DateTimeFormat.substring(5,7)=="dd")
		        {
		            if(strValue.length>4)
		            {
		                intDay =  strValue.substring(4,6);
		            }
		            if(strValue.length>6)
		            {
		                intMonth =  strValue.substring(6,strValue.length);
		            }
		            
		            strValue = "";
		            if(intYear!=null) 
	                {
	                    if(intYear.length==4) 
	                    { 	
	                         strValue += intYear + separator;
	                    }
	                    else
	                    {
	                        strValue += intYear;
	                    }	               	                
	                }              		           		            
		            
		            if(intDay!=null) 
		            {		            
		                if(intDay.length==2) 
		                {		                
		        		    strValue +=intDay + separator;  
		                }
		                else
		                {
		                    strValue +=intDay;
		                }
		            }
		            		        
		            if(intMonth!=null) 
		            {
		                     strValue +=intMonth;  
		            }   
		        }
		        else (_cp_DateTimeFormat.substring(5,7)=="MM")
		        {   
		            if(strValue.length>6)
		            {
		                intDay =  strValue.substring(6,strValue.length);
		            }
		             if(strValue.length>4)
		            {
		                intMonth =  strValue.substring(4,6);
		            }
		            
		            strValue = "";
		            if(intYear!=null) 
	                {
	                    if(intYear.length==4) 
	                    { 	
	                         strValue += intYear + separator;
	                    }
	                    else
	                    {
	                        strValue += intYear;
	                    }	               	                
	                } 		            
		            if(intMonth!=null) 
		            {
		                if(intMonth.length==2) 
		                {
		                     strValue +=intMonth + separator;		                 
		                }
		                else
		                {
		                     strValue +=intMonth;		                 
		                }	
		            }
		            if(intDay!=null) 
		            {
		                     strValue +=intDay;	
		            }
		        }	     
		    }
		 }						
		formElem.value = strValue;		
	   } 
	   

/*****************************************************************
DESCRIPTION: Calculate the ASCII code of the given character
PARAMETERS:  aChar - String to be tested for calculation
RETURNS:   ASCII code
******************************************************************/	  
function CalcKeyCode(aChar) {
  var character = aChar.substring(0,1);
  var code = aChar.charCodeAt(0);
  return code;
}

function IsFocusSelect(isSelect, obj)
{  
   if (isSelect)
   {
    obj.select();
   }
}

/*****************************************************************
DESCRIPTION: Validates that a string is numeric, otherwise it deletes the non-numeric character. 
PARAMETERS:   Num - String to be tested for validity
              canNegative - String can be negative value
RETURNS:   False if string is non-numeric.
******************************************************************/
function isNumeric(Num, canNegative) {
   if(!(window.event.keyCode > 47 && window.event.keyCode < 58))  
  {
    if(window.event.keyCode==9)
       window.event.returnValue = true;
    else
       window.event.returnValue = false;
  }
}

/*****************************************************************
DESCRIPTION: Validates that a string is numeric, otherwise it deletes the non-numeric character. 
PARAMETERS:  num - String to be tested for validity
             places - Decimal places to be tested for validity.
             canNegative - String can be negative value
	         e- Window event
RETURNS:   False if string is non-numeric.
******************************************************************/
function isDecimal(num, places, canNegative, e) {
  //debugger;
  if(num.disabled == true)
  {
      return false;
  }
  var whichCode1 = event.keyCode || event.which;
  var key1 = String.fromCharCode(whichCode1);  // Get key value from key code
  var selectedValue = document.selection.createRange().text;
  if (selectedValue != "")
  {
     if (key1.replace(/[\d+]/ig,"").length > 0)
     {
         with(document.selection.createRange())
        {
            num.value = selectedValue;
            moveStart("character",num.value.length); //把光标定位到起始位置      
            select();              
        }
        return false;
     }     
  
    num.value = num.value.replace(selectedValue,key1);
    document.selection.empty();
    with(document.selection.createRange())
    {
       moveStart("character",1); //把光标定位到起始位置
       collapse();
       select();
     }
     return false;  
  }
  var negative = 0;
  var sep = 0;
  var decSep = '.';
  var key = '';
  var i = j = 0;
  var len = 0;
  var strCheck = '0123456789.';
  var strNegCheck = '-0123456789.';
  var aux = aux2 = '';
  //var whichCode = (window.Event) ? e.which : e.keyCode;
  var whichCode = event.keyCode || event.which;
  if (whichCode == 13) return true;  // Enter
  if (whichCode == 8) return true;  // Delete
  
 key = String.fromCharCode(whichCode);  // Get key value from key code
  if (!canNegative) {
    if (strCheck.indexOf(key) == -1)
     return false;  // Not a valid key
  }
  else  {
    if (strNegCheck.indexOf(key) == -1)
     return false;  // Not a valid key
  }     
  //过滤TextBox的长度,缺省10位
  var length = parseInt(num.getAttribute("maxlength"));
  if(length > 100)
  {
    length = 10;
  }
  if(num.value.length == length)
  {
     return false;
  }
  if (num.value.charAt(0)=="-") {
    negative = 1;
    num.value = num.value.substring(1, num.value.length);
  }
  len = num.value.length;
  for(i = 0; i < len; i++)
  if ((num.value.charAt(i) != '0') && (num.value.charAt(i) != decSep)) break;
  aux = '';
  
    
  for(i=0; i < len; i++) {
            if (strCheck.indexOf(num.value.charAt(i))!=-1) {
            aux += num.value.charAt(i);
            }
   }
   

  if (whichCode != 45)  {
  aux += key;  
  }  
  
  var arrAux = aux.split(decSep)
  
  if(arrAux.length==1){
    num.value = aux 
  }else{
    if(arrAux[1].length>places){
        num.value = arrAux[0] + decSep + arrAux[1].substr(0,places) 
    }else{
        num.value = arrAux[0] + decSep + arrAux[1];
    }
  }
  /*
  len = aux.length;  
  if ((len == 0) && (whichCode != 45)) num.value = '';
  if ((len >0) && (len<=places))
  {
     num.value = aux 
  }
  if (len >places) {
    aux2 = '';
    for (j = 0, i = len - (places+1); i >= 0; i--) {
      aux2 += aux.charAt(i);
      j++;
    }
    num.value = ''; 
    for (i = len - (places+1); i >= 0; i--)
    num.value += aux2.charAt(i);
    num.value += decSep + aux.substr(len - places, len);        
  }
  */
   
  //Add '-' for negative
  if (negative == 0) {
    if ((canNegative) && (whichCode == 45) && (len!=0)) {   
        num.value = "-" + num.value;
    }
  }    
  else {
    num.value = "-" + num.value;
  }
  
  return false;
}

/************************************************
DESCRIPTION: Validates that a string a matches a valid regular expression value.
PARAMETERS:  strValue - String to be tested for validity
             strMatchPattern - String containing a valid regular expression match pattern.
RETURNS:     True if valid, otherwise false.
*************************************************/
function validateValue( strValue, strMatchPattern ) {

var objRegExp = new RegExp( strMatchPattern);

//check if string matches pattern
return objRegExp.test(strValue);
}


/************************************************
DESCRIPTION: Validates that a string is not all blank (whitespace) characters.
PARAMETERS:  strValue - String to be tested for validity
RETURNS:     True if valid, otherwise false.
*************************************************/
function isNotEmpty( strValue ) {

   var strTemp = strValue;
   strTemp = trimAll(strTemp);
   if(strTemp.length > 0){
     return true;
   }
   return false;
}


/************************************************
DESCRIPTION: Removes leading and trailing spaces.
PARAMETERS: Source string from which spaces will be removed;
RETURNS: Source string with whitespaces removed.
*************************************************/
function trimAll( strValue ) {

var objRegExp = /^(\s*)$/;

    //check for all spaces
    if(objRegExp.test(strValue)) {
       strValue = strValue.replace(objRegExp, '');
       if( strValue.length == 0)
          return strValue;
    }

   //check for leading & trailing spaces
   objRegExp = /^(\s*)([\W\w]*)(\b\s*$)/;
   if(objRegExp.test(strValue)) {
       //remove leading and trailing whitespace characters
       strValue = strValue.replace(objRegExp, '$2');
    }
  return strValue;
}


/************************************************
DESCRIPTION: Validates that a string is valid email.
PARAMETERS: Email -String to be tested for validity.
RETURNS: True if valid, otherwise false.
*************************************************/
function IsEmail(email) {
//  at = email.indexOf('@');
//  dot = email.indexOf('.');

//  if(at == -1 || 
//    dot == -1 || 
//    dot <= at + 1 ||
//    dot == 0 || 
//    dot == email.length - 1)
//    return(false);
//     
//  user_name = email.substr(0, at);
//  domain_name = email.substr(at + 1, email.length);                  

//  if(validateString(user_name) === false || 
//    validateString(domain_name) === false)
//    return(false);                     

//  return(true);
  objRegExp = /^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
  return objRegExp.test(email);
}
function IsMobile(mobile)
{
   objRegExp = /^\+\d/;
    return objRegExp.test(mobile);
}
/************************************************
DESCRIPTION: Validates that a string is valid.
PARAMETERS: string -String to be tested for validity,
            return_invalid_chars - String value for return.
RETURNS: True if valid, otherwise false.
*************************************************/
function validateString(string, return_invalid_chars) {
  valid_chars = '1234567890-_.^~abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
  invalid_chars = '';
  if(string == null || string == '')
     return(true);

  //For every character on the string.   
  for(index = 0; index < string.length; index++) {
    char = string.substr(index, 1);                        
     
    //Is it a valid character?
    if(valid_chars.indexOf(char) == -1) {
      //If not, is it already on the list of invalid characters?
      if(invalid_chars.indexOf(char) == -1) {
        //If it's not, add it.
        if(invalid_chars == '')
          invalid_chars += char;
        else
          invalid_chars += ', ' + char;
      }
    }
  }
            
  //If the string does not contain invalid characters, the function will return true.
  //If it does, it will either return false or a list of the invalid characters used
  //in the string, depending on the value of the second parameter.
  if(return_invalid_chars == true && invalid_chars != '') {
    last_comma = invalid_chars.lastIndexOf(',');
    if(last_comma != -1)
      invalid_chars = invalid_chars.substr(0, $last_comma) + 
      ' and ' + invalid_chars.substr(last_comma + 1, invalid_chars.length);
    return(invalid_chars);
    }
  else
    return(invalid_chars == ''); 
}

/************************************************
DESCRIPTION: Remove all html elements of the string
PARAMETERS: Word -String to be tested for validity,            
RETURNS: String not contains any html elements
*************************************************/
function removeHTML(Word) {
a = Word.indexOf("<");
b = Word.indexOf(">");
len = Word.length;
c = Word.substring(0, a);
if(b == -1)
b = a;
d = Word.substring((b + 1), len);
Word = c + d;
tagCheck = Word.indexOf("<");
if(tagCheck != -1)
Word = removeHTML(Word);
return Word;
}



/************************************************
DESCRIPTION: Format currency
PARAMETERS: num -Numeric to be format,
            places - Decimal place to be format.   
RETURNS: Formatted currency value
*************************************************/
function formatCurrency(num,places){
		if(!isNaN(num)){
			num = roundUp(num,places);
			if (String(num).indexOf(".") < 0 ){
				num = num + ".";
				for(i=0;i<places;i++){
					num = num + "0";
				}
			}else if(String(num).length-String(num).indexOf(".")-1<places){
				for(i=String(num).length-String(num).indexOf(".")-1;i<places;i++){
					num = num + "0";
				}
			}
			var str1 = String(num).substring(0,String(num).indexOf("."));
			var str2 = String(num).substring(String(num).indexOf("."),String(num).length);
			var str3 = "";
			var str4="";
			if(str1.charAt(0)=='-'){
				str4="-";
				str1 = String(str1).substring(1,String(str1).length);
			}
			var i = 0;

			for(j=str1.length-1;j>=0;j--){
				if (i%3==0&&i>0&&i<str1.length){
					str3 = "," + str3;
				}
				str3 = str1.charAt(j) + str3;
				i++;
			}
			if(str2=='.'){
				str2 = "";
			}
			return str4 + str3 + str2;
		}else{
			return "0.00";
		}
	}
	
	
/************************************************
DESCRIPTION: Roundup numeric with decimal places
PARAMETERS: num -Numeric to be format,
            places - Decimal place to be format.   
RETURNS: Numeric value
*************************************************/
function roundUp(num,places){
	if(!isNaN(num)){
		if(String(num).indexOf("e") > 0 ){
			num = 0;
		}else if (String(num).indexOf(".") > 0 ){
			if(String(num).substring(String(num).indexOf(".")+1+places,String(num).indexOf(".")+2+places)>=5){
				if(num>=0){
					num = parseFloat(num) + 0.01;
				}else{
					num = parseFloat(num) - 0.01;
				}
			}
			num = String(num).substring(0,String(num).indexOf(".")+1+places);
		}
		return num;
	}else{
		return 0;
	}
}

/************************************************
DESCRIPTION: Validates that a string is valid.
PARAMETERS: stringValue -String to be tested for validity.            
RETURNS: True if valid, otherwise false.
*************************************************/
function isURL(stringValue){
//var urlReg = "//([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?";
   return /^http(s)?:\/\/([\w-]+\.)+[\w-]+(\/[\w- ./?%&=]*)?$/.test(stringValue);
//return validateValue(stringValue,urlReg)	
}










window.attachEvent("onload",initDateCtrl);
