var errEmptyEventTitle = "Please insert your Event Title";
var errEmptyEventRoom = "Please insert your Room Title";
var errEmptyEventID = "Please select Event Name";
var errEmptyGrant = "Please marking your Grant Privilege or marking at All checkbox ";
var errEmptyTeam = "Please marking your Team Privilege or marking at All checkbox ";
var errEmptyTopicName = "Please insert Topic Speaker's Name";
var errEmptyTopicTitle = "Please insert Topic Title";
var errEmptyTopicStatus = "Please select Topic Speaker's Status";
var errEmptyBoardTopic = "Please insert Webboard Topic ";
var errEmptyBoardMsg = "Please insert Webboard Message English or Thai" ;
var errEmptyReplyMsg = "Please insert Reply Message English or Thai " ;
var errEmptyMainNewsTitle = "Please insert News Topic";
var errEmptyMainNewsDetail = "Please insert News Detail";
var errErrReEmail = "Please Check Email and Confirm Email again";
var errEmptyInviteCode = "Please insert invitaion code";
var errEmptyToolsTitle = "Please insert your Tools Title";
var errEmptyWebID = "Please select Website";
var errEmptyRegion = "Please select Region" ;
var errEmptystrNameTH= "Please insert your Thai name";
var errEmptystrLastNameTH= "Plase insert your Thai Lastname";
var errEmptystrNameEN= "Please insert your English name";
var errEmptystrLastNameEN= "Please insert your English lastname";
var errEmptystrNick= "Please insert your Nickname";
var errEmptyBirthday= "Please select your Birthday";
var errEmptystrHerbalifeID = "Please insert Herbalife ID";
var errEmptyAddress = "Please insert Address";
var errEmptyCity = "Please insert City";
var errEmptyProvince = "Please insert Province" ;
var errEmptyZipCode = "Please insert Zipcode" ;
var errEmptystrPhone = "Please insert Phone number";
var errEmptystrEmail = "Please insert your E-mail ";
var errEmptystrBankAcc = "Please insert Bank's Account";
var errEmptyMemberStatus = "Please select your Herbalife status";
var errEmptystrMySponsor = "Please insert Herbalife ID's sponser ";
var errEmptystrPass = "Please insert Password ";
var errEmptyType = "Please select Term Register ";
var errEmptyRadioNet = "Please select Term Thai Recruiting Service";
var errEmptyRadioInfo = "Please select Term Global Recruiting Service";
var errEmptyRadioDiet = "Please select Term Thai Retail Service";
//=============================================================================================
var errEmptyFirstNameTH = "กรุณากรอกชื่อของท่าน" ;
var errEmptyLastNameTH = "กรุณากรอกนามสกุลของท่าน" ;
var errEmptyNickNameTH = "กรุณากรอกชื่อเล่นของท่าน" ;
var errEmptyEmailAddressTH = "กรุณากรอกอีเมล์ของท่าน" ;
var errEmptyNationalityTH = "กรุณากรอกสัญชาติของท่าน" ;
var errEmptyAgeTH = "กรุณากรอกอายุของท่านและต้องเป็นตัวเลขเท่านั้น" ;
var errEmptyHeightTH = "กรุณากรอกส่วนสูงของท่านและต้องเป็นตัวเลขเท่านั้น" ;
var errEmptyWeightTH = "กรุณากรอกน้ำหนักของท่านและต้องเป็นตัวเลขเท่านั้น" ;
var errEmptyEducationTH = 'กรุณาเลือกระดับการศึกษาสูงสุดของท่าน' ;
var errEmptyProfessionTH = 'กรุณาเลือกวิชาชีพของท่าน' ;
var errEmptyAddressTH = "กรุณากรอกที่อยู่ของท่าน" ;
var errEmptyCityTH = "กรุณากรอกชื่ออำเภอของท่าน" ;
var errEmptyZipCodeTH = "กรุณากรอกรหัสไปรษณีย์ของท่าน" ;
var errEmptyProvinceTH = "กรุณากรอกชื่อจังหวัดของท่าน" ;
var errEmptyPhoneTH = "กรุณากรอกเบอร์โทรศัพท์ของท่าน" ;
var errEmptyFaxTH = "กรุณากรอกเบอร์แฟ็กของท่าน" ;
var errEmptyCodePhoneTH = "กรุณาเลือกรหัสเบอร์โทรศัพท์ของท่าน" ;
var errEmptyWhen_FromTH = "กรุณากรอกเวลาที่สะดวกให้เราติดต่อกับท่าน";
var errEmptyWhen_ToTH = "กรุณากรอกเวลาที่สะดวกให้เราติดต่อกับท่าน";
var errStartTime = "กรุณาเลือกเวลาที่จะติดต่อให้ถูกต้อง";
var errEmptyJobTH = " กรุณากรอกหน้าที่ของคุณในบริษัท";
var errEmptyIncomeTH = "กรุณาเลือกรายได้ที่ต้องการเพิ่มต่อเดือน ";
var errEmptyTime_HoursTH = "กรุณาเลือกเวลาว่างที่คุณมีต่อสัปดาห์ ";
var errEmptyMethodTH = "กรุณาเลือกสื่อที่คุณพบเว็ปไซต์ของเรา";
var errEmptyAdsTH = "กรุณาเลือกแหล่งที่ท่านพบโฆษณาของเรา";
var errEmptyWToPayDateTH = "กรุณาระบุวันกำหนดโอนเงิน";
var errEmptyWQ1TH ="กรุณาตอบแบบสอบถามข้อที่ 1";
var errEmptyWQ2TH ="กรุณาตอบแบบสอบถามข้อที่ 1 เพราะอะไร";
var errEmptyWQ3TH ="กรุณาตอบแบบสอบถามข้อที่ 2 มีธุรกิจหรือไม่";
var errEmptyWQ4TH ="กรุณาตอบแบบสอบถามข้อที่ 2";
var errEmptyWQ5TH ="กรุณาตอบแบบสอบถามข้อที่ 3";
var errEmptyWQ6TH ="กรุณาตอบแบบสอบถามข้อที่ 4";
var errEmptyWQ7TH ="กรุณาตอบแบบสอบถามข้อที่ 4 ได้หรือไม่ได้";
var errEmptyWQ8TH ="กรุณาตอบแบบสอบถามข้อที่ 5 เงินเดือน";
var errEmptyWQ9TH ="กรุณาตอบแบบสอบถามข้อที่ 5 เพราะว่า";
var errEmptyWQ10TH ="กรุณาตอบแบบสอบถามข้อที่  6";
var errEmptyWQ11TH ="กรุณาตอบแบบสอบถามข้อที่ 6 เพราะ";
var errEmptyWQ12TH ="กรุณาตอบแบบสอบถามข้อที่  7";
var errEmptyWQ13TH ="กรุณาตอบแบบสอบถามข้อที่ 8";
var errEmptyWQ14TH ="กรุณาตอบแบบสอบถามข้อที่ 9";
var errEmptyWQ15TH ="กรุณาตอบแบบสอบถามข้อที่ 9 ทุนไม่เกิน";
var errEmptyMemberIDTH ="กรุณากรอกรหัสสมาชิก";
var errEmptyPasswordTH ="กรุณากรอกรหัสผ่าน";
var errEmptyNumberTH="กรุณากรอกอักษรตัวตามที่เห็นในภาพ";
var errEmptyRePasswordTH ="กรุณากรอกรหัสผ่านอีกครั้ง";
var errEmptyMWReferNameTH="กรุณากรอกชื่ออ้างอิงสำหรับ recuit";
var errEmptyMSReferNameTH="กรุณากรอกชื่ออ้างอิงสำหรับ retail";
var errEmptyMUplineNameTH="กรุณากรอกชื่อผู้สนับสนุน";
var errEmptyMUplineIDTH="กรุณากรอก รหัสของผู้สนับสนุน";
var errEmptyMPositionTH ="กรุณาเลือกตำแหน่งปัจบันของท่าน";
var errEmptyBirthDateTH ="กรุณากรอกวันเดือนปีเกิดของผู้สมัคร";
//=========================================================================
var errEmptystrCamName  = "Please insert Name Campaign" ;
var errEmptystrCostCamNet  = "Please insert Price Thai Recruit" ;
var errEmptystrCostCamInfo  = "Please insert Price Inter Recruit" ;
var errEmptystrCostCamDiet  = "Please insert Price Thai Retail" ;
//var errEmptystrCostCamEN  = "กรุณากรอกราคา Inter Campaign" ;
//var errEmptystrCamMemo  = "กรุณากรอก Campaign Memo" ;
var errEmptystart  = "Please insert Start Campaign Date" ;
var errEmptyend  = "Please insert End Campaign Date" ;
var errEmptyamount  = "กรุณากรอกจำนวนวันรวม Campaign " ;
var errEmptystrNameChannel = "Please insert Channel Name" ;
var errEmptystrTitleChannel = "Please Insert Channel Title" ;
var errEmptystrChannel = "Please select Channel" ;
var errEmptystrStoryName = "Please Insert  Story Name" ;
var errEmptystrNewsTopic = "Please Insert  News Topic" ;
var errEmptystrNewsDetail = "Please Insert  News Detail" ;
var errEmptystrCatName = "Please Insert  Category Name" ;
var errEmptyCat = "Please select Caterogry" ;
var errEmptyFaqCat = "Please select Faq Caterogry" ;
var errEmptystrQuestion = "Please Insert  Question" ;
var errEmptystrAnswer = "Please Insert  Answer " ;
var errEmptyStatusTick = "Please select Status Ticket" ;
var errEmptystrListName = "Please Insert  List Name " ;
var errEmptystrListValue = "Please Insert  List Value " ;
var errEmptyUse = "Please select  Internet place" ;
var errEmptyGoal = "Please select business target at less 1 choise" ;
var errEmptystrSubject = "Please Insert  Subject" ;
var errEmptystrstrDescribe = "Please Insert  Description";
var errEmptyslotNet = "Please insert number Slot Thai Recruit and More than 0." ;
var errEmptyslotInfo = "Please insert number Slot Inter Recruit and More than 0." ;
var errEmptyslotDiet = "Please insert number Slot Thai Retail and More than 0 ." ;
/*var errEmptyBrowse = "กรุณาใส่ไฟล์ข้อมูลรูปของท่าน";*/

var errEmptyNet1 = "Please Insert Flee's Net for 3 months " ;
var errEmptyNet2 = "Please Insert Flee's Net for 6 months " ;
var errEmptyNet3 = "Please Insert Flee's Net for 12 months " ;
var errEmptyInfo1 = "Please Insert Flee's Info for 3 months " ;
var errEmptyInfo2 = "Please Insert Flee's Info for 6 months " ;
var errEmptyInfo3 = "Please Insert Flee's Info for 12 months " ;
var errEmptyDiet1 = "Please Insert Flee's Diet for 3 months " ;
var errEmptyDiet2 = "Please Insert Flee's Diet for 6 months " ;
var errEmptyDiet3 = "Please Insert Flee's Diet for 12 months " ;
var errEmptyUnit = "Please Insert Unit's money for this Country" ;

var errEmptyURL = "Please Insert URL ";
var errEmptyTitleLink = "Please Insert Title Link ";
var errEmptyDetailLink = "Please Insert Detail Link ";
var errEmptyWRequestInfo="Please select Information pack";
var errEmptyNameTo = "กรุณากรอกชื่อผู้รับ";
var errEmptyNameFrom = "กรุณากรอกชื่อผู้ส่ง";
var errEmptyEmailTo = "กรุณากรอกอีเมล์ผู้รับ";
var errEmptyEmailFrom = "กรุณากรอกอีเมล์ผู้ส่ง";
var errEmptyAcceptTH ="กรุณาเลือกเพื่อยอมรับความเข้าใจ";
var errNotSameEmailTH="อีเมล์ที่กรอกไม่เหมือนกัน";
var errEmptyRefCodeTH="กรุณากรอกชื่อโปรไฟล์ เป็นภาษาอังกฤษ";
var defaultEmptyOK = false ;
var iEmail = "อีเมล์ไม่ถูกต้อง, กรุณากรอกอีเมล์ใหม่" ;
var whitespace = " \t\n\r" ;
		
//================================= Function Validate Data Empty ===============================
function isEmpty(s)
{   
	return ((s == null) || (s.length == 0));
}
//================================ End Function Validate Data Empty ============================

//================================== Begin Function  isWhitespace ==============================
// Returns true if string s is empty or 
// whitespace characters only.
function isWhitespace(s)
{  
	 var i;
	
	 // Is s empty?
    if (isEmpty(s)) { return true; }

    for (i = 0; i < s.length; i++)
    {   
        // Check that current character isn't whitespace.
        var c = s.charAt(i);

        if (whitespace.indexOf(c) == -1) { return false ; }
    }

    // All characters are whitespace.
    return true;
}
//=================================== End Function  isWhitespace ==============================


//================================== Function Warn Empty Value ===============================
function warnEmpty(theField, sMsg) 
{
	   alert (sMsg);
	   theField.focus();
	    return;
}
//================================ End Function  Warn Empty Value =============================

//================================ Begin Function Warn Invalid Value ============================
function warnInvalid(theField, sMsg)
{   
	alert(sMsg);
	theField.focus();
    theField.select();
    return ;
}
//================================ End Function Warn Invalid Value ===============================

//============================== Begin Function checkString ===============================
function checkString(theField, sMsg, emptyOK)
{   // Next line is needed on NN3 to avoid "undefined is not a number" error
    // in equality comparison below.
    if (checkString.arguments.length == 2) { emptyOK = defaultEmptyOK ; }
    if ((emptyOK == true) && (isEmpty(theField.value))) { return true ; }
    if (isWhitespace(theField.value)) 
	{
		warnEmpty(theField, sMsg) ;
       return false;
    }
    else 
	{
		return true;
	}
}
//============================== End Function checkString        ===============================
//============================== Function Validate Check Email ===============================
function checkEmail(theField, sMsg, emptyOK)
{
		var A=0;
		var B=0;
		var P=999;
		 if (checkEmail.arguments.length < 2 ) 
		 { 
	 		emptyOK = defaultEmptyOK ;
	 	 }
		if (((emptyOK == false) && isEmpty(theField.value)) || isWhitespace(theField.value))
		{
			warnEmpty(theField, sMsg) ;
			return false ;
		}
		if (theField.value.length > 0)
		{	
			for (i=0;i<theField.value.length;i++)
			{
				//alert(document.addform.temail.value.charCodeAt(i));
				if(theField.value.substr(i,1)==" ")		//อีเมล์เป็นช่องว่าง spacebar
				{
					warnInvalid (theField, iEmail) ;
					return false;
				}// end if

				if( i==0 && theField.value.substr(i,1)=="@")		//อีเมล์ตัวแรกขึ้นต้นด้วย @
				{
					warnInvalid (theField, iEmail) ;
					return false;
				}// end if

				if( i==0  && theField.value.substr(i,1)==".")		//อีเมล์ตัวแรกขึ้นต้นด้วย .
				{
					warnInvalid (theField, iEmail) ;
					return false;
				}// end if
				
				if(theField.value.substr(i,1)=="@")
				{
					A = A+1;
					if(theField.value.substr(i+1,1) == "." || theField.value.substr(i-1,1) == ".")	// อีเมล์ที่มี . อยู่ติดกับ @
					{
						warnInvalid (theField, iEmail) ;
						return false;
					}// end if
				}// end if

				if(theField.value.substr(i,1)==".")
				{
					B=B+1;
				}// end if
				//alert(document.addform.temail.value.charCodeAt(i));
				if ((theField.value.charCodeAt(i)<48 || theField.value.charCodeAt(i)>57) && (theField.value.charCodeAt(i)<65 || theField.value.charCodeAt(i)>90)&&(theField.value.charCodeAt(i)<97 || theField.value.charCodeAt(i)>122))
				{		
					if (theField.value.charCodeAt(i) !=64 &&  theField.value.charCodeAt(i) !=46 && theField.value.charCodeAt(i) !=95 && theField.value.charCodeAt(i) !=45)
					{
						//alert(document.addform.temail.value.charCodeAt(i));
						warnInvalid (theField, iEmail) ;
						return false;
					}// end if
				}//end if
		  }// end for			
		  var pointPos = theField.value.indexOf(".");
		  var strChk ;
		  if( pointPos != "-1")
		  {
				strChk = theField.value.substr( (pointPos +1), theField.value.length);
				//alert(strChk.length);
				if(strChk.length < 1)
				{
					warnInvalid (theField, iEmail) ;
					return false;			
				}
		  }
		  if ( (A > 1) || (A < 1) || (B < 1) )
		  {
				warnInvalid (theField, iEmail);
				return false;			
		   }// end if
		   return true;
		}// end if
}
//=======================================================
function Validate_SMRegister(objForm)
{
	var dForm = document.forms[objForm.name] ;
	if (!checkString(dForm.SMFirstName, errEmptyFirstNameTH)) { return false ; }
	if (!checkString(dForm.SMLastName, errEmptyLastNameTH)) { return false ; }
	if (!checkString(dForm.SMNickName, errEmptyNickNameTH)) { return false ; }
	if (!checkAge(dForm.SMAge, errEmptyAgeTH, 13,false)) { return false ; }
	if (!checkString(dForm.SMBirthdate, errEmptyBirthDateTH)) { return false ; }
	if (!checkEmail(dForm.SMEmail, errEmptyEmailAddressTH)) { return false ; }
	if (!checkString(dForm.SMPassword, errEmptyPasswordTH)) { return false ; } //
	if (!checkString(dForm.SMProvince, errEmptyProvinceTH)) { return false ; }
	if (!checkString(dForm.SMPhone, errEmptyPhoneTH)) { return false ; }
	if (!checkString(dForm.SMRefCode, errEmptyRefCodeTH)) { return false ; }
/*	if ( dForm.Use[].disabled == false )
	{
		//if (!checkMultiCheckBoxFocus(objForm,'Use[]',errEmptyUse)) { return false ; }
	}	*/
	return true;
}
function Validate_SMUpdate(objForm)
{
	var dForm = document.forms[objForm.name] ;
	if (!checkString(dForm.SMFirstName, errEmptyFirstNameTH)) { return false ; }
	if (!checkString(dForm.SMLastName, errEmptyLastNameTH)) { return false ; }
	if (!checkString(dForm.SMNickName, errEmptyNickNameTH)) { return false ; }
	if (!checkAge(dForm.SMAge, errEmptyAgeTH, 13)) { return false ; }
	if (!checkString(dForm.SMBirthdate, errEmptyBirthDateTH)) { return false ; }
	if (!checkNumber(dForm.SMTall, errEmptyHeightTH)) { return false ; }
	if (!checkNumber(dForm.SMWeight, errEmptyWeightTH)) { return false ; }
	if (!checkEmail(dForm.SMEmail, errEmptyEmailAddressTH)) { return false ; }
	if (!checkString(dForm.SMProvince, errEmptyProvinceTH)) { return false ; }
	if (!checkString(dForm.SMPhone, errEmptyPhoneTH)) { return false ; }
/*	if ( dForm.Use[].disabled == false )
	{
		//if (!checkMultiCheckBoxFocus(objForm,'Use[]',errEmptyUse)) { return false ; }
	}	*/
	return true;
}
//======================= Function Validate Check Form frmQuote =========================
function Validate_WLRegister(objForm)
{
	var dForm = document.forms[objForm.name] ;
	if (!checkString(dForm.WLFirstName, errEmptyFirstNameTH)) { return false ; }
	if (!checkEmail(dForm.WLEmail, errEmptyEmailAddressTH)) { return false ; }
	if (!checkString(dForm.WLPassword, errEmptyPasswordTH)) { return false ; }
	
	if (!checkString(dForm.number, errEmptyNumberTH)) { return false ; }
/*
if ( dForm.AcceptTerm[].disabled == false )
	{
		
	}	
	//if (!checkMultiCheckBoxFocus(objForm,'AcceptTerm', errEmptyAcceptTH)) { return false ; }
	*/
	return true;
}

//====================================================================================
function Validate_Auto_Register_Lead(objForm)
{
	var dForm = document.forms[objForm.name] ;
	if (!checkString(dForm.WLFirstName, errEmptyFirstNameTH)) { return false ; }
	if (!checkString(dForm.WLLastName, errEmptyLastNameTH)) { return false ; }
	if (!checkEmail(dForm.WLEmail, errEmptyEmailAddressTH)) { return false ; }
	if (!checkEmail(dForm.WLReEmail, errEmptyEmailAddressTH)) { return false ; }
	if (dForm.WLEmail.value!=dForm.WLReEmail.value){
		warnEmpty(dForm.WLEmail,errNotSameEmailTH) ;
		return false;
	}
	if (!checkString(dForm.WLPhone, errEmptyPhoneTH)) { return false ; }
	if (!checkMultiCheckBoxFocus(objForm,'Accept', errEmptyAcceptTH)) { return false ; }
	
}
function Validate_FollowUp_Register(objForm)
{
	var dForm = document.forms[objForm.name] ;
//	if (!checkString(dForm.FNextDate,"Please enter date to pay")){return false ;}
	if (!checkString(dForm.FComment, "Please add comment")) { return false ; }
	
}
function Validate_InViteMail_Lead(objForm) // doesn't work 
{
	var dForm = document.forms[objForm.name] ;
    var number=dForm.NumEmails.options[dForm.NumEmails.selectedIndex].value;
	alert (number);
	for (i=1; i <= number; i++) {
		var dToFirstName='ToFirstName'+i;
		var dToLastName='ToLastName'+i;
		var dToEmail='ToEmail'+i;
		alert (dToFirstName);
		if (!checkString(dForm.ToFirstName+i, errEmptyFirstNameTH)) { return false ; }
		if (!checkString(dForm.ToLastName+i, errEmptyLastNameTH)) { return false ; }
		if (!checkEmail(dForm.ToEmail+i, errEmptyEmailAddressTH)) { return false ; }
	}
		
}

function Validate_Data_frmSendToFriend(objForm)
{
	var dForm = document.forms[objForm.name] ;
	//var Num = dForm.num.value ;
//	if (!checkSelectBox(dForm.WebID, errEmptyWebID)) { return false ; }
	if (!checkString(dForm.NameTo,errEmptyNameTo)) { return false ; }
	if (!checkEmail(dForm.EmailTo,errEmptyEmailTo)) { return false ; }
	if (!checkString(dForm.NameFrom, errEmptyNameFrom)) { return false ; }
	if (!checkEmail(dForm.EmailFrom, errEmptyEmailFrom)) { return false ; }

	return true ;
}
function SelectAll(id)
{
    document.getElementById(id).focus();
    document.getElementById(id).select();
}
function copyall(name){
	var tempval=document.getElementById(name);
	 document.getElementById(name).focus();
     document.getElementById(name).select();
	 therange = document.getElementById(name).createTextRange();
	 therange.execCommand("Copy");
}
/* common.js */
	// function to popup a window
		function NewWindow(mypage, myname, w, h, sscroll) 
		{
			var winl = (screen.width - w)/2;
			var wint = (screen.height - h)/2;
			winprops = 'height='+h+',width='+w+',top='+wint+',left='+winl+',scrollbars='+sscroll+',resizable';
			 win=window.open(mypage, myname, winprops);

			if (parseInt(navigator.appVersion) >= 4) { 
				win.window.focus(); 
			}//end if
		}// end of function
      // function  to swap color on mouse over table
		function chTdBg(tdID,oldcolor)
		{ 

			if (document.getElementById(tdID).bgColor== oldcolor){
					document.getElementById(tdID).bgColor= "#003366";
			}
			else{
				document.getElementById(tdID).bgColor = oldcolor;
			}// end if
		}// end function

function getWeek(year,month,day){
    //lets calc weeknumber the cruel and hard way :D
    //Find JulianDay 
    month += 1; //use 1-12
    var a = Math.floor((14-(month))/12);
    var y = year+4800-a;
    var m = (month)+(12*a)-3;
    var jd = day + Math.floor(((153*m)+2)/5) + 
                 (365*y) + Math.floor(y/4) - Math.floor(y/100) + 
                 Math.floor(y/400) - 32045;      // (gregorian calendar)
    //var jd = (day+1)+Math.Round(((153*m)+2)/5)+(365+y) + 
    //                 Math.round(y/4)-32083;    // (julian calendar)
    
    //now calc weeknumber according to JD
    var d4 = (jd+31741-(jd%7))%146097%36524%1461;
    var L = Math.floor(d4/1460);
    var d1 = ((d4-L)%365)+L;
    NumberOfWeek = Math.floor(d1/7) + 1;
    return NumberOfWeek;        
}
//=====================================================================================================
function CheckKeypressAcceptDateValueOnly(e)
{
	//alert(event.keyCode);
	if (e.keyCode < 47 || e.keyCode > 57)
	{
		e.returnValue = false;
		alert("คุณสามารถกรอกข้อมูลเป็นตัวเลขตั้งแต่ 0-9 และ '/' เท่านั้น  เช่น \"2005/08/01\"");
		//alert("Please enter ( 0-9 and '/' ) only.");
	}
}
function calculateRangeDate( strStartDate,  objTarget )
{
	//alert(strStartDate.value);
	//alert(strEndDate.value);
	strEndDate.value = "2007/12/31";
	if ( strStartDate.value != "" && strEndDate.value != "" )
	{
		var strSDate = new String(strStartDate.value) ;
		var strEDate =new String(strEndDate.value) ;

		if( ( strStartDate.value.length < 3 ) && ( strEndDate.value.length < 3 ) )
		{
			totalDays = "" ;
			if (objTarget.value == "" )
			{
				objTarget.value =  totalDays ;
			}
			return ;
		}

		var arr_startdate = strSDate.split('/');
		var arr_enddate = strEDate.split('/');
		
		if ( ( arr_startdate.length != 3 ) && ( arr_enddate.length != 3 ) )
		{
			totalDays = "" ;
			if (objTarget.value == "" )
			{
				objTarget.value =  totalDays ;
			}
			return ;
		}
		
		var sDate = arr_startdate[1] + "/" + arr_startdate[2] + "/" + arr_startdate[0]
		var eDate =arr_enddate[1] + "/" + arr_enddate[2] + "/" + arr_enddate[0]
		var startDate = new  Date(sDate) ;
		var endDate = new  Date(eDate) ;
		var millisecondPerDay = 86400000 ;
		var diffDate, resultDiffDate, totalDays, intPosPoint ;
		//alert( strStartDate + " ==> " + strEndDate ) ;
		//alert( startDate + " ==> " + endDate ) ;
		diffDate = endDate - startDate    //difference in milliseconds
		iResultDiffDate  = diffDate/millisecondPerDay//calculate days 
		//alert( "  ==> " + iResultDiffDate ) ;
		if( iResultDiffDate >= 0 )
		{
			iResultDiffDate = iResultDiffDate + 1 ;
		}
		resultDiffDate = new String(iResultDiffDate)  ;  // convert number to string
		//alert( "  ==> " + resultDiffDate ) ;
		intPosPoint = resultDiffDate.indexOf(".") ;   //find the decimal point
	    point = new String(intPosPoint)  ;
		//alert( " Position Point ==> '" + intPosPoint + "'" ) ;
		if( intPosPoint != -1 )
		{
			totalDays = resultDiffDate.substring(0,intPosPoint)  ; //get just the whole days
			//alert( "1 Total  Days ==> " + totalDays ) ;
		}
		else
		{
			totalDays = resultDiffDate
			//alert( "2 Total  Days ==> " + totalDays ) ;
		}

		if(isNaN(totalDays))
		{
			if (objTarget.value == "" )
			{
				totalDays = "" ;
			}
			else
			{
				totalDays = objTarget.value ;
			}
		}
	}
	else
	{
		if (objTarget.value == "" )
		{
			totalDays = "" ;
		}
		else
		{
			totalDays = objTarget.value ;
		}
	}
	objTarget.value =  totalDays ;
	//alert( "Total  Days ==> " + totalDays ) ;
	return ;
}
//=====================================================================================================
function toggleCheckBoxes(formName)   {
// toggle Check Boxes using Prototype Library
	var form=$(formName);
	var i=form.getElements('checkbox');
	i.each(function(item)
		{
		if (item.checked){
			item.checked=false;
		}
		else {
			item.checked=true;
		}
		}
	);
} 

function checkPersonalID(id) {
	if(id.length != 13) return false;
	for(i=0, sum=0; i < 12; i++)
	sum += parseFloat(id.charAt(i))*(13-i);
	if((11-sum%11)%10!=parseFloat(id.charAt(12))) return false;
	return true;
	}
	function checkForm() {
	if(!checkID(document.form1.txtID.value))
	alert('ผมรู้นะ...ว่าคุณมั่ว');
	else
	alert('ถูกต้องงงงงง');
}

/* end of commond.js */


/* menudown.js */
var winprops = "height=500,width=500,location=no,scrollbars=no,"
             + "menubars=no,toolbars=no,resizable=yes";
var visMnu = "";
var actMnu, url, msOver;

function menuHandler(actMnu,url)
{
   popup = window.open("http://"+url,"MenuPopup",winprops);
   hideMenu(actMnu);
   popup.focus()
}
function changeBg(actMnu,msOver)
{
	if(msOver==true)
	{
		//actMnu.style.background="#DBEAF5";
		actMnu.style.color="#00FFFF";

	}
	else 
	{
		//actMnu.style.background="#3366CC";
		actMnu.style.color="#FFFFFF";
	}
			
}

function flipMenu(actMnu)
{
   if ( actMnu.style.display == "none")
   {
   		showMenu(actMnu);
   }
   else
   {
	    hideMenu(actMnu);
   }
   /*
   {
      if (visMnu == actMnu)
         hideMenu(actMnu);
      else
      {
        // hideMenu(visMnu);
         showMenu(actMnu);
      }
   }*/
}
function showMenu(actMnu)
{
   //actMnu.style.background = "#FFFFFF"; /* modify menu-background-color */
   actMnu.style.display = "block";
   visMnu = actMnu;
}
function hideMenu(actMnu)
{
   //actMnu.style.background = ""; /* modify color "selected" */
   actMnu.style.display = "none";
   visMnu = "";
}
/* end of menudown.js ********************************/


/* jQuery version ---------------------------------------*/
// JavaScript Document
(function( $, undefined ) {

$.fn.fbmenu = function(usr){

    if (typeof usr != 'object') {
        var options = {
            submenuClass: 'fb-simple-class',
            selectedClass: 'selected',
            left: false,
            zIndex: 1000
        };
    } else {
        var options = usr;
    }
    //Fixed, used for closing system
    options.fixedClass = 'fb-class-fixed';
    options.fixedSelectedClass = 'fb-selected-class-fixed';

    var a = function(elem, options){
        elem.find('ul').attr('style', 'display:none');

        var closeOpenedMenu = function() {
            $('.'+options.fixedClass).remove();
            $('li.'+options.fixedSelectedClass).removeClass(options.selectedClass);
        };

        elem.find('a').click(function(event){
            var s = $(this).parent().find('ul');

            if (s.length > 0) {
                event.preventDefault();
            }
        });

        elem.children('li').click(function(event){

            closeOpenedMenu();

            event.stopImmediatePropagation();	//Stop event propagation

            var submenu = $(this).children('ul').clone();
            submenu.addClass(options.submenuClass); //For remove system
            submenu.addClass(options.fixedClass);
            $('body').append(submenu);

            var li = $(this);

            if (submenu.size() > 0) {

                li.addClass(options.selectedClass);
                li.addClass(options.fixedSelectedClass);

                var left = li.offset().left;
                if (!options.left) {
                    left += li.outerWidth() - submenu.outerWidth();
                } else {

                }

                var top = li.offset().top;

                submenu.attr(
                    'style',
                    'position: absolute;'+
                    'z-index: ' + options.zIndex + ';'+
                    'left: '+ left +'px; '+
                    'top: ' + (top + li.outerHeight()) + 'px;'
                );

                $('body').click(function(){
                    closeOpenedMenu();
                    $('body').unbind('click');
                });
            }
        });
    };
    a($(this), options);
}

})(jQuery);
		 function doUpdate(target, executefile,waitbar)
		 {
				
				divtag ='#'+ target;
				if (target=='subinfomain')waitbar='submenu_loading';
				if (target=='syssetup')waitbar='subd_loading';
			    if (target=='subbiz')waitbar='subbiz_loading';
				if (target=='infomain')waitbar='infomain_loading';
				if (target=='fullview')waitbar='progress';
				if (! waitbar) waitbar=target;
				var url = executefile + '&divtarget='+target;

			   if (target=='infomain') $.history.load('!'+executefile + '&divtarget='+ target); 
			    if (target=='fullview') $.history.load('!'+executefile + '&divtarget='+ target); 
				$("#"+waitbar+"").show();
				$("#"+waitbar+"").html('<img src="/images/icons/loading.gif"  height="16"/>');
					$.ajax( {
					  url: executefile,
					  success: function(r) {
							$("#"+waitbar+"").html('');
							//$("#"+waitbar+"").hide();
							$('#'+target+"").html( r );
							//location.reload( true );
							//$(document).ready(function(){
							Cufon.replace('.title, .headerblackfont1,.headerredfont1,.topic1font,.headerwhitefont1,.button'); 
							Cufon.replace('#menu ul li a', {hover: true,	hoverables:{ strong: true, em: true,a:true }});
							Cufon.replace('.post-bt', {hover: true,	hoverables:{ strong: true, em: true,a:true }});
							Cufon.replace('.bt', {hover: true,hoverables:{ strong: true, em:true,a:true }});
							Cufon.now(); 
					
					   }
				  });
		  				
		 }			

		  function doSimpleLoad(target, executefile,waitbar)
		 {
				divtag ='#'+ target;
				//$("#"+target+"").empty().html('<img src="/images/icons/loading.gif" />');
				$("#"+target+"").load(""+executefile+"");
				
		 }	
		 $(document).ready(function() {
				function loadpage(executefile,target) {
					
					divtag ='#'+ target;
					if (target=='subinfomain')waitbar='submenu_loading';
					if (target=='syssetup')waitbar='subd_loading';
					if (target=='subbiz')waitbar='subbiz_loading';
					if (target=='infomain')waitbar='infomain_loading';
					if (target=='fullview')waitbar='progress';
					if (! waitbar) waitbar=target;
					var url = executefile + '&divtarget='+target;
					$("#"+waitbar+"").show();
					$("#"+waitbar+"").html('<img src="/images/icons/loading.gif"  height="16"/>');
						$.ajax( {
						  url: executefile,
						  success: function(r) {
								$("#"+waitbar+"").html('');
								//$("#"+waitbar+"").hide();
								$('#'+target+"").html( r );
								//location.reload( true );
								//$(document).ready(function(){
								Cufon.replace('.title, .headerblackfont1,.headerredfont1,.topic1font,.headerwhitefont1'); 
								Cufon.replace('#menu ul li a', {hover: true,	hoverables:{ strong: true, em: true,a:true }});
								Cufon.replace('.post-bt', {hover: true,	hoverables:{ strong: true, em: true,a:true }});
								Cufon.replace('.bt', {hover: true,hoverables:{ strong: true, em:true,a:true }});
								Cufon.now(); 
								 //Cufon.refresh();
								//});
								//return false;
								
						   }
					  });

				}	
				
				$.history.init(function(url) {
						//url= unescape(url);				  
					   //alert (target);					
					    url1 =url.replace(/^.*#/, '');
						$.history.load(url1);		
					    if (url !=''){   //url ="/myprofile.php?sid=<? echo $sid;?>&mode=mprofile&divtarget=infomain"; 
							var target =url.replace(/^.*divtarget=/, '');
							url = url.replace(/^.*!/, '');
							loadpage(url,target);
						}
						//else{
							//urlrefresh = '!/myprofile.php<? echo $_SERVER['REQUEST_URI'];?>&divtarget=infomain'
							// $.history.load(urlrefresh);	

					  //}
		
					},{unescape: true  });
				// urlrefresh = '<? echo $_SERVER['REQUEST_URI'];?>'
		        // $.history.load(urlrefresh);	
				

		  });
		function doUpdateList(target, executefile,waitbar)
		 {
				divtag ='#'+ target;
				//$("#"+target+"").html('<img src="/images/icons/loading.gif" />');
				if (! waitbar) waitbar=target;
				$("#"+waitbar+"").show();
				$("#"+waitbar+"").html('<img src="/images/icons/loading.gif"  height="16"/>');
				$.ajax( {
					  url: executefile,
					  success: function(r) {
							$("#"+waitbar+"").hide();
							$('#'+target+"").fadeIn(100);
							$('#'+target+"").html( r );
							
					   }
				  });
				  

				function runEffect() {
					// get effect type from 
					var selectedEffect = "slide";
					
					// most effect types need no options passed by default
					var options = {};
					// some effects have required parameters
		 
					// run the effect
					$( "#" +target+"").effect( selectedEffect, options, 500, callback );
				};
				
				function callback() {
						setTimeout(function() {
							$( "#"+target+"" ).removeAttr( "style" ).hide().fadeIn();
						}, 1000 );
				};			
				// set effect from select menu value
				//runEffect();
	
		 }	

		 function doPeriodicalUpdate(target, executefile,freq)
		 {
				divtag ='#'+ target;
				
				 $.PeriodicalUpdater({
					  url : ""+executefile+""
				   },
				   function(data){				 
					  $("#"+target+"").append(data);
				   });
				//$("#"+target+"").load(""+executefile+"");		
				 // new Effect.Squish (target);
				// new Effect.Shrink (target);
				 //new Effect.Grow(target);

		 }
		 
		function doPost(target,formname, executefile,waitbar)
		 {
			 	if (tinyMCE){
			 		tinyMCE.triggerSave(false,true);
				}
				dataString = $('#'+formname).serialize();
				//$("#"+target+"").empty().html('<img src="/images/icons/loading.gif" />');
				divtag ='#'+ target;
				if (waitbar==''){ // does not assigned waitbar
					if (target=='subinfomain')waitbar='submenu_loading';
					else if (target=='syssetup')waitbar='subd_loading';
					else if (target=='subbiz')waitbar='subbiz_loading';
					else if (target=='infomain')waitbar='infomain_loading';
					else if (target=='fullview')waitbar='progress';
					else  waitbar=target;
				}
				$("#"+waitbar+"").show();
				$("#"+waitbar+"").html('<img src="/images/icons/loading.gif"  height="16"/>');
				$.ajax( {
						  type: 'post',
						  url: executefile,
						  data: dataString,
						  success: function( r ) {
								$('#'+target).html( r );
								//location.reload( true );
								Cufon.replace('h1,h2,h3,.title,  .headerblackfont1,.topic1font,.bt'); 
								Cufon.replace('#menu ul li a', {hover: true,	hoverables:{ strong: true, em: true,a:true }});
								//Cufon.replace('#mymenu ul li a', {hover: true,	hoverables:{ strong: true, em: true,a:true }});
								Cufon.replace('.post-bt' , {hover: true,	hoverables:{ strong: true, em: true,a:true }});
								Cufon.replace('.bt' , {hover: true,hoverables:{strong: true, em: true,a:true }});
								//Cufon.now(); 
								
						 }
				});
				$('#'+formname).reset();
				return false;	
		 }


		function submitMsgAjax (target,formname, executefile, waitbar)
		{
			dataString = $('#'+formname).serialize();
			//$("#"+target+"").empty().html('<img src="/images/icons/loading.gif" />');
			divtag ='#'+ target;
			if (waitbar==''){ // does not assigned waitbar
				if (target=='subinfomain')waitbar='submenu_loading';
				else if (target=='syssetup')waitbar='subd_loading';
				else if (target=='subbiz')waitbar='subbiz_loading';
				else if (target=='infomain')waitbar='infomain_loading';
				else if (target=='fullview')waitbar='progress';
				else  waitbar=target;
			}
			$("#"+waitbar+"").show();
			$("#"+waitbar+"").html('<img src="/images/icons/loading.gif"  height="16"/>');
			$.ajax( {
					  type: 'post',
					  url: executefile,
					  data: dataString,
					  success: function( r ) {
							$('#'+target).html( r );
							//location.reload( true );
							Cufon.replace('h1,h2,h3,.title,  .headerblackfont1,.topic1font,.bt'); 
							Cufon.replace('#menu ul li a', {hover: true,	hoverables:{ strong: true, em: true,a:true }});
							//Cufon.replace('#mymenu ul li a', {hover: true,	hoverables:{ strong: true, em: true,a:true }});
							Cufon.replace('.post-bt' , {hover: true,	hoverables:{ strong: true, em: true,a:true }});
							Cufon.replace('.bt' , {hover: true,hoverables:{strong: true, em: true,a:true }});
							//Cufon.now(); 
							
					 }
			});
			$('#'+formname).reset();
			return false;	
		}// end of funtin	

 /*----------------------------------- tooltip.js -----------------------------*/
 var Xmouse, Ymouse;
var hidden = true;
var preMessage="<table border=0 cellspacing=1 cellpadding=4 bgcolor='#666666'><tr><td bgcolor='#ffffff'><font color='#555555'>";
var postMessage="</font></td></tr></table>";
function tooltip(message) {
	if(message){
		window.status = message;
		hidden = false;
		if (document.layers){
			with (document["tooltip"].document){
				open();
				write(preMessage + message + postMessage);
				close();
			}
		} else if (document.all) {
			document.all["tooltip"].innerHTML = preMessage + message + postMessage;
		} else if (document.getElementById){
			jxdocrange = document.createRange();
			jxdocrange.setStartBefore(document.getElementById("tooltip"));
			while (document.getElementById("tooltip").hasChildNodes()){
				document.getElementById("tooltip").removeChild(document.getElementById("tooltip").lastChild);
			}
			document.getElementById("tooltip").appendChild(jxdocrange.createContextualFragment(preMessage + message + postMessage));
		}
		if (document.all) {
			document.all["tooltip"].style.visibility = "visible";
		} else if (document.layers){
			document.layers["tooltip"].visibility = "show";
		} else if (document.getElementById){
			document.getElementById("tooltip").style.visibility = "visible";
		}
		document.onmousemove = MoveHandler;
	} else {
		hidden = true;
		if (document.all) {
			document.all["tooltip"].style.visibility = "hidden";
		} else if (document.layers){
			document.layers["tooltip"].visibility = "hide";
		} else if (document.getElementById){
			document.getElementById("tooltip").style.visibility = "hidden";
		}
		message = "";
		if (document.layers){
			with (document["tooltip"].document){
				open();
				write(preMessage + message + postMessage);
				close();
			}
		} else if (document.all) {
			document.all["tooltip"].innerHTML = preMessage + message + postMessage;
		} else if (document.getElementById){
			jxdocrange = document.createRange();
			jxdocrange.setStartBefore(document.getElementById("tooltip"));
			while (document.getElementById("tooltip").hasChildNodes()){
				document.getElementById("tooltip").removeChild(document.getElementById("tooltip").lastChild);
			}
			document.getElementById("tooltip").appendChild(jxdocrange.createContextualFragment(preMessage + message + postMessage));
		}
		window.status = "";
		document.onmousemove=''
	}
	return(true);
}
function MoveHandler(evnt) {
	if(document.all) {
		Xmouse = window.event.clientX + document.body.scrollLeft;
		Ymouse = window.event.clientY + document.body.scrollTop;
	} else if(document.layers||document.getElementById){
		Xmouse = evnt.pageX;
		Ymouse = evnt.pageY;
	}
	moveLayer("tooltip",Xmouse-30,Ymouse+20);
}
function moveLayer(Id,x,y){
	if (document.all){
		document.all[Id].style.left = x;
		document.all[Id].style.top = y;
	} else if (document.layers){
		document.layers[Id].left = x;
		document.layers[Id].top = y;
	} else if (document.getElementById){
		document.getElementById(Id).style.left = x+'px';
		document.getElementById(Id).style.top = y+'px';
	}
}
if (document.layers){
	document.captureEvents(Event.MOUSEMOVE);
}

/* ---------------------------end of tooltip ----------------------*/


    function grayscaleImageIE(imgObj)
    {
        imgObj.style.filter = 'progid:DXImageTransform.Microsoft.BasicImage(grayScale=1)';
    }

    function grayscaleImage(img)
    {
        var canvas = document.createElement('canvas');
        var canvasContext = canvas.getContext('2d');
        var imgObj = new Image();
   		 	imgObj.src = img;
        var imgW = imgObj.width;
        var imgH =  imgObj.height;
        canvas.width = imgW; 
        canvas.height = imgH;
        
        canvasContext.drawImage(imgObj, 0, 0);
        var imgPixels = canvasContext.getImageData(0, 0, imgW, imgH);
        
        for(var y = 0; y < imgPixels.height; y++){
            for(var x = 0; x < imgPixels.width; x++){
                var i = (y * 4) * imgPixels.width + x * 4;
                var avg = (imgPixels.data[i] + imgPixels.data[i + 1] + imgPixels.data[i + 2]) / 3;
                imgPixels.data[i] = avg; 
                imgPixels.data[i + 1] = avg; 
                imgPixels.data[i + 2] = avg;
            }
        }
        
        canvasContext.putImageData(imgPixels, 0, 0, 0, 0, imgPixels.width ,imgPixels.height );
        return canvas.toDataURL();
    }
function streamPublish(name, description, hrefTitle, hrefLink, userPrompt){  		
		FB.ui({ method : 'feed', 
				message: userPrompt,
				link   :  hrefLink,
				source: 'http://www.youtube.com/v/8vgnZpRr9ss&rel=0&disablekb=1&autoplay=1&showinfo=0',
				caption:  hrefTitle,
				description: description,
				picture: 'http://www.epayfriend.com/images/business-social-networking.jpg'
	    });
	}// end of function
	function publishStream(slink){
		streamPublish("TestdriveEpayfriend", '<--ชมคลิบเปิดตัว เรียนเชิญทดลอง Testdrive ระบบสร้างรายได้ผ่าน facebook ฟรี', 'กำลังฟอร์มทีมเปิดต้นสายด้วย EpayFaceApp ', slink, '' );
	}// end of function
     function quietPublishStream(slink){
		 FB.ui({ method : 'feed', 
				message: "ข่าวดีการตลาดยุคใหม่ให้โอกาสทุกคนทำเงิน ง่ายจากเครือข่ายสังคม",
				link   :  slink,
				source: 'http://www.youtube.com/v/8vgnZpRr9ss&rel=0&disablekb=1&autoplay=1&showinfo=0',
				caption:  "TestdriveEpayfriend",
				description: '<--ชมคลิบเปิดตัว เรียนเชิญทดลอง Testdrive ระบบสร้างรายได้ผ่าน facebook ฟรี',
				picture: 'http://www.epayfriend.com/images/business-social-networking.jpg'
	    });
	}// end of function
		 //http://developers.facebook.com/docs/reference/dialogs/requests/
	function newInvite(){
		 var receiverUserIds = FB.ui({ 
				method : 'apprequests',
				//filters: ['app_non_users'],
				message: 'เรียนเชิญ ทดลองระบบ epayfriend ระบบสร้างเพื่อนสร้างรายได้ atomic social marketing'
		       },
		       function(response) {
				  console.log("IDS : " + response.request_ids);
				   //alert(receiverUserIds.request_ids);
				   if (response && response.request_ids) {
					 /*
					 var requests = response.request_ids.join(',');
					   $.post('facebook/fbapp_handle_requests.php',{
							  uid: <?php echo $fbuid; ?>, 
							  request_ids: requests
						},function(resp) {});
					   */
				   } 
		       }		 
			  );
	  }// end of function
	 function FacebookLogin2(nextload){		 
		 FB.login(function(response) {
			   if (response.authResponse) {
				 console.log('Welcome!  Fetching your information.... ');
				 FB.api('/me', function(response) {
				   console.log('Good to see you, ' + response.name + '.');
				   FB.logout(function(response) {
					 console.log('Logged out.');
				   });
				 });
				 window.location = '/fb_leadregister_do.php?' + nextload;
			   } else {
				 console.log('User cancelled login or did not fully authorize.');
			   }
			 }, {scope: 'publish_stream,offline_access,user_status,read_stream,user_birthday,user_hometown,email'});
			
	 }	// end of function FacebookLogin		
	function FacebookLogin(nextload,appid) {
				//env_executeCommand("SECURE_LOGIN_REQUEST");
				var path = 'http://www.facebook.com/dialog/oauth/?';
				var queryParams = ['response_type=token','client_id=125310340876622', 'redirect_uri=http://www.epayfriend.com/fb_leadregister_do.php?' + nextload +'', 'scope=publish_stream,offline_access,user_status,read_stream,user_birthday,email', 'display=popup'];
				var query = queryParams.join('&');
				var url = path + query;
				top.location = url;
				//popup(url);
	}
	function popup(url, winname, width, height) {
			if (winname == '') winname = 'fblc';
			if (!width) width = 580;
			if (!height) height = 400;
			var left = (screen.width/2)-(width/2);
			var top = (screen.height/2)-(height/2);
			var win_arg = 'scrollbars=no,status=no,resizable=yes,location=no,toolbar=no,width=' + width + 'px,height=' + height + 'px,top=' + top + 'px,left=' + left+'px;';
			window.open(url,winname,win_arg);
   }
