﻿/*
	openCalendar
*/
var FieldName;
function openCalendar(FN){
	FieldName = FN;
	var pathname = (window.location.pathname.toLowerCase());
	var stFeature = 'width=250,height=270';
	var toppx = (screen.height-270)/2;
	var leftpx = (screen.width-250)/2;
	stFeature += ',top='+toppx.toString()+'px,left='+leftpx.toString()+'px';
	window.open('cal.htm','Calendar',stFeature);
}//openCalendar

function round_currency(a)
{
  
  var b = Math.abs(a);
  
  b = Math.round(b * 10000000.0) / 100000.0;
  
  b = Math.round(b) / 100.0;
  
  b = b * (a >= 0.0 ? 1.0 : -1.0);
  if( b == 0.0 )
	return 0.0;
  return b;
}//round_currency

function pad_to_atleast_two_decimal_places(a)
{
  var s;
    if(a == null)
    {
       s = "";
    }
  else
  {
    s = a.toString();
    var n = s.indexOf(".");
    if(n == -1)
    {
      //s = s + ".00";
    }
    else if(n == s.length-1)
    {
      //s = s + "00";
      s = s;
    }
    else if(n == s.length-2)
    {
      s = s + "0";
    }
    if (n == 0)
    {
      s = "0" + s;
    }
  }
  return s;
}//pad_to_atleast_two_decimal_places

function format_currency(a, bDoNotRound)
{
  
  var returnMe;
  if(isNaN(a))
  {
    return "";
  }
  else if( !(bDoNotRound == true))  
  {
        returnMe = round_currency(a);
  }
  else
    returnMe = a;
  returnMe = pad_to_atleast_two_decimal_places(returnMe);
  return returnMe;
}//format_currency

function format_currency(a, bDoNotRound)
{
  
  var returnMe;
  if(isNaN(a))
  {
    return "";
  }
  else if( !(bDoNotRound == true))  
  {
        returnMe = round_currency(a);
  }
  else
    returnMe = a;
  returnMe = pad_to_atleast_two_decimal_places(returnMe);
  return returnMe;
}//format_currency


function onlydigits(str){ 
	var re = new RegExp("([0-9]+)"); 
	return (re.exec(str)!=null && RegExp.$1==str); 
}//onlydigits

function FomatNumber(txtName){
	var sumstr = document.all.item(txtName).value;
	sumstr = format_currency(parseFloat(sumstr));
	sumstr = sumstr.substring(0,10);
	document.all.item(txtName).value = sumstr;
}//FomatNumber


// Convert Number to format "###.###"
function ConvertToVNNumber(num){
	num = num.toString().replace(/\$|\./g,'');
	num = String(num).substring(0,10);	
	num = parseFloat(num);
	if(isNaN(num))num = "0";
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*100+0.50000000001);
	//cents = num%100;
	//if(cents<10)
	//cents = "0" + cents;
	
	num = Math.floor(num/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 ((sign)?'':'-') + num;
}//ConvertToVNNumber

// Convert Number to format "###,###"
function ConvertToSysNumber(num){
	num = num.toString().replace(/\$|\./g,'');
	return parseFloat(num);
}//ConvertToSysNumber

// Convert Number to format "###.###,###"
function ConvertToVNCurrency(num){
	var numInteger;
	var numDecimal;	
	num = num.toString().replace(/\$|\,/g,'');
	num = num.toString().replace(/\$|\./g,',');
	return FormatVNCurrency(num)
}//ConvertToVNCurrency

function FormatVNCurrency(num){
	var numInteger;
	var numDecimal;
	num = num.toString().replace(/\$|\./g,'');
	num = num.toString().replace(/\$|\,/g,'.');
	//num = String(num).substring(0,10);	
	num = parseFloat(num);
	if(isNaN(num))num = "0";
	sign = (num == (num = Math.abs(num)));
	
	if (num.toString().indexOf('.')>0){
		var array = num.toString().split(".");
        numInteger = array[0];
        numDecimal = array[1];	
	}else{
        numInteger = num;
        numDecimal = '';	
	}      
	numInteger = parseInt(numInteger);
	
	numInteger = Math.floor(numInteger*100+0.50000000001);
	numInteger = Math.floor(numInteger/100).toString();
	for (var i = 0; i < Math.floor((numInteger.length-(1+i))/3); i++){
		numInteger = numInteger.substring(0,numInteger.length-(4*i+3))+'.'+ numInteger.substring(numInteger.length-(4*i+3));
	}
	if (numDecimal != ''){
		return (numInteger + ',' + numDecimal);
	
	}else{
	
		return (numInteger);
	}

}//FormatVNCurrency


// Convert Number to format "###,###"
function ConvertToSysCurrency(num){
	num = num.toString().replace(/\$|\./g,'');
	num = num.toString().replace(/\$|\,/g,'.');
	return parseFloat(num);
}//ConvertToSysCurrency

function FormatNumber(txtName){
	var num = document.all.item(txtName).value;	
	document.all.item(txtName).value = ConvertToVNNumber(num);	
}//FormatNumber

function FormatCurrency(txtName){
	var num = document.all.item(txtName).value;	
	document.all.item(txtName).value = FormatVNCurrency(num);	
}//FormatCurrency


function CheckTypeOfByte(txtFieldName){
	var fValue = 1;
	var strValue = document.all.item(txtFieldName).value;
	strValue = format_currency(parseFloat(strValue));
	strValue = strValue.substring(0,10);
	if ((strValue.length > 0)&&(parseFloat(strValue) > 0))
		document.all.item(txtFieldName).value = strValue
	else{
		document.all.item(txtFieldName).value = "";
		alert("Giá trị phải là số dương lớn hơn 0");
	}
}//CheckTypeOfByte

function NotEmpty(txtName){
	var sumstr = document.all.item(txtName).value;
	if (sumstr == ''){
		alert('Chưa nhập dữ liệu');
		document.all.item(txtName).focus();
		return false;
	}else{
		document.all.item(txtName).value = sumstr;	
		return true;
	}	
}//NotEmpty

function validate_field(field,type,doalert,mandatory)
{
	type = type.toLowerCase();
    if (field.value == null || field.value.length == 0){
		if (mandatory == true){
		    if (doalert) alert("Chưa nhập dữ liệu ");
		    field.focus();
		    //field.select();
			//window.isvalid = false;
			return false;
		}
		else{
		    //window.isvalid = true;
		    return true;
		}
    }
    var validflag = true;
    if (type == "date")
    {
        validflag = true;
        var m=0,d=0,y=0, val=field.value;
        var fmterr;
        var year="";

        if (val.indexOf("/") != -1) {
                var c = val.split("/");
                if(onlydigits(c[0])) d = parseInt(c[0],10);
                if(onlydigits(c[1])) m = parseInt(c[1],10);
                if(onlydigits(c[2])) y = parseInt(c[2],10);
                year=c[2];
        }
        else{
                //var l = val.length, str;
                //str = val.substr(0,2-l%2); if(onlydigits(str)) m = parseInt(str,10);
                //str = val.substr(2-l%2,2); if(onlydigits(str)) d = parseInt(str,10);
                //str = val.substr(4-l%2);   if(onlydigits(str)) y = parseInt(str,10);
                //year=str;
        }
        fmterr = "Ngày/Tháng/Năm";
        if(m==0 || d==0)
        {
            if (doalert) alert("Ngày không hợp lệ, phải là : "+fmterr+"");
            field.value = "";
            field.focus();
		    //field.select();

            validflag = false;

        }
        else
        {
			if (y==0 && !onlydigits(year)) y = (new Date()).getYear();  
            if(m<1) m=1; else if(m>12) m=12;
            
            if(d<1) d=1; else if(d>31) d=31;
            
            switch (m){
				case 1 : 
				case 3 :
				case 5 :
				case 7 :
				case 8 :
				case 10 :
				case 12 :
				{
					if(d>31) d=31;
					break;
				}
				case 6 :
				case 9 :
				case 11 : 
				case 4 : {
					if(d>30) d=30;
					break;
				}
				case 2 : {
					if(d>28) d=28;
					break;
				}
			}
			
            if(y<100) y+=((y>=70)?1900:2000);
            if(y<1000) y*=10;
            if (y > 9999) y = (new Date()).getYear();
            if(d <= 9){ d = '0'+ d;}
            if(m <= 9){m = '0'+ m;}        
            field.value = d +'/'+ m + '/'+ y ;//getdatestring(new Date(y,m-1,d));
        }
    }
    else if (type =="number"){
			var sumstr = field.value;
			sumstr = format_currency(parseFloat(sumstr));
			field.value = sumstr;
			if (field.value == null || field.value.length == 0){
				if (mandatory == true){
					if (doalert) alert("Chưa nhập dữ liệu ");
					field.focus();
					return false;
				}
				else{
					return true;
				}
			}
			
    }    
        
    else if (type =="currency"){
        var val = field.value.replace(/\$/g,"");
        val = field.value.replace(/\ /g,"");
				val = val.replace(/,/g,"");
        val = val.toLowerCase();
        if(val.charAt(0) == '=') val = val.substr(1);
        if (val.substr(1).search(/[\+\-\*\/]/g) != -1){
            var c = val.charAt(0);
            if(val.charAt(0) >='a' && val.charAt(0) <='z')
            {
                //value = "error";
            }
            else
            {
		    //    try {
            //      val = eval(val);
			//	} catch (e) { val = "error"; }
                //autoplace = false;
            }
        }
        numval = parseFloat(val);
        if (isNaN(numval) || Math.abs(numval)>=1.0e+12){
            if (doalert) alert("Giá trị không hợp lệ, phải nhỏ hơn 999.999.999.999,99");
            validflag = false;

        }
        else {
			//if(autoplace && val.indexOf(".") == -1) numval/=100;
			field.value = format_currency(numval);
			validflag = true;
        }
    }
    else if (type == "time" || type == "timetrack"){
        var hours;
        var minutes;

        var re = /([0-9][0-9]?)?(:[0-5][0-9])?/
        var result = re.exec(field.value)
        if (result==null || result.index > 0 || result[0].length != field.value.length){
            timeval = parseFloat(field.value);
            if (isNaN(timeval))
                hours = -1;
            else{
                hours = Math.floor(timeval);
                minutes = Math.floor((timeval-hours)*60+0.5);
            }
        }
        else{
            if (RegExp.$1.length > 0)
                hours = parseInt(RegExp.$1,10);
            else
                hours = 0;
            if (typeof(RegExp.$2) != "undefined" && RegExp.$2.length > 0)
                minutes = parseInt(RegExp.$2.substr(1),10);
            else
                minutes = 0;
        }
        if (hours >= 0 && minutes >= 0 && minutes < 60){
            field.value = hours + ":" + (minutes < 10 ? "0" : "") + minutes;
            validflag = true;
        }
        else{
            if (doalert) alert("Thời gian không hợp lệ, phải là (giờ:phút)");
            validflag = false;
        }
    }
    return validflag;
}//validate_field

function openImageNews(vLink, vHeight, vWidth)
{
	var sLink = (typeof(vLink.href) == 'undefined') ? vLink : vLink.href;

	if (sLink == '')
	{
		return false;
	}

	winDef = ""
	winDef = winDef.concat('height=').concat(vHeight).concat(',width=').concat(vWidth)
	winDef = winDef.concat(',resizable=yes,scrollbars=no,menubar=no,toolbar=no,status=no,location=no,directories=no,alwaysRaised=yes')
	winDef = winDef.concat(',top=').concat((screen.height - vHeight)/2).concat(',');
	winDef = winDef.concat('left=').concat((screen.width - vWidth)/2);
	newwin = open('', '_blank', winDef);

	newwin.document.writeln('<title>Thu vien anh</title><body topmargin="0" leftmargin="0" marginheight="0" marginwidth="0">');
	newwin.document.writeln('<a href="" onClick="window.close(); return false;"><img src="', sLink, '" alt="', 'Dong lai', '" border=0></a>');
	newwin.document.writeln('</body>');

	if (typeof(vLink.href) != 'undefined')
	{
		return false;
	}
}//openImageNews

//Function check the date is valid
/**
 * DHTML date validation script. Courtesy of SmartWebby.com (http://www.smartwebby.com/dhtml/)
 */
// Declaring valid date character, minimum year and maximum year
var dtCh= "/";
var minYear=1900;
var maxYear=3000;

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;
}//isInteger

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;
}//stripCharsInBag

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 );
}//daysInFebruary

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
}//DaysArray

function isDate(dtStr){
	var daysInMonth = DaysArray(12)
	var pos1=dtStr.indexOf(dtCh)
	var pos2=dtStr.indexOf(dtCh,pos1+1)
	var strMonth=dtStr.substring(0,pos1)
	var strDay=dtStr.substring(pos1+1,pos2)
	var strYear=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("Nhập ngày có dạng : Tháng/Ngày/Năm ví dụ như 09/02/1945")
		return false
	}
	if (strMonth.length<1 || month<1 || month>12){
		//alert("Bạn phải nhập một ngày hợp lệ")
		return false
	}
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
		//alert("Bạn phải nhập một ngày hợp lệ")
		return false
	}
	if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
		//alert("Nhập năm nằm trong khoảng "+minYear+" và "+maxYear)
		return false
	}
	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
		//alert("Bạn phải nhập một ngày hợp lệ")
		return false
	}
return true
}//isDate


function onlyKeypressDigits(){
	if(event.keyCode < 48 || event.keyCode > 57){
		event.keyCode = 0;
	}
}//onlyKeypressDigits

function nonKeypress(){
	event.keyCode = 0;
}//nonKeypress

function doEnterKeypress(id){
	if((event.which && event.which == 13)||(event.keyCode && event.keyCode == 13))
	{
		document.getElementById(id).focus();
		document.getElementById(id).click();
		return false;
	} 
	else 
		return true;
}//doEnterKeypress