// Khai bao cac bien dung chung
//var SoCMNDHetHan = 15;
//var TuoiDuDieuKienKD = 18;
function validateEmail(email)
{
// a very simple email validation checking. 
// you can add more complex email checking if it helps 
    var splitted = email.match("^(.+)@(.+)$");
    if(splitted == null) return false;
    if(splitted[1] != null )
    {
      var regexp_user=/^\"?[\w-_\.]*\"?$/;
      if(splitted[1].match(regexp_user) == null) return false;
    }
    if(splitted[2] != null)
    {
      var regexp_domain=/^[\w-\.]*\.[A-Za-z]{2,4}$/;
      if(splitted[2].match(regexp_domain) == null) 
      {
	    var regexp_ip =/^\[\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\]$/;
	    if(splitted[2].match(regexp_ip) == null) return false;
      }// if
      return true;
    }
return false;
}
/*-----------------------------------------Date Check------------------------------------------------
// function check date.
// returns true : valid
// returns false : Invalid
*/
function checkDate(s) {
	
	if (s == ""){
		return true;
	}
	else{
		var i1 = s.indexOf("/");
		if (i1<0) return false;
		var i2 = s.indexOf("/",i1+1);
		if (i2<0) return false;
		var dd = s.substr(0, i1);
		var mm = s.substr(i1+1, i2-(i1+1));
		var yy = s.substr(i2+1);
	
		if (!checkInt(dd)) return false;
		if (!checkInt(mm)) return false;
		if (!checkInt(yy)) return false;
	
		d = dd.valueOf();
		m = mm.valueOf();
		y = yy.valueOf();
	
		if ((m<1) || (m>12)) return false;
		if (y<1) return false;
		var leapyear=( (y % 4)==0 );
		var maxday=0;
	
		maxday=31;
		if ((m==4) || (m==6) || (m==9) || (m==11))
			maxday=30;
		if (m==2)
			maxday=(leapyear)?29:28;
	
		if ((dd.valueOf()<1) || (dd.valueOf()>maxday)) return false;
		return true;
	}
	
}

/*------------------------- Over18 Check ------------------------------------------------------------
// function over18 check
//
//
*/
function over18(s) 
{	
     if (!checkDate(s)) {
          return false;
     }
	 else
	 {	
			arrdate = s.split("/");
			s = arrdate[1] + "/" + arrdate[0] + "/" + arrdate[2];
			dtest = new Date(s);
			date = new Date();
			
			year = date.getFullYear();
			month = date.getMonth() + 1;
			day = date.getDate();
			
			year_test = dtest.getFullYear();
			month_test = dtest.getMonth() + 1;
			day_test = dtest.getDate();
			
			if (year - year_test < 18)
			{
				return false;
			}
			else
			{
				if (year - year_test == 18){
					if (month < month_test){
						return false;
					}
					else{
						if (month == month_test){
							if (day < day_test){
								return false;
							}
							else{
								return true;
							}
						}
						else{
							return true;
						}
					}
				}
				else{
					return true;
				}
				
			}
		}
}

/*------------------------- DateRegisted Check ------------------------------------------------------------
//Kiem tra ngay nhap vao co be hon ngay hien tai hay khong
//
//
*/
function DateRegisted(s)
{	
	var check = true;
	var i1 = s.indexOf("/");
	var i2 = s.indexOf("/",i1+1);
	var dd = s.substr(0, i1);
	var mm = s.substr(i1+1, i2-(i1+1));
	var yy = s.substr(i2+1);

	d1 = dd.valueOf();
	m1 = mm.valueOf();
	y1 = yy.valueOf();
	
	dtest = new Date();
	
	d2 = dtest.getDate();
	m2 = dtest.getMonth() + 1;
	y2 = dtest.getFullYear();
	
	if (y1 > y2)
	{	
		check = false;
	}
	
	if (y1 == y2)
	{
		if (m1 > m2)
		{	
			check = false;
		}
		
		if (m1 == m2)
		{
			if (d1 > d2)
			{	
				check = false;
			}
		}
	}
	
	return check;
}
/*------------------------- CompareDateRegisted Check ------------------------------------------------------------
//Kiem tra ngay nhap vao voi tham so da cho
//
//
*/
function CompareDateRegisted(s)
{	
	var check = true;
	var i1 = s.indexOf("/");
	var i2 = s.indexOf("/",i1+1);
	
	var dd = s.substr(0, i1);
	var mm = s.substr(i1+1, i2-(i1+1));
	var yy = s.substr(i2+1);
	
	var i1_compare = strNgaysinh.indexOf("/");
	var i2_compare = strNgaysinh.indexOf("/",i1_compare+1);
	
	var dd_compare = strNgaysinh.substr(0, i1_compare);
	var mm_compare = strNgaysinh.substr(i1_compare+1, i2_compare-(i1_compare+1));
	var yy_compare = strNgaysinh.substr(i2_compare+1);

	d1 = dd.valueOf();
	m1 = mm.valueOf();
	y1 = yy.valueOf();
		
	d2 = dd_compare.valueOf();
	m2 = mm_compare.valueOf();
	y2 = yy_compare.valueOf();
	
	if (y1 - y2 < 16)
	{	
		check = false;
	}
	
	if (y1 - y2 == 16)
	{	
		if (eval(m1) < eval(m2))
		{	
			check = false;
		}
		
		if (eval(m1) == eval(m2))
		{
			if (eval(d1) < eval(d2))
			{	
				check = false;
			}
		}
	}
	
	return check;
}
/*------------------------- Phone Check ------------------------------------------------------------
// function phone check
//
//
*/
function isPhoneNumber(s) 
{
 
     // Check for correct phone number
	 rePhoneNumber = new RegExp(/(^[0-9]\d{1,2}\.\d{3,4}\.\d{6,9}(\-\d{6,9})*$)|(^[0-9]\d{3,4}\.\d{6,9}(\-\d{6,9})*$)|^[0-9]\d{5,9}$/);
 
     if (!rePhoneNumber.test(s)) {
          //alert("Phone Number Must Be Entered As: (84.0511) 847353 - 847353");
          return false;
     }
 
	return true;
}
/*----------------------------------------- Check Int--------------------------------------------------------
//
//
*/
function checkInt(checkStr) {
	if (checkStr.length < 1) return false;
	var checkOK = "0123456789";
	for (i=0; i<checkStr.length; i++) {
		ch = checkStr.charAt(i);
		if (checkOK.indexOf(ch) < 0)
			return false;
	}
	if (checkStr.valueOf()<1) return false;
	return true;
}

/*----------------------------------------------------------------------------------------------------- 
*function validateData 
*  Checks each field in a form 
*  Called from validateForm function 
*/ 
function validateData(strValidateStr,objValue,strError) 
{
    var epos = strValidateStr.search("="); 
    var  command  = ""; 
    var  cmdvalue = ""; 
	objValue.value = objValue.value.trim();
    if(epos >= 0) 
    { 
     command  = strValidateStr.substring(0,epos); 
     cmdvalue = strValidateStr.substr(epos+1); 
    } 
    else 
    { 
     command = strValidateStr; 
    } 

    switch(command) 
    { 
        case "req": 
        case "required": 
         { 
           if(eval(objValue.value.trim().length) == 0) 
           { 
              if(!strError || strError.length ==0) 
              { 
                strError = objValue.name + " : Required Field"; 
              }//if 
              alert(strError); 
              return false; 
           }//if 
           break;             
         }//case required 
        case "maxlength": 
        case "maxlen": 
          { 
             if(eval(objValue.value.trim().length) >  eval(cmdvalue)) 
             { 
               if(!strError || strError.length ==0) 
               { 
                 strError = objValue.name + " : "+cmdvalue+" characters maximum "; 
               }//if 
               alert(strError); 
               return false; 
             }//if 
             break; 
          }//case maxlen 
        case "minlength": 
        case "minlen": 
           { 
             if(eval(objValue.value.trim().length) <  eval(cmdvalue)) 
             { 
               if(!strError || strError.length ==0) 
               { 
                 strError = objValue.name + " : " + cmdvalue + " characters minimum  "; 
               }//if               
               alert(strError); 
               return false;                 
             }//if 
             break; 
            }//case minlen 
        case "alnum": 
        case "alphanumeric": 
           { 
              var charpos = objValue.value.trim().search("[^A-Za-z0-9]"); 
              if(objValue.value.trim().length > 0 &&  charpos >= 0) 
              { 
               if(!strError || strError.length ==0) 
                { 
                  strError = objValue.name+": Only alpha-numeric characters allowed "; 
                }//if 
                alert(strError); 
                return false; 
              }//if 
              break; 
           }//case alphanumeric 
        case "num": 
        case "numeric": 
           { 
              var charpos = objValue.value.trim().search("[^0-9]"); 
              if(objValue.value.trim().length > 0 &&  charpos >= 0) 
              { 
                if(!strError || strError.length ==0) 
                { 
                  strError = objValue.name+": Only digits allowed "; 
                }//if               
                alert(strError); 
                return false; 
              }//if 
              break;               
           }//numeric 
        case "alphabetic": 
        case "alpha": 
           { 
              var charpos = objValue.value.trim().search("[^A-Za-z]"); 
              if(objValue.value.trim().length > 0 &&  charpos >= 0) 
              { 
                  if(!strError || strError.length ==0) 
                { 
                  strError = objValue.name+": Only alphabetic characters allowed "; 
                }//if                             
                alert(strError); 
                return false; 
              }//if 
              break; 
           }//alpha 
		case "phone": 
          { 
               if (objValue.value.trim() !== "")
			   {
				    if(!isPhoneNumber(objValue.value.trim())) 
               		{ 
                 		alert(strError); 
                 		return false; 
					}//if	  
               	}//if 
           break; 
          }//case phone
        case "email": 
          { 
               if (objValue.value.trim() !== "")
			   {
				    objValue.value = objValue.value.replace(/\.\.*/gi, '.');
					if(!validateEmail(objValue.value.trim())) 
               		{ 
                 		if(!strError || strError.length ==0) 
                 		{ 
                    		strError = objValue.name+": Enter a valid Email address "; 
                 		}//if                                               
                 		alert(strError); 
                 		return false; 
					}//if	  
               	}//if 
           break; 
          }//case email 
        case "lt": 
        case "lessthan": 
         { 
            if(isNaN(objValue.value.trim())) 
            { 
              alert(objValue.name+": Should be a number "); 
              return false; 
            }//if 
            if(eval(objValue.value.trim()) >=  eval(cmdvalue)) 
            { 
              if(!strError || strError.length ==0) 
              { 
                strError = objValue.name + " : value should be less than "+ cmdvalue; 
              }//if               
              alert(strError); 
              return false;                 
             }//if             
            break; 
         }//case lessthan 
        case "gt": 
        case "greaterthan": 
         { 
            if(isNaN(objValue.value.trim())) 
            { 
              alert(objValue.name+": Should be a number "); 
              return false; 
            }//if 
             if(eval(objValue.value.trim()) <=  eval(cmdvalue)) 
             { 
               if(!strError || strError.length ==0) 
               { 
                 strError = objValue.name + " : value should be greater than "+ cmdvalue; 
               }//if               
               alert(strError); 
               return false;                 
             }//if             
            break; 
         }//case greaterthan 
		 case "date": 
         { 
            if(!checkDate(objValue.value.trim())) 
            { 
                 if(!strError || strError.length ==0) 
                 { 
                    strError = objValue.name+": Enter a valid Date "; 
                 }//if                                               
                 alert(strError); 
                 return false; 
            }//if 
            break; 
         }//case date
		 case "dateregisted": 
         { 
            if(!DateRegisted(objValue.value.trim())) 
            { 
                 alert(strError); 
                 return false; 
            }//if 
            break; 
         }//case dateregisted
		 case "comparedateregisted": 
         { 
            if(!CompareDateRegisted(objValue.value.trim())) 
            { 
                 alert(strError); 
                 return false; 
            }//if 
            break; 
         }//case comparedateregisted 
		 case "over18": 
         { 
            if(!over18(objValue.value.trim())) 
            {                                        
                 alert(strError); 
                 return false; 
            }//if 
            break; 
         }//case over18
        case "regexp": 
         { 
            if(!objValue.value.trim().match(cmdvalue)) 
            { 
              if(!strError || strError.length ==0) 
              { 
                strError = objValue.name+": Invalid characters found "; 
              }//if                                                               
              alert(strError); 
              return false;                   
            }//if 
           break; 
         }//case regexp 
        case "dontselect": 
         { 
            if(objValue.selectedIndex == null) 
            { 
              alert("BUG: dontselect command for non-select Item"); 
              return false; 
            } 
            if(objValue.selectedIndex == eval(cmdvalue)) 
            { 
             if(!strError || strError.length ==0) 
              { 
              strError = objValue.name+": Please Select one option "; 
              }//if                                                               
              alert(strError); 
              return false;                                   
             } 
             break; 
         }//case dontselect
		 case "dontselectCb": 
         { 
            if(objValue.checked == null) 
            { 
              alert("BUG: dontselect command for non-select Item"); 
              return false; 
            } 
            if(objValue.checked == eval(cmdvalue)) 
            { 
             if(!strError || strError.length ==0) 
              { 
              strError = objValue.name+": Please Select one option "; 
              }//if                                                               
              alert(strError); 
              return false;                                   
             } 
             break; 
         }//case dontselectCb
    }//switch 
    return true; 
} 
String.prototype.trim = function() { return this.replace(/^\s+|\s+$/, '').replace(/((\s*\S+)*)\s*/, '$1'); };

function validateForm(objFrm,arrObjDesc) 
{ 
	 refreshData(objFrm);
	 for(var itrobj=0; itrobj < arrObjDesc.length; itrobj++) 
	 { 
	   if(objFrm.elements.length <= itrobj) 
	   { 
			alert("BUG: Obj descriptor for a non existent form element"); 
			return false; 
	   }//if 
	   for(var itrdesc=0; itrdesc < arrObjDesc[itrobj].length ;itrdesc++) 
	   { 
		  if(validateData(arrObjDesc[itrobj][itrdesc][0], 
					 objFrm[itrobj],arrObjDesc[itrobj][itrdesc][1]) == false) 
		   { 
			 objFrm[itrobj].focus();
			 return false; 
		   }//if 
	   }//for 
	 }//for 
} 

function submitForm(objFrm, arrObjDesc) 
{ 
	return validateForm(objFrm,arrObjDesc);	
} 

function onChangeValue(control){
	obj = document.getElementById("idThaydoi");
	if (obj != null){
		obj.value += ", " + control.name;
		control.className = "onchangeInput";
	}
}

function refreshData(objFrm){
	for(var itrobj=0; itrobj < objFrm.elements.length; itrobj++) 
	 { 
		if (objFrm[itrobj].value != null){
			objFrm[itrobj].value = objFrm[itrobj].value.replace(/  */gi, ' ').trim();
		}		
	 }//for 	
}

function formatCurrency(num, control) 
{	
	re = /\./gi;
	
	num = num.replace(re, "");
	num = repl1(num.toString());
	if (num != ""){
		if (isNaN(num)) {
			num = "";
			alert("Bạn phải nhập vào kiểu số.");
			control.focus();
		}
		else{
			num = parseInt(num);
			if (num<0){
				num = "";
				alert("Bạn phải nhập vào số dương.");
			}
			else{
				num = Math.floor((num*100+0.5)/100).toString();
				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 (num);
}

function repl1(str)
{
	var strResult="";
	for(i=0;i<str.length;i++)
		if ((str.charAt(i)!="$")&&(str.charAt(i)!=","))
			strResult=strResult + str.charAt(i)
	return strResult;
}

// Kiem tra ngay hop le.
// returns 0 : hop le
// returns 1 : sai format (dd/mm/ccyy, dd-mm-ccyy, ddmmccyy, d/m/ccyy , d-m-ccyy )
// returns 2 : khong hop le (i.e. 30/02/1999)
function isValidDate(strDate)
{
  var retval = 0
  var aDDMMCCYY
  var dtest
  // Kiem tra dung format
  if (/^(\d\d?-\d\d?-\d{4})|(\d\d?\/\d\d?\/\d{4})|(\d{8})$/.test(strDate))
  {
    if (/\//.test(strDate))
    {
      aDDMMCCYY = strDate.split("/");
    }
    else
    if (/-/.test(strDate))
    {
      aDDMMCCYY = strDate.split("-");
    }
    else
    {
      aDDMMCCYY = Array(strDate.substr(0,2), strDate.substr(2,2), strDate.substr(4,4))
    }    
	dtest = new Date(aDDMMCCYY[1] + "/" + aDDMMCCYY[0] + "/" + aDDMMCCYY[2]);      
    if (dtest.getDate() != aDDMMCCYY[0] || dtest.getMonth() +1 != aDDMMCCYY[1] || dtest.getFullYear() != aDDMMCCYY[2])
    {
      retval = 2
    }
  }
  else
  {
	retval = 1
  }
  return retval
}

// so cmnd het han su dung
//return true: het han
//return false: con han
function isExpired(strDate)
{
    arrdate = strDate.split("/");
	strDate = arrdate[1] + "/" + arrdate[0] + "/" + arrdate[2];
	
    dtest = new Date(strDate);
	date = new Date(); // nam hien tai	
	
	year = date.getFullYear();
	month = date.getMonth() + 1;
	day = date.getDate();
	
	year_test = dtest.getFullYear();
	month_test = dtest.getMonth() + 1;
	day_test = dtest.getDate();	
	
	if (year -  year_test < SoCMNDHetHan) 
	{
	    return false;
	}
	else 
	{
	    if (year -  year_test == SoCMNDHetHan)
	    {
	        if (month  <  month_test)
	        {
	            return false;
	        }
	        else
	        {
	            if (month  ==  month_test)
	            {
	                if (day <= day_test)
	                {
	                    return false;
	                }
	                else return true;
                }
                else return true;
            }            
        }
        else return true;
    }	                
}

// Ngay nhap vao lon hon ngay hien tai
//return true: het han
//return false: con han
function isOverCurrentDate(strDate)
{
    arrdate = strDate.split("/");
	strDate = arrdate[1] + "/" + arrdate[0] + "/" + arrdate[2];
	
    dtest = new Date(strDate);
	date = new Date(); // nam hien tai	
	
	year = date.getFullYear();
	month = date.getMonth() + 1;
	day = date.getDate();
	
	year_test = dtest.getFullYear();
	month_test = dtest.getMonth() + 1;
	day_test = dtest.getDate();	
	
	if (year >  year_test) 
	{
	    return false;
	}
	else 
	{
	    if (year == year_test)
	    {
	        if (month  >  month_test)
	        {
	            return false;
	        }
	        else
	        {
	            if (month  ==  month_test)
	            {
	                if (day >= day_test)
	                {
	                    return false;
	                }
	                else return true;
                }
                else return true;
            }            
        }
        else return true;
    }	                
}

function formatNgay(strNgay)
{
	var s="";
	var arr;
	n=strNgay.indexOf("/")
	if (n!=-1)
	{
		arr=strNgay.split("/")
		s=arr[1] + "/" + arr[0] + "/" + arr[2]
	}
	else
	{
		n=strNgay.indexOf("-")
		if (n!=-1)
		{
			arr=strNgay.split("-")
			s=arr[1] + "-" + arr[0] + "-" + arr[2]
		}	
	}
	return (s);
}

function CheckDeleteHS()
{
	return confirm("Bạn muốn xóa hồ sơ đăng ký?\n\nĐồng ý nhấn \'OK\', không đồng ý nhấn \'Cancel\'");	
}

function QuayVe()
{    
	return window.history.back(1);
}

// Cac ham kiem tra ngay thang

 // Kiem tra ngay cap chung minh nhan dan
 // Hop le
 //	Khong qua 15 nam
 // nho hon ngay hien tai
function KtraNgayCapCM(obj)
{
    if (obj.value.length!=0)
    {
	    if (isValidDate(obj.value)!=0)
	    {		
		    alert("Ngày " + obj.value + " không đúng!");
		    obj.value="";
		    obj.focus();
		    return;
	    }
	    else
	    {		    
	        if (isExpired(obj.value))
	        {
	            alert("Chứng minh thư đã hết hạn sử dụng!");
		        obj.value="";
		        obj.focus();
		        return;
	        }
	        else
	        if (isOverCurrentDate(obj.value))	
	        {
	            alert("Ngày cấp không được lớn hơn ngày hiện tại!");
		        obj.value="";
		        obj.focus();
		        return;
	        }		
	    }
    }
}
    
//Kiem tra ngay cap
// Hop le
// Nho hon ngay hien tai
function KtraNgayCap(obj)
{
    if (obj.value.length!=0)
    {
	    if (isValidDate(obj.value)!=0)
	    {		
		    alert("Ngày " + obj.value + " không đúng!");
		    obj.value="";
		    obj.focus();
		    return;
	    }
	    else
	    if (isOverCurrentDate(obj.value))	
	    {
	        alert("Ngày cấp không được lớn hơn ngày hiện tại!");
		    obj.value="";
		    obj.focus();
		    return;
	    }	
    }
}
    
// Kiem tra ngay het han
// Dieu kien ngay het han phai lon hon ngay cap
// Ngay het han phai lon hon ngay hien tai
function KtraNgayHetHan(obj)
{
    if (obj.value.length!=0)
    {
	    if (isValidDate(obj.value)!=0)
	    {		
		    alert("Ngày " + obj.value + " không đúng!");
		    obj.value="";
		    obj.focus();
		    return;
	    }
	    else
	    if (!isOverCurrentDate(obj.value))	
	    {
	        alert("Chứng chỉ này đã hết hạn sử dụng!");
		    obj.value="";
		    obj.focus();
		    return;
	    }    
	    	
    }
}

//Kiem tra ngay sinh nguoi dai dien
//Dieu kien
//Dung
//Du 18 tuoi
function KtraNgaySinhDD(obj)
{    
	if (obj.value.length!=0)
	{	    
		if (isValidDate(obj.value)!=0)
		{			    
			alert("Ngày '" + obj.value + "' không đúng!");
			obj.value="";
			obj.focus();
			return;
		}
		dtest = new Date(formatNgay(obj.value));
		date = new Date();		
		year = date.getFullYear();
		year_test = dtest.getFullYear();
		tuoi = TuoiDuDieuKienKD;
		if ((year - year_test) < tuoi)
		{
			alert("Người dưới " + tuoi + " tuổi chưa đủ điều kiện đăng ký kinh doanh!");
			obj.value="";
			obj.focus();
		}
	}
}

//Kiem tra ngay sinh 
//Dieu kien
//Dung
function KtraNgaySinh(obj)
{    
	if (obj.value.length!=0)
	{	    
		if (isValidDate(obj.value)!=0)
		{			    
			alert("Ngày '" + obj.value + "' không đúng!");
			obj.value="";
			obj.focus();
			return;
		}
		if (isOverCurrentDate(obj.value))	
	    {
	        alert("Ngày sinh không được lớn hơn ngày hiện tại!");
		    obj.value="";
		    obj.focus();
		    return;
	    }			
	}
}

//Kiem tra ngay
//Dieu kien
//Dung
function KtraNgay(obj)
{    
	if (obj.value.length!=0)
	{	    
		if (isValidDate(obj.value)!=0)
		{			    
			alert("Ngày '" + obj.value + "' không đúng!");
			obj.value="";
			obj.focus();
			return;
		}		
	}
}