var servertime = new Date();
var str_servertime = "";
var defaultUserURL = "../khanggia/";
function getClock(langid)
{
    var DayEN = "Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday";
    var DayVN = "Chủ nhật,Thứ hai,Thứ ba,Thứ tư,Thứ năm,Thứ sáu,Thứ bảy";
    var arrDayEN = new Array();
    arrDayEN = DayEN.split(",");
    var arrDayVN = new Array();
    arrDayVN = DayVN.split(",");
    
    var MonthEN = "January,February,March,April,May,June,July,August,September,October,November,December";
    var MonthVN = "Tháng giêng,Tháng hai,Tháng ba,Tháng tư, Tháng năm,Tháng sáu,Tháng bảy,Tháng tám,Tháng chín,Tháng mười,Tháng mười một,Tháng mười hai";
    var arrMonthEN = new Array();
    arrMonthEN = MonthEN.split(",");
    var arrMonthVN = new Array();
    arrMonthVN = MonthVN.split(",");
    if(str_servertime!="")
    {
        var InputDateTime = new Array();
        var InputDate = new Array();
        var InputTime = new Array();
        var InputSize = "";
        InputDateTime = str_servertime.split(" ");
        InputDate = InputDateTime[0].split("/");
        InputTime = InputDateTime[1].split(":");
        InputSize = InputDateTime[2];  
        servertime.setUTCFullYear(InputDate[2],InputDate[0]-1,InputDate[1]);
        var hour = InputTime[0]*1;
        if(InputSize == "PM")
           hour = hour+12;
        //if (hour == 24 ) 
        //    hour = 0;
        servertime.setHours(hour,InputTime[1],InputTime[2]);
    }
    var thetime= new Date();
    var thetime=servertime;
    thetime.setSeconds(servertime.getSeconds()+1);
    var nhours=thetime.getHours();
    var nmins=thetime.getMinutes();
    var nsecn=thetime.getSeconds();
    var nday=thetime.getDay();
    var nmonth=thetime.getMonth();
    var ntoday=thetime.getDate();
    var nyear=thetime.getYear();
    var AorP=" ";
    
    if(langid=="en")
    {
        if (nhours>=12)
        {
           AorP="P.M.";
        }
        else
        {
           AorP="A.M.";
        }
        if (nhours>=13)
            nhours-=12;
        if (nhours==0)
            nhours=12;
    }

    if (nsecn<10)
     nsecn="0"+nsecn;

    if (nmins<10)
     nmins="0"+nmins;
     
    nmonth+=1;

    if (nyear<=99)
      nyear= "19"+nyear;

    if ((nyear>99) && (nyear<2000))
     nyear+=1900;
    var result = "";
    if(langid=="vi") 
    {
        result = arrDayVN[nday]+", "+ntoday+" "+arrMonthVN[nmonth-1]+", "+nyear+" - "+nhours+":"+nmins+":"+nsecn;
    }
    else
    {
        result = arrDayEN[nday]+", "+arrMonthEN[nmonth-1]+" "+ntoday+", "+nyear+" - "+nhours+":"+nmins+":"+nsecn+" "+AorP;
    }
    return result;
}
function startclock(langid)
{
    var result = getClock(langid);
	if(document.getElementById('spotclock')!=null)
	{
		document.getElementById('spotclock').innerHTML=result;
		str_servertime = "";
		setTimeout('startclock("'+langid+'")',1000);
	}
} 
function popup(mylink, windowname,width,height)
{
	if (! window.focus)
		return true;
	var href;
	if (typeof(mylink) == 'string')
	   href=mylink;
	else
	   href=mylink.href;
	window.open(href, windowname, 'width='+width+',height='+height+',scrollbars=no');
	return false;
}
function changeLanguage(lang)
{
	document.frmHead.lang.value = lang;
	document.frmHead.submit();
}
/*
   name - name of the cookie
   value - value of the cookie
   [expires] - expiration date of the cookie
     (defaults to end of current session)
   [path] - path for which the cookie is valid
     (defaults to path of calling document)
   [domain] - domain for which the cookie is valid
     (defaults to domain of calling document)
   [secure] - Boolean value indicating if the cookie transmission requires
     a secure transmission
   * an argument defaults when it is assigned null as a placeholder
   * a null placeholder is not required for trailing omitted arguments
*/

function setCookie(name, value, expires, path, domain, secure) {
  var curCookie = name + "=" + escape(value) +
      ((expires) ? "; expires=" + expires.toGMTString() : "") +
      ((path) ? "; path=" + path : "") +
      ((domain) ? "; domain=" + domain : "") +
      ((secure) ? "; secure" : "");
  document.cookie = curCookie;
}


/*
  name - name of the desired cookie
  return string containing value of specified cookie or null
  if cookie does not exist
*/

function getCookie(name) {
  var dc = document.cookie;
  var prefix = name + "=";
  var begin = dc.indexOf("; " + prefix);
  if (begin == -1) {
    begin = dc.indexOf(prefix);
    if (begin != 0) return null;
  } else
    begin += 2;
  var end = document.cookie.indexOf(";", begin);
  if (end == -1)
    end = dc.length;
  return unescape(dc.substring(begin + prefix.length, end));
}


/*
   name - name of the cookie
   [path] - path of the cookie (must be same as path used to create cookie)
   [domain] - domain of the cookie (must be same as domain used to
     create cookie)
   path and domain default if assigned null or omitted if no explicit
     argument proceeds
*/

function deleteCookie(name, path, domain) {
  if (getCookie(name)) {
    document.cookie = name + "=" +
    ((path) ? "; path=" + path : "") +
    ((domain) ? "; domain=" + domain : "") +
    "; expires=Thu, 01-Jan-70 00:00:01 GMT";
  }
}

// date - any instance of the Date object
// * hand all instances of the Date object to this function for "repairs"

function fixDate(date) {
  var base = new Date(0);
  var skew = base.getTime();
  if (skew > 0)
    date.setTime(date.getTime() - skew);
}
function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}
/*check form */
/*-------------------------------------------------------------------------------------
Date: 17/08/2006
Author: ThangVQ
File: checkImage.js
Purpose: check all text field in the form
Change: first create
-------------------------------------------------------------------------------------*/
function round_number (num, dec) 
{ // low-level numeric format with upward rounding at 5+ 
 var cDec = '.'; // decimal point symbol 
 if (!(dec >= 0 && dec <= 9)) 
  dec = 2; 
 if (isNaN (num) || num == '') 
 { // zero values are returned in proper decimal format 
  var sdec = ""; 
  for (var i = 0; i < dec; i++) 
   sdec += '0'; 
  return "0" + (sdec != "" ? cDec + sdec : ""); 
 } 
 var snum = new String (num); 
 var arr_num = snum.split (cDec); 
 var neg = ''; 
 var nullify = 0; 
 dec_a = arr_num.length > 1 ? arr_num[1].length : 0; 
 if (dec_a <= dec) 
 { // fill decimal places with trailing zeros if necessary 
  if (!dec_a) 
   arr_num[1] = ""; 
  for (var i = 0; i < dec - dec_a; i++) 
   arr_num[1] += '0'; 
  dec_a = dec; 
 } 
 // total decimal places in value before rounding and formatting 
 dec_i = dec_a; 
 dec_a -= dec; 
 if (arr_num[0].charAt(0) == '-') 
 { // preserve negative symbol, remove from value (calculations) 
  neg = '-'; 
  arr_num[0] = arr_num[0].substring (1, arr_num[0].length); 
 } 
 if (!parseInt (arr_num[0])) // case when whole value is 0 
 { // nullify a zero whole value for correct decimal point placement 
  arr_num[0] = "1"; // 0 whole # would not preserve amount in calc. 
  nullify = 1; // flag to remove greatest 1 portion from whole # 
 } 
 var whole = parseInt (arr_num[0] * Math.pow (10, arr_num[1].length)); 
 // remove leading zeros 
 for (i = 0; i < arr_num[1].length; i++) 
  if (arr_num[1].charAt (i) != '0') 
   break; 
 if (arr_num[1].length == i) // decimal portion blank or all zeros 
  return (neg + arr_num[0] + (arr_num[1] != "" ? (cDec + arr_num[1]) : "")); 
 whole += parseInt (arr_num[1].substring (i, arr_num[1].length)); 
 if (arr_num[1].length != dec) 
 { // round number affecting appropriate cluster of decimal places 
  var diff = ""; 
  var str = new String (whole); 
  for (i = dec_a; i > 0; i--) 
   diff += str.charAt (str.length - i); 
  diff = Math.pow (10, dec_a) - parseInt (diff); 
  whole += ((diff <= 5 * Math.pow (10, dec_a - 1)) ? diff : 0); 
 } 
 str = new String (whole); 
 var str_f = ""; 
 var j = 0; 
 var k = 0; 
 if (nullify) 
 { 
  arr_num[0] = "0"; // remove 1 from greatest decimal place (restoration) 
  str = (parseInt (str.charAt(0)) - 1) + str.substring (1, str.length); 
 } 
 else // re-assign whole numeric portion from entire numeric string value 
  arr_num[0] = str.substring (0, str.length - dec_i); 
 for (i = 0; i < str.length; i++) 
 { // combine portions of decimal number (whole, fraction, sign) 
  if (k - 1 > dec) 
   break; // fraction termination case 
  if (j == arr_num[0].length) 
  { 
   if (!j) 
    str_f += 0; 
   str_f += (dec != 0 ? cDec : ''); // insert decimal point 
   --i; // backtrack one character 
   k++; // signal fraction count 
  } 
  else // assign character by character 
   str_f += str.charAt (i); 
  j++; 
  if (k) // fractional counter increment 
   k++; 
 } 
 return neg + str_f; 
} 


function input_filterAmt (str, dec, bNeg) 
{ // auto-correct input - force numeric data based on params. 
 var cDec = '.'; // decimal point symbol 
 var bDec = 0; var val = ""; 
 var strf = ""; var neg = ""; var i = 0; 

 if (str == "") return; round_number (parseFloat ("0"), dec); 
 if (bNeg && str.charAt (i) == '-') { neg = '-'; i++; } 

 for (i; i < str.length; i++) 
 { 
  val = str.charAt (i); 
  if (val == cDec) 
  { 
   if (!bDec) { strf += val; bDec = 1; } 
  } 
  else if (val >= '0' && val <= '9') 
   strf += val; 
 } 
 strf = (strf == "" ? 0 : neg + strf); 
 return round_number (parseFloat (strf), dec); 
} 


function isDecimal(value)
{
		
		pattern =/^[+,-]*[0-9]([0-9]*,*[0-9]*)*\.?[0-9]*$/;
		if(pattern.test(value)==false)
		{
			return false;
		}
	
	return true;

}

function addCommas( strValue ) {
/************************************************
DESCRIPTION: Inserts commas into numeric string.

PARAMETERS:
  strValue - source string containing commas.

RETURNS: String modified with comma grouping if
  source was all numeric, otherwise source is
  returned.

REMARKS: Used with integers or numbers with
  2 or less decimal places.
*************************************************/
  var objRegExp  = new RegExp('(-?[0-9]+)([0-9]{3})');

    //check for match to search criteria
    while(objRegExp.test(strValue)) {
       //replace original string with first group match,
       //a comma, then second group match
       strValue = strValue.replace(objRegExp, '$1,$2');
    }
  return strValue;
}

function ltrim(str) { 
	for(var k = 0; k < str.length && isWhitespaceChar(str.charAt(k)); k++);
	return str.substring(k, str.length);
}
function rtrim(str) {
	for(var j=str.length-1; j>=0 && isWhitespaceChar(str.charAt(j)) ; j--) ;
	return str.substring(0,j+1);
}
function trim(str) {
	return ltrim(rtrim(str));
}
function isWhitespaceChar(charToCheck) {
	var whitespaceChars = " \t\n\r\f";
	return (whitespaceChars.indexOf(charToCheck) != -1);
}
// returns true if the string is empty
function isEmpty(str){
	return (str == null) || (str.length == 0);
}
// returns true if the string is a valid email
function isEmail(str){
	if(isEmpty(str)) return false;
	var re = /^[^\s()<>@,;:\/]+@\w[\w\.-]+\.[a-z]{2,}$/i;
	return re.test(str);
}
// returns true if the string only contains characters A-Z or a-z
function isAlpha(str){
	var re = /[^a-zA-Z]/g;
	if (re.test(str)) return false;
	return true;
}
// returns true if the string only contains characters 0-9
function isPositiveNumeric(str){
	var re = /[\D]/g;
	if (re.test(str)) return false;
	return true;
}
// returns true if the string only contains characters -,0-9
function isNumber(str){
	pattern = /^-{0,1}\d*\.{0,1}\d+$/;
		if(pattern.test(str)==false)
		{
			return false;
		}
	
	return true;
}
// returns true if the string only contains characters A-Z, a-z or 0-9
function isAlphaNumeric(str){
	var re = /[^a-zA-Z0-9]/g;
	if (re.test(str)) return false;
	return true;
}
// returns true if the string's length equals "len"
function isLength(str, len){
	return str.length == len;
}
// returns true if the string's length is between "min" and "max"
function isLengthBetween(str, min, max){
	return (str.length >= min)&&(str.length <= max);
}
// returns true if the string is a US phone number formatted as...
// (000)000-0000, (000) 000-0000, 000-000-0000, 000.000.0000, 000 000 0000, 0000000000
function isPhoneNumber(str){
	var re = /^\(?[2-9]\d{2}[\)\.-]?\s?\d{3}[\s\.-]?\d{4}$/;
	return re.test(str);
}
// returns true if the string is a valid date formatted as...
// mm dd yyyy, mm/dd/yyyy, mm.dd.yyyy, mm-dd-yyyy
function isDate(str){
	var re = /^(\d{1,2})[\s\.\/-](\d{1,2})[\s\.\/-](\d{4})$/;
	if (!re.test(str)) return false;
	var result = str.match(re);
	var m = parseInt(result[1]);
	var d = parseInt(result[2]);
	var y = parseInt(result[3]);
	if(m < 1 || m > 12 || y < 1900 || y > 2100) return false;
	if(m == 2){
		var days = ((y % 4) == 0) ? 29 : 28;
	}else if(m == 4 || m == 6 || m == 9 || m == 11){
		var days = 30;
	}else{
		var days = 31;
	}
	return (d >= 1 && d <= days);
}
// returns true if "str1" is the same as the "str2"
function isMatch(str1, str2){
	return str1 == str2;
}
// returns true if the string contains only whitespace
// cannot check a password type input for whitespace
function isWhitespace(str){ // NOT USED IN FORM VALIDATION
	var re = /[\S]/g;
	if (re.test(str)) return false;
	return true;
}
// removes any whitespace from the string and returns the result
// the value of "replacement" will be used to replace the whitespace (optional)
function stripWhitespace(str, replacement){// NOT USED IN FORM VALIDATION
	if (replacement == null) replacement = '';
	var result = str;
	var re = /\s/g;
	if(str.search(re) != -1){
		result = str.replace(re, replacement);
	}
	return result;
}

function isFile(value)
{
 if (isNull(value))
 {
  return "null";
 }
 else if (value.substring(value.length - 4, value.length).toLowerCase() != ".jpg" && value.substring(value.length - 4, value.length).toLowerCase() != ".gif")
 {
  return "notimg";
 }
 else
 {
  return true;
 }
}
function isNull(str)
{
	if( (isEmpty(str)==true))
		return true;
	return false;
}

function checkField(field,require,type,attr,compare)
{
 	var value = trim(field.value);
 	var i = 0;
 	var arr_result = '';
 	if(require == 'notnull' && isNull(value)==true)
 	{
 	
		arr_result = ' còn trống!';
	
 	} 
 	else if(attr>0 && isLengthBetween(value,0,attr)==false)
	{
		arr_result = ' quá dài';
	}
	else if(compare!=false && trim(value)!=trim(compare))
	{
		arr_result = ' không giống nhau';
	}
	else
	{
		switch(type)
		{
			case 'number':
				if(value!='' && isPositiveNumeric(value)==false)
					arr_result = ' phải là số!';
				break;
			case 'email':
				if(value!='' && isEmail(value)==false)
					arr_result = ' không phải là email!';
				break;

			case 'phone':
				if(value!='' && isPhoneNumeric(value)==false)
					arr_result = ' không phải là số điện thoại';
				break;
		
			case 'onlytext':
				if(value!='' && isAlpha(value)==false)
					arr_result = ' không hợp lệ';
				break;

			case 'onlytextnumber':
				if(value!='' && isAlphaNumeric(value)==false)
					arr_result = ' không hợp lệ';
				break;

			case 'decimal':
				if(value!='' && isDecimal(value,5)==false)
					arr_result = ' không hợp lệ';
				break;
			case 'interger':
				if(value!='' && isNumber(value)==false)
					arr_result = ' không phải là số';
				break;
				
			case 'default':
				break;
		}
	}	

 return arr_result;
}
var tempRowColor;
function changeRowColor(obj)
{
	tempRowColor=obj.style.backgroundColor;
	obj.style.backgroundColor='#FFF2E6';
}
function getBackRowColor(obj)
{
	obj.style.backgroundColor=tempRowColor;	
}
function changeImageButton(objectsource, imageSource)
{
	objectsource.src = imageSource;
}
function toggleComment(id)
{
    var CommentPlace = document.getElementById(id);
    
    if(CommentPlace.style.display == "none")
    {
        CommentPlace.style.display = "block";
    }
    else
    {
        CommentPlace.style.display = "none";
    }
}
var ns4,op5,op6,agt,mac,ie,mac_ie;
function sniffBrowsers() {
	ns4 = document.layers;
	op5 = (navigator.userAgent.indexOf("Opera 5")!=-1) ||(navigator.userAgent.indexOf("Opera/5")!=-1);
	op6 = (navigator.userAgent.indexOf("Opera 6")!=-1) ||(navigator.userAgent.indexOf("Opera/6")!=-1);
	agt=navigator.userAgent.toLowerCase();
	mac = (agt.indexOf("mac")!=-1);
	ie = (agt.indexOf("msie") != -1); 
	mac_ie = mac && ie;
}


function getStyleObject(objectId) {
    if(document.getElementById && document.getElementById(objectId)) {
	return document.getElementById(objectId).style;
    } else if (document.all && document.all(objectId)) {
	return document.all(objectId).style;
    } else if (document.layers && document.layers[objectId]) {
		return getObjNN4(document,objectId);
    } else {
	return false;
    } 
} 

function changeObjectVisibility(objectId, newVisibility) {
    var styleObject = getStyleObject(objectId, document);
    if(styleObject) {
	styleObject.visibility = newVisibility;
	return true;
    } else {
	return false;
    }
} 

function findImage(name, doc) {
	var i, img;
	for (i = 0; i < doc.images.length; i++) {
    	if (doc.images[i].name == name) {
			return doc.images[i];
		}
	}
	for (i = 0; i < doc.layers.length; i++) {
    	if ((img = findImage(name, doc.layers[i].document)) != null) {
			img.container = doc.layers[i];
			return img;
    	}
	}
	return null;
}

function getImage(name) {
	if (document.layers) {
    	return findImage(name, document);
	}
	return null;
}

function getObjNN4(obj,name)
{
	var x = obj.layers;
	var foundLayer;
	for (var i=0;i<x.length;i++)
	{
		if (x[i].id == name)
		 	foundLayer = x[i];
		else if (x[i].layers.length)
			var tmp = getObjNN4(x[i],name);
		if (tmp) foundLayer = tmp;
	}
	return foundLayer;
}

function getElementHeight(Elem) {
	if (ns4) {
		var elem = getObjNN4(document, Elem);
		return elem.clip.height;
	} else {
		var elem;
		if(document.getElementById) {
			var elem = document.getElementById(Elem);
		} else if (document.all){
			var elem = document.all[Elem];
		}
		if (op5) {
			xPos = elem.style.pixelHeight;
		} else {
			xPos = elem.offsetHeight;
		}
		return xPos;
	} 
}

function getElementWidth(Elem) {
	if (ns4) {
		var elem = getObjNN4(document, Elem);
		return elem.clip.width;
	} else {
		var elem;
		if(document.getElementById) {
			var elem = document.getElementById(Elem);
		} else if (document.all){
			var elem = document.all[Elem];
		}
		if (op5) {
			xPos = elem.style.pixelWidth;
		} else {
			xPos = elem.offsetWidth;
		}
		return xPos;
	}
}

function getElementLeft(Elem) {
	if (ns4) {
		var elem = getObjNN4(document, Elem);
		return elem.pageX;
	} else {
		var elem;
		if(document.getElementById) {
			var elem = document.getElementById(Elem);
		} else if (document.all){
			var elem = document.all[Elem];
		}
		xPos = elem.offsetLeft;
		tempEl = elem.offsetParent;
  		while (tempEl != null) {
  			xPos += tempEl.offsetLeft;
	  		tempEl = tempEl.offsetParent;
  		}
		return xPos;
	}
}


function getElementTop(Elem) {
	if (ns4) {
		var elem = getObjNN4(document, Elem);
		return elem.pageY;
	} else {
		if(document.getElementById) {	
			var elem = document.getElementById(Elem);
		} else if (document.all) {
			var elem = document.all[Elem];
		}
		yPos = elem.offsetTop;
		tempEl = elem.offsetParent;
		while (tempEl != null) {
  			yPos += tempEl.offsetTop;
	  		tempEl = tempEl.offsetParent;
  		}
		return yPos;
	}
}


function getImageLeft(myImage) {
	var x, obj;
	if (document.layers) {
		var img = getImage(myImage);
    	if (img.container != null)
			return img.container.pageX + img.x;
		else
			return img.x;
  	} else {
		return getElementLeft(myImage);
	}
	return -1;
}

function getImageTop(myImage) {
	var y, obj;
	if (document.layers) {
		var img = getImage(myImage);
		if (img.container != null)
			return img.container.pageY + img.y;
		else
			return img.y;
	} else {
		return getElementTop(myImage);
	}
	return -1;
}

function getImageWidth(myImage) {
	var x, obj;
	if (document.layers) {
		var img = getImage(myImage);
		return img.width;
	} else {
		return getElementWidth(myImage);
	}
	return -1;
}

function getImageHeight(myImage) {
	var y, obj;
	if (document.layers) {
		var img = getImage(myImage);
		return img.height;
	} else {
		return getElementHeight(myImage);
	}
	return -1;
}

function moveXY(myObject, x, y) {
	obj = getStyleObject(myObject);
	if (ns4) {
		obj.top = y;
 		obj.left = x;
	} else {
		if (op5) {
			obj.pixelTop = y;
 			obj.pixelLeft = x;
		} else {
			obj.top = y + 'px';
 			obj.left = x + 'px';
		}	
	}
}
function toggle(aDivId)
{
    try
    {
        var aDiv = document.getElementById(aDivId);
        if (aDiv.style.display == "none")
            aDiv.style.display = "block";
        else
            aDiv.style.display = "none";    
    }
    catch(e)
    {
    }
}
sniffBrowsers();
