// JavaScript Document
var nErrorCount = 0;
var arErrorMsg 	= new Array();
var bHasFocus 	= false;
var sRootImg = "";
arErrorMsg[0] 	= "---- The following errors occured ----" + String.fromCharCode(10);

function checkFieldValue(szType, formField, szMsg,useReturnBoolean)
{	
//	if (typeof(useReturnBoolean) == 'undefined')
//		nErrorCount = 0;
	var szCheckValue 	= formField.value.replace(/^\s+/, "");
	var szValid;
	var szInvalid;
	var bAllValid 		= true;
	var bFlagDot  		= false;	
	// Blank error
	if (szType == 'noblank')
	{		
		if (szCheckValue == "")
	  	{			
		  	nErrorCount ++;
			arErrorMsg[nErrorCount] = szMsg + String.fromCharCode(10);
			if(bHasFocus == false)
			{
				bHasFocus 		= true;				
				formField.value	= "";
				formField.focus();
			}
  		}
	}
	// Kiem tra dien chi email
	else if(szType == 'email')
	{
		if(!ValidateEmail(szCheckValue))
		{
			nErrorCount ++;
			arErrorMsg[nErrorCount] = szMsg + String.fromCharCode(10);
			if(bHasFocus == false)
			{
				bHasFocus 		= true;				
				formField.focus();
			}
		}
	}
	// kiem tra co phai la ten ho khong
	else if(szType == 'vnname')
	{
		// special character
		szInvalid = "`1234567890-=\[];',./~!@#$%^&*()_+|{}:\"<>?";
		if(!isLegal(szCheckValue, szInvalid))
		{
			nErrorCount ++;
			arErrorMsg[nErrorCount] = szMsg + String.fromCharCode(10);
			if(bHasFocus == false)
			{
				bHasFocus 		= true;				
				formField.focus();
			}
		}
	}	
	// address
	else if(szType == 'vnaddress')
	{
		// special character
		szInvalid = "`=;'~!@#$%^&*()_+|{}:\"<>?";
		if(!isLegal(szCheckValue, szInvalid))
		{
			nErrorCount ++;
			arErrorMsg[nErrorCount] = szMsg + String.fromCharCode(10);
			if(bHasFocus == false)
			{
				bHasFocus 		= true;				
				formField.focus();
			}
		}
	}
	else if(szType == 'integer')
	{
		/* ^\d+$ */
		if (!szCheckValue.match(/^\d+$/))
		{
			nErrorCount ++;
			arErrorMsg[nErrorCount] = szMsg + String.fromCharCode(10);
			if(bHasFocus == false)
			{
				bHasFocus 		= true;				
				formField.focus();
			}
		}
		}
		else if(szType == 'decimal')
		{
			/* ^((\d+\.\d+)|(\d+))$ */
		if (!szCheckValue.match(/^((\d+\.\d+)|(\d+))$/))
		{
			nErrorCount ++;
			arErrorMsg[nErrorCount] = szMsg + String.fromCharCode(10);
			if(bHasFocus == false)
			{
				bHasFocus 		= true;				
				formField.focus();
			}
		}
	}
	else if(szType == 'text')
	{
		/* ^[A-Za-z\s]+$ */
		if (!szCheckValue.match(/^[A-Za-z\s]+$/))
		{
			nErrorCount ++;
			arErrorMsg[nErrorCount] = szMsg + String.fromCharCode(10);
			if(bHasFocus == false)
			{
				bHasFocus 		= true;				
				formField.focus();
			}
		}
	}
	else if(szType == 'alphanumeric')
	{
		/* ^[\w\s\.\+\-\#\,\/\(\)]+$ */
		if (!szCheckValue.match(/^[\w\s\.\+\-\#\,\\/\(\)]+$/))
		{
			nErrorCount ++;
			arErrorMsg[nErrorCount] = szMsg + String.fromCharCode(10);
			if(bHasFocus == false)
			{
				bHasFocus 		= true;				
				formField.focus();
			}
		}
	}
	else if(szType == 'alphanum')
	{
		/* ^[\w\s]+$ */
		if (!szCheckValue.match(/^[\w\s]+$/))
		{
			nErrorCount ++;
			arErrorMsg[nErrorCount] = szMsg + String.fromCharCode(10);
			if(bHasFocus == false)
			{
				bHasFocus 		= true;				
				formField.focus();
			}
		}
	}
	else if(szType == 'username')
	{
		/* ^(([A-Za-z\d][A-Za-z\d_]+[a-zA-Z\d])|([a-zA-Z\d]+))$ */
		// neu co underscore thi khong nam dau hay cuoi username
		if (!szCheckValue.match(/^(([A-Za-z\d][A-Za-z\d_]+[a-zA-Z\d])|([a-zA-Z\d]+))$/))
		{
			nErrorCount ++;
			arErrorMsg[nErrorCount] = szMsg + String.fromCharCode(10);
			if(bHasFocus == false)
			{
				bHasFocus 		= true;			
				formField.focus();
			}
		}
	}
	else if(szType == 'verificationcode')
	{
		/* ^[A-Z0-9]{5}$ */
		if (!szCheckValue.match(/^[A-Z0-9]{5}$/))
		{
			nErrorCount ++;
			arErrorMsg[nErrorCount] = szMsg + String.fromCharCode(10);
			if(bHasFocus == false)
			{
				bHasFocus 		= true;				
				formField.focus();
			}
		}
	}
	else if(szType == 'phone')
	{
		if (!szCheckValue.match(/^((\(\+?84\)[\-\.\s]?)|(\+?84[\-\.\s]?)|(0))((\d{3}[\-\.\s]?\d{6})|(\d{2}[\-\.\s]?\d{8}))$/))
		{
			
			nErrorCount ++;
			arErrorMsg[nErrorCount] = szMsg + String.fromCharCode(10);
			if(bHasFocus == false)
			{
				bHasFocus 		= true;				
				formField.focus();
			}
		}
	}
	else if(szType == 'location') 
	{
		szInvalid = "`1234567890-=\[];,./~!@#$%^&*()_+|{}:\"<>?";
		if(!isLegal(szCheckValue, szInvalid))
		{
			nErrorCount ++;
			arErrorMsg[nErrorCount] = szMsg + String.fromCharCode(10);
			if(bHasFocus == false)
			{
				bHasFocus 		= true;				
				formField.focus();
			}
		}
	}
	else if(szType == 'configvalue')
	{
		// special character
		szInvalid = "`-=\[];',~!#$%^&*()+|{}:\"<>?";
		if(!isLegal(szCheckValue, szInvalid))
		{
			nErrorCount ++;
			arErrorMsg[nErrorCount] = szMsg + String.fromCharCode(10);
			if(bHasFocus == false)
			{
				bHasFocus 		= true;				
				formField.focus();
			}
		}
	}
	else
	{
		if(szType == 'full')
		{
			szValid = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_ ";
		}
		else if(szType == 'configvariable')
		{
			szValid = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_123456789";
		}
		else if(szType == 'URL')
		{
			szValid = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789.:/\\";
		}
		else if(szType == 'path')
		{
			szValid = "0123456789.+-_#,/ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz () \\ ";
		}
		else if(szType == 'file')
		{
			szValid = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_.";
		}
		
		else
		{
			nErrorCount ++;
			arErrorMsg[nErrorCount] = "Error type."  + String.fromCharCode(10);
			return 1;
		}

		// thu tuc kiem tra, duyet chuoi can kiem tra
		for (i = 0;  i < szCheckValue.length;  i++)
  		{
    		ch = szCheckValue.charAt(i);
    		// neu co trong cac ky tu hop le thi bo qua
			for (j = 0;  j < szValid.length;  j++)
			{
	      		if (ch == szValid.charAt(j))
	      		{
					break;
	      		}

				if (j == szValid.length - 1)
				{

					bAllValid = false;
					break;
				}
			}
			if (!bAllValid)
			{
				nErrorCount ++;
				arErrorMsg[nErrorCount] = szMsg  + String.fromCharCode(10);
					
				if(bHasFocus == false)
				{
					bHasFocus 		= true;					
					formField.focus();
				}
				break;
			}
     	}
	}
	
	if (nErrorCount > 0 )
		return false;
	else
		return true;
}
function ValidateEmail(szEmail)
{
	// chi co 1 ky tu @ o giua, chieu dai username tu 1 den 64 ky tu
	// chieu dai domain tu 1 den 255 ky tu
	if (!szEmail.match(/^[^@]{1,64}@[^@]{1,255}$/))
	{
		return false;
	}

  	// chia 2 phan truoc va sau @
  	szEmailArray = szEmail.split("@");
  	// szEmailArray[0] user, szEmailArray[1] domain

  	// phan username, chieu dai tu max 64 ky tu
  	// valid character la ky tu chu a-zA-Z, ky tu so 0-9 dash _ hyphen - va dot .
  	// neu de trong quote "langxang, at vinacyber dot com dot vn!"@server.com
  	// tach cac phan phan chia boi dot .
  	szLocalArray = szEmailArray[0].split(".");

  	// kiem tra tung phan
  	for(i = 0; i < szLocalArray.length; i ++)
  	{
  		// part 1: neu co dau dash hay hyphen thi khong co o dau va o cuoi
  		// part 2: neu khong do dash hay hyphen thi la A-Za-z0-9 chieu dai tu 1 den 64 ky tu
  		// part 3: neu trong quote, phan trong quote khong chua \" dau quote hay \\ va back slash
		if (!szLocalArray[i].match(/^(([A-Za-z0-9][A-Za-z0-9_-]{0,62}[A-Za-z0-9])|([A-Za-z0-9]{1,64})|(\"[^(\\|\")]{0,62}\"))$/))
		{
      		return false;
    	}
  	}

  	// domain khong phai la IP
  	if (!szEmailArray[1].match(/\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b/))
  	{
  		// kiem tra valid domain, tach tung phan domain
    	szDomainArray = szEmailArray[1].split(".");
    	// it nhat co 2 phan cua domain sau @
    	if (szDomainArray.length < 2)
    	{
        	return false;
    	}

    	// kiem tra tung phan
    	for(i = 0; i < szDomainArray.length; i++)
    	{
    		// maxinum la 64, chua A-Za-z, 0-9, co the chua hyphen -
    		// dau hyphen khong o dau va khong o cuoi, domain case in-sensitive
    		// neu khong co hyphen thi la A-Za-z0-9
			if (!szDomainArray[i].match(/^(([A-Za-z0-9][A-Za-z0-9-]{0,62}[A-Za-z0-9])|([A-Za-z0-9]{0,64}))$/))
			{
        		return false;
      		}
    	}

    	// kiem tra top domain
		// szDomainArray[szDomainArray.length - 1]
  	}
  	return true;
}
function isLegal(szCheck, szInvalid) {
	// szInvalid cac ky tu dac biet
	for(i = 0; i < szInvalid.length; i ++) {
		// co ky tu dac biet trong chuoi can check
		if(szCheck.indexOf(szInvalid.charAt(i)) >= 0 )	{
			return false;
		}
    }
	return true;
}
function switchMainTab(index)
{	
	tabs = document.getElementById("idMenu").getElementsByTagName("li");
	for(var i = 0; i < tabs.length; i++) {
		if(tabs[i].className == "current") {
			/* Deactivate */
			tabs[i].className = "";
		}
	}
	if( index > -1 && index < tabs.length){
		/* Activate */
		tabs[index].className = "current";
	}
}

function switchSubTab(index)
{
	tabs = document.getElementById("idSubTab").getElementsByTagName("li");
	for(var i = 0; i < tabs.length; i++) {
		if(tabs[i].className == "current") {
			/* Deactivate */
			tabs[i].className = "";
		}
	}
	if( index > -1 && index < tabs.length){
		/* Activate */
		tabs[index].className = "current";
	}
}

function switchSubMenu(index)
{	
	tabs = document.getElementById("idLogin").getElementsByTagName("li");
	for(var i = 0; i < tabs.length; i++) {
		if(tabs[i].className == "current") {
			/* Deactivate */
			tabs[i].className = "";
		}
	}
	if( index > -1 && index < tabs.length){
		/* Activate */
		tabs[index].className = "current";
	}
}
/**
* Written by 		: Trương Kim Phụng
* Dated by			: 06/07/2007
* Description		: Kiểm tra tính hợp lệ của ngày nhập liệu
* Function			: function isValidDate
* @param strDate	: Ngày cần kiểm tra
* @param strMessage1: Thông báo tin ra
* @param strMessage2: Thông báo tin ra
*/
function checkDate( strDate, strMessage1, strMessage2 ) 
{
 /**gia tri nhap vao phai la dd/mm/yyyy*/
	var arrayDATE;
    var dtest;
   	arrayDATE = strDate.split("/"); 
	/** ngay cua he thong la mm/dd/yyyy nen phai doi ra ngay he thong */
	dtest = new Date(arrayDATE[1] + "/" + arrayDATE[0] + "/" + arrayDATE[2]);   
    if (dtest.getDate() != arrayDATE[0] || dtest.getMonth() +1 != arrayDATE[1] || dtest.getFullYear() != arrayDATE[2]) 
	{
    	//alert( strMessage1 );   
		return false;
    }
	if (arrayDATE[2]<=1900) 
	{
	   /**neu nam nho hon 1900 thi se ko insert duoc vao sql server*/
		//alert(strMessage2);  
		return false;
	}
	return true;
}

/**
* Written by 		: Nguyễn Thị Nguyệt Minh
* Dated by			: 1/11/2007
* Description		: so sánh 2 ngày
* Function			: function compareDate
*/
function compareDate( strDate1, strDate2 ) 
{
    if (Date.parse(strDate1) < Date.parse(strDate2)) 
	{
    	return 0;
    }
	else if (Date.parse(strDate1) == Date.parse(strDate2)) 
	{
	    return 1;
	}
	return 2;
}

/**
* Written by 		: Nguyễn Thị Nguyệt Minh
* Dated by			: 08/097/2007
* Description		: kiểm tra ký tự nhập vào có là số hay ko
* Function			: function checkKey
*/
function checkKey(e){
	if ((e.keyCode >= 48 && e.keyCode <= 57) || e.keyCode == 8 || (e.keyCode>=96 && e.keyCode<=105) || e.keyCode == 9)
		return true;
	else
		return false;
}
/**
* 
*/
function ExpandDiv(theDivName){
	InitializeGlobalData();
	if (null == theDivName || typeof(theDivName) == "undefined") 
		return; 
	var theDiv = allDivs[theDivName]; 
	if (null == theDiv || typeof(theDiv) == "undefined") return;
	
	if(navigator.appName.indexOf("Microsoft") > -1)
		theDiv.style.display = "block";
	else
		theDiv.style.display = "table-row";				
			
	var thePic = allImages[theDivName + "_img"];		
	if (null != thePic && typeof(thePic) != "undefined")
	{
		//thePic.src = "../images/hentocdo/down.gif";
		thePic.src = sRootImg + "images/icon_ropdown.gif";
		thePic.alt = strHide;		
	}
}
function CollapseDiv(theDivName){
	InitializeGlobalData();	
	if (null == theDivName || typeof(theDivName) == "undefined") return; 
	var theDiv = allDivs[theDivName]; 
	if (null == theDiv || typeof(theDiv) == "undefined") return;
	theDiv.style.display = "none";
	var thePic = allImages[theDivName + "_img"];
	if (null != thePic && typeof(thePic) != "undefined")
	{		
		//thePic.src = "../images/hentocdo/up.gif";			
		thePic.src = sRootImg + "images/icon_roptop.gif";	
		thePic.alt = strShow;
	}
}

function ToggleDiv(theDivName, rootimg)
{
	if (typeof(rootimg) != "undefined") sRootImg = rootimg;
	InitializeGlobalData();
	
	if (null == theDivName || typeof(theDivName) == "undefined") return; 
	var theDiv = allDivs[theDivName];			
	if (null == theDiv || typeof(theDiv) == "undefined") return;		
	if (theDiv.style.display.toUpperCase() != "BLOCK" && theDiv.style.display.toUpperCase() != "TABLE-ROW") 
		ExpandDiv(theDivName);
	
	else
		CollapseDiv(theDivName);
}
function mygo(url){
	navigate(url);
}
function InitializeGlobalData(){	
	allDivs   = document.body.getElementsByTagName("div");
	allSpans  = document.body.getElementsByTagName("span");
	allImages = document.body.getElementsByTagName("img");		
}
var strShow = 'Show';
var strHide = 'Hide';


var flagXuLyPoint;
//Kiểm tra gõ key
function checkCommaKey(e){
	var keyCode //= (window.event) ? event.keyCode : e.which;   
	if (window.event) keyCode = event.keyCode   
	else keyCode = e.which   
	// Was key that was pressed a numeric character (0-9) or . or <- or -> or backspace (8)?   
	if ( keyCode > 47 && keyCode < 58  || keyCode == 44 ||  keyCode == 37 || keyCode == 39 || keyCode == 8 ) {
		flagXuLyPoint = true;
		return; // if so, do nothing   else // otherwise, discard character   
	}
	flagXuLyPoint = false;
	if (window.event) //IE       
		window.event.returnValue = null;     
	else //Firefox       
		e.preventDefault(); 
}


function checkPointKey(e){
	var keyCode //= (window.event) ? event.keyCode : e.which;   
	if (window.event) keyCode = event.keyCode   
	else keyCode = e.which   
	// Was key that was pressed a numeric character (0-9) or <- or -> or backspace (8)?   
	if ( keyCode > 47 && keyCode < 58 ||  keyCode == 37 || keyCode == 39 || keyCode == 8 ) {
		flagXuLyPoint = true;
		return; // if so, do nothing   else // otherwise, discard character   
	}
	flagXuLyPoint = false;
	if (window.event) //IE       
		window.event.returnValue = null;     
	else //Firefox       
		e.preventDefault(); 
	 
}
function addPoint(node ){
	var str 	= node.value;
	if(!flagXuLyPoint)	return;	
	str =filter(str ,'0123456789');		
	var cont = true;
	while(cont){
		if(str.charAt(0) == '0'){
			str = str.substr(1,str.length);
		}
		else cont = false;
	}
	temp="";
	for(i=str.length-1; i>=0; i--){
		temp=str.charAt(i)+temp;		
		if ( (((i-str.length)%3)==0) && (i!=0)){
			temp= '.' + temp;
		}
	}	
	node.value = temp ;		
}
function filter(inputString, filterString){
	outString = "";	
	for(i=0; i<inputString.length; i++){
		if(filterString.indexOf(inputString.substr(i,1) )!=-1)
			outString = outString + inputString.substr(i,1);
	}	
	return outString;
}
function keyUp(idField, strValue) {
	strResult	= document.getElementById(idField).value;		
	addPoint(strValue);		
}
function onChange(strInput, idField) {	
	strValue = document.getElementById(idField).value;	
	if(strInput.value == 'VND') {
		/**
		* Từ $124,450.20 --> 124.450,20 VND 
		*/
		arrValue = strValue.split('.');		
		if(arrValue.length > 1 ) {
			strResult = replace(arrValue[0], ",", "\.") + ',' + arrValue[1];
		}
		else {
			strResult = replace(strValue, ",", "\.");				
		}
	}
	else {	
		/**
		* Từ 124.450,20 VND --> $124,450.20 
		*/
		arrValue = strValue.split(',');		
		if(arrValue.length > 1 ) {
			strResult = replace(arrValue[0], "\.", ",") + '.' + arrValue[1];
		}
		else {
			strResult = replace(strValue, "\.", ",");
			alert
		}				
	}
	document.getElementById(idField).value = strResult;
}
function replace(string,text,by) {
	// Replaces text with by in string
    var strLength = string.length, txtLength = text.length;
    if ((strLength == 0) || (txtLength == 0)) return string;

    var i = string.indexOf(text);
    if ((!i) && (text != string.substring(0,txtLength))) return string;
    if (i == -1) return string;

    var newstr = string.substring(0,i) + by;

    if (i+txtLength < strLength)
        newstr += replace(string.substring(i+txtLength,strLength),text,by);

    return newstr;
}

function $id(id){return document.getElementById(id);}
function $idS(id){return $(id).style;}

function getCookie(c_name)
{
if (document.cookie.length>0)
  {
  c_start=document.cookie.indexOf(c_name + "=");
  if (c_start!=-1)
    { 
    c_start=c_start + c_name.length+1; 
    c_end=document.cookie.indexOf(";",c_start);
    if (c_end==-1) c_end=document.cookie.length;
    return unescape(document.cookie.substring(c_start,c_end));
    } 
  }
return "";
}
function isChecked(obj){//kiem tra user co chon radio button or checkbox
	for(i=0; i<obj.length; i++){
		if(obj[i].checked==true)
			return true;
	}
	return false;
}
function errorFound(obj,msg){
    if(msg)alert(msg);
    obj.focus();	 
	if (obj.type=="text" || obj.type=="textarea" || obj.type=="password"){
	    //obj.style.backgroundColor="#ff6666";
		obj.select();
	}
     obj.onclick=mkwhite;
     obj.onkeydown=mkwhite;
     return false;
}
function mkwhite(){this.style.backgroundColor="ffffff";}

function invite(input)
{	
	var index 	= 0;
	var mask  	='0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_';
	var len 	= input.value.length;
	
		while (index < len) {
			if (mask.indexOf(input.value.charAt(index)) == -1)
			{
				if (index == len-1){
					input.value = input.value.substring(0, len-1);
				}
				else{
				if (index == 0)
						input.value = input.value.substring(1, len);
					 else 
						input.value = input.value.substring(0, index)+input.value.substring(index+1, len);
				}
				index = 0;
				len = input.value.length;
			}
			else index++;
		}
	
}


	function changeLang(curLang,newLang)
	{
		if (curLang == newLang ) return ;
		curLoc  = document.location.href;
		if (curLoc.indexOf('lang=')>0)
			newLoc  = curLoc.replace('lang='+curLang, 'lang='+newLang);
		else
			newLoc  = curLoc + (curLoc.indexOf('?') >  0 ? '&':'?') + 'lang='+newLang ;
		document.location.href = newLoc;
	}
	function actionSubmit(frm, action, ischeck) {
		if (typeof(ischeck) == 'undefined') ischeck = true;//check has choose checkbox
		if (ischeck == false)
		{
				frm.btnClick.value = action;		
				frm.submit();
				return true;
		}
		if (isChooseRecord(frm) )
		{		
			frm.btnClick.value = action;		
			if (action == 'delete')
				if (confirm('Bạn có chắc muốn xóa những record này ?') ==false) return false;
			frm.submit();
		}
		return true;
	}
	function changeMainImg(idObjectChange, newImage)
	{
		$id(idObjectChange).src= newImage;
	}
	function preLoadImg(image)
	{
		img = new Image();
		img.src= image;
	}

