// เลือกทั้งหมด ใน CheckBoxList
function CheckBoxListSelect(cbControl, state)
{    
    var chkBoxList = document.getElementById(cbControl);
    var chkBoxCount= cbControl.getElementsByTagName("input");
    for(var i=0;i<chkBoxCount.length;i++) 
    {
        chkBoxCount[i].checked = state;
    }
    return false; 
}
function CheckBoxListSelect(cbControl, state, txtArea, txtall)
{    
    var chkBoxCount= cbControl.getElementsByTagName("input");
    for(var i=0;i<chkBoxCount.length;i++) 
    {
        chkBoxCount[i].checked = state;
    }
    if(state)
    {
        txtArea.value = txtall.value;
    }
    else
    {
        txtArea.value = '';
    }
    return false; 
}
function CheckBoxListSelectNull(cbControl, state, txtArea, txtall)
{    
    var chkBoxCount= cbControl.getElementsByTagName("input");
    for(var i=0;i<chkBoxCount.length;i++) 
    {
        chkBoxCount[i].checked = state;
    }
    if(state)
    {
        txtArea.value = txtall.value;
    }
    else
    {
        txtArea.value = 'null';
    }
    return false; 
}
// Manage Span
function InsertKeyw(spanID, txtall, txtsel, txtinput, msgalert, msgsame, msgsameall, rmsg, cfmsg)
{
    if(txtinput.value.trim() == '') {alert(msgalert); return false;} 
    var sinput = "";
    if(txtinput.value.indexOf(",") == -1)
    {
        if(txtsel.value.indexOf(txtinput.value + ", ") != -1) {alert(msgsame); return false; } else
        if(txtall.value.indexOf(txtinput.value + ", ") != -1) {if(!confirm(msgsameall)) {return false}; }
        sinput = txtinput.value;
    }
    else
    {
        var arkeyw = txtinput.value.split(',');
        for(var i = 0; i < arkeyw.length; i++)
        {
            if(arkeyw[i].trim() == "") continue;
            if(txtsel.value.indexOf(arkeyw[i].trim() + ", ") != -1) {alert(msgsame); continue; } else
            if(txtall.value.indexOf(arkeyw[i].trim() + ", ") != -1) {if(!confirm(msgsameall)) {continue}; }
            sinput += ", " + arkeyw[i].trim();
        }
        if(sinput != "") sinput = sinput.substring(2, sinput.length);
    }
    
    // เพิ่มของแต่ละอัน(paper)
    replaceText(sinput, txtsel);
    // เพิ่มทั้งหมด(docuent)
    replaceText(sinput, txtall);
    //
    OpenKeyw(spanID, txtall, txtsel, rmsg, cfmsg);
    // clear input & set focus
    txtinput.value = '';
    txtinput.focus();
}
function RemoveKeyw(spanID, txtall, txtsel, msg, rmsg, cfmsg)
{
    txtsel.value = txtsel.value.replace(msg + ", ", "");
    txtall.value = txtall.value.replace(msg + ", ", "");
    OpenKeyw(spanID, txtall, txtsel, rmsg, cfmsg);
}
function RemoveAllKeyw(txtall, txtsel)
{
    var arkeyw = txtsel.value.split(',');
    for(var i = 0; i < arkeyw.length; i++)
    {
        if(arkeyw[i].trim() == '') continue;
        txtsel.value = txtsel.value.replace(arkeyw[i].trim() + ", ", "");
        txtall.value = txtall.value.replace(arkeyw[i].trim() + ", ", "");
    }
}
function OpenKeyw(spanID, txtall, txtsel, rmsg, cfmsg)
{
    spanID.innerHTML = '';
    var arkeyw = txtsel.value.split(',');
    for(var i = 0; i < arkeyw.length; i++)
    {
        if(arkeyw[i].trim() == '') continue;
        spanID.innerHTML += "<a onclick=\"if(confirm('" + cfmsg + "')){RemoveKeyw(" + spanID.id + ", " + txtall.id + ", " + txtsel.id + ", '" + arkeyw[i].trim() + "', '" + rmsg + "', '" + cfmsg + "');}\" style='cursor:hand'><img src='images/del.gif' alt='" + rmsg + "' width='12' height='12' border='0'></a> " + (i + 1) + ". " + arkeyw[i].trim() + "<br />";
    }
}
// 
function CheckAll(cbControl)
{ 
    var ic = true;
    var chkBoxCount = cbControl.getElementsByTagName("input");
    for(var i = 0; i < chkBoxCount.length; i++) 
    {
        if (chkBoxCount[i].checked) continue;
        ic = false; break;
    }
    return ic;
}
function CheckDefaultOfSelect(cbControl, txtsel, chkall, imode)
{ 
    var chkBoxCount = cbControl.getElementsByTagName("input");
    if(txtsel.value == "00, " || (imode.value == "add" && txtsel.value == "")) //
    {
        chkall.checked = true;
        txtsel.value = "";
        for(var i = 0; i < chkBoxCount.length; i++) 
        {
            chkBoxCount[i].checked = true;
            txtsel.value += chkBoxCount[i].parentNode.alt + ", ";
        }
    }
    else
    {
        var c = 0;
        for(var i = 0; i < chkBoxCount.length; i++) 
        {
            if (txtsel.value.indexOf(chkBoxCount[i].parentNode.alt + ", ") != -1)
            {
                chkBoxCount[i].checked = true; c++;
            }
            else
            {
                chkBoxCount[i].checked = false;
                chkall.checked = false;
            }
        }
        chkall.checked = (chkBoxCount.length == c);
    }
}
function SelectAddTextArea(chkVal, idVal, txtArea, txtValue) 
{ 
    var frm = document.forms[0];
    // Loop through all elements
    for (i=0; i<frm.length; i++) 
    {
        //if elements is them RadioButtonList not access scope if
        if(frm.elements[i].id == idVal && frm.elements[i].disabled == false)
        {
            // Check if main checkbox is checked, then select or deselect datagrid checkboxes 
            frm.elements[i].checked = chkVal;
            if(chkVal == true) 
            {
                if(txtArea.value.indexOf(txtValue + ", ") == -1)
                {
                    replaceText(txtValue, txtArea);
                }
            } 
            else 
            {
                if(txtArea.value.indexOf(txtValue + ", ") != -1)
                {
                    txtArea.value = txtArea.value.replace(txtValue + ", ", "");
                }
            }
            // Work here with the Item Template's multiple checkboxes
        }
    }
    return false; 
}
function SelectAddTextAreaNull(chkVal, idVal, txtArea, txtValue) 
{ 
    var frm = document.forms[0];
    if(txtArea.value == "null") txtArea.value = "";
    // Loop through all elements
    for (i=0; i<frm.length; i++) 
    {
        //if elements is them RadioButtonList not access scope if
        if(frm.elements[i].id == idVal && frm.elements[i].disabled == false)
        {
            // Check if main checkbox is checked, then select or deselect datagrid checkboxes 
            frm.elements[i].checked = chkVal;
            if(chkVal == true) 
            {
                if(txtArea.value.indexOf(txtValue + ", ") == -1)
                {
                    replaceText(txtValue, txtArea);
                }
            } 
            else 
            {
                if(txtArea.value.indexOf(txtValue + ", ") != -1)
                {
                    txtArea.value = txtArea.value.replace(txtValue + ", ", "");
                }
            }
            // Work here with the Item Template's multiple checkboxes
        }
    }
    if(txtArea.value == "") txtArea.value = "null";
    return false; 
}
// Replaces the currently selected text with the passed text.
function replaceText(text, textarea)
{
	// Attempt to create a text range (IE).
	if (textarea.createTextRange && typeof(textarea.caretPos) != "undefined")
	{
		var caretPos = textarea.caretPos;

		caretPos.text = caretPos.text.charAt(caretPos.text.length - 1) == ' ' ? text + ' ' : text;
		caretPos.select();
	}
	// Mozilla text range replace.
	else if (typeof textarea.selectionStart != 'undefined')
	{
		var begin = textarea.value.substr(0, textarea.selectionStart);
		var end = textarea.value.substr(textarea.selectionEnd);
		var savescrollTop=0;
		var newCursorPos=begin.length + text.length;

		// Save scrollTop of TextArea
		if (typeof textarea.scrollTop !='undefined') {
			savescrollTop = textarea.scrollTop;
		}
		textarea.value = begin + text + end;

		if (textarea.setSelectionRange)
		{
			textarea.focus();
			if (typeof textarea.scrollTop !='undefined') {
				// Restore scrollTop of TextArea
				textarea.scrollTop = savescrollTop;
				textarea.setSelectionRange(newCursorPos, newCursorPos);
			}
			else {
				textarea.setSelectionRange(newCursorPos, newCursorPos+1);
				var evt = document.createEvent('KeyEvents');
				evt.initKeyEvent('keypress', true, true, window, false, false, false, false, 0, textarea.value.charCodeAt(newCursorPos));
				textarea.dispatchEvent(evt);
				textarea.setSelectionRange(newCursorPos, newCursorPos);
			}
		}
	}
	// Just put it on the end.
	else
	{
		textarea.value += text ;//+ ", " แก้ไข 22/03/2553 by pan
		textarea.focus(textarea.value.length - 1);
	}
}
// Validate with CustomValidator & Javascript
function ValidateDate(y, mo, d, h, mi, s)
{
  var date = new Date(y, mo - 1, d, h, mi, s, 0);
  var ny = date.getFullYear();
  var nmo = date.getMonth() + 1;
  var nd = date.getDate();
  var nh = date.getHours();
  var nmi = date.getMinutes();
  var ns = date.getSeconds();
  return ny == y && nmo == mo && nd == d && nh == h && nmi == mi && ns == s;
}
function CustomValidatorValidateDate(source, args)
{
    var _date = document.getElementById(source.controltovalidate).value;
    var _dmy = _date.split('/');
    args.IsValid = ValidateDate(_dmy[2]-543, _dmy[1], _dmy[0], 0, 0, 0);
}
function isDate(e)
{
    /* http://www.w3schools.com/jsref/jsref_onkeypress.asp */
    var keynum;
    var keychar;
    var datecheck;

    if(window.event) // IE
    {
        keynum = e.keyCode;
    }
    else if(e.which) // Netscape/Firefox/Opera
    {
        keynum = e.which;
    }
    keychar = String.fromCharCode(keynum);
    //alert(keychar+' '+keynum);
    datecheck = /\d|[/]/;

    return datecheck.test(keychar) && isCorrectSlashPosition(keychar, e); 
}
function isCorrectSlashPosition(keyChar, e)
{
    if(keyChar == '/')
    {
        // check version browser
        if (window.event) e = window.event; //IE (e.srcelement), FireFox (e.target)
        var objTextBox = e.srcElement ? e.srcElement : e.target;
        // check count slash
        if(objTextBox.value.split('/').length > 2) return false;
        var _ifirstSlash = objTextBox.value.indexOf('/');
        var _iPosition = getCaretPosition(objTextBox);
        // check position
        if((_iPosition == 2 || _iPosition == 3) && _ifirstSlash == -1) return true;
        else if((_ifirstSlash + 1) == 2 && (_iPosition == 4 || _iPosition == 5)) return true;
             else if((_ifirstSlash + 1) == 3 && (_iPosition == 5 || _iPosition == 6)) return true;
                  else return false;
    } 
    else return true; 
}
function getCaretPosition(objTextBox)
{
    /* Purpose : Returns the caret position of the cursor
     * in the text box
     * Effects : None
     * Inputs : objTextBox - a text box
     * Returns : Integer indicating the caret position
     * in the text box
     * http://bytes.com/topic/javascript/answers/149058-date-validation-using-onkeydown-javascript-asp
     */

    var i = objTextBox.value.length + 1;
    if (objTextBox.createTextRange)
    {
        objCaret = document.selection.createRange().duplicate();
        while (objCaret.parentElement() == objTextBox && objCaret.move("character", 1) == 1) --i;
    }
    return i;
}
function blurValidateDate(e)
{
    // check version browser
    if (window.event) e = window.event; //IE (e.srcelement), FireFox (e.target)
    var objTextBox = e.srcElement ? e.srcElement : e.target;
    if(objTextBox.value.split('/').length > 2) return true;
    var _dmy = objTextBox.value.split('/');
    if(!ValidateDate(_dmy[2]-543, _dmy[1], _dmy[0], 0, 0, 0))
    {
        var _date = new Date();
        objTextBox.value = _date.getDate() + '/' + (_date.getMonth() + 1) + '/' + (_date.getFullYear() + 543);
    }
}
// PasswordStrength Related Function
function passwordStrength(password, _desc, _color)
{
	var desc = new Array();
	desc[0] = "Very Weak";
	desc[1] = "Weak";
	desc[2] = "Better";
	desc[3] = "Medium";
	desc[4] = "Strong";
	desc[5] = "Strongest";

	var score   = 0;

	//if password bigger than 6 give 1 point
	if (password.length > 5) score++;

	//if password has both lower and uppercase characters give 1 point	
	if ( ( password.match(/[a-z]/) ) && ( password.match(/[A-Z]/) ) ) score++;

	//if password has at least one number give 1 point
	if (password.match(/\d+/)) score++;

	//if password has at least one special caracther give 1 point
	if ( password.match(/.[!,@,#,$,%,^,&,*,?,_,~,-,(,)]/) )	score++;

	//if password bigger than 12 give another 1 point
	if (password.length > 11) score++;

	 document.getElementById(_desc).innerHTML = desc[score];
	 document.getElementById(_color).className = "strength" + score;
}
//
// Custom Validator Function Javascript 
function CheckImagesFileOnly(source, args)
{
    //var sFile = args.value.toLowerCase();
    var sFile = document.getElementById(source.controltovalidate).value.toLowerCase();
    args.IsValid = ((sFile.endsWith('.jpg')) ||
                    (sFile.endsWith('.jpeg')) ||
                    (sFile.endsWith('.gif')) ||
                    (sFile.endsWith('.bmp')) ||
                    (sFile.endsWith('.png')));
}
function CheckFileOnly(source, args)
{
    //var sFile = args.value.toLowerCase();
    var sFile = document.getElementById(source.controltovalidate).value.toLowerCase();
    args.IsValid = ((sFile.endsWith('.pdf')) ||
                    (sFile.endsWith('.txt')) ||
                    (sFile.endsWith('.doc')) ||
                    (sFile.endsWith('.docx')) ||
                    (sFile.endsWith('.xls')) ||
                    (sFile.endsWith('.xlsx')) ||
                    (sFile.endsWith('.wav')) ||
                    (sFile.endsWith('.dat')));
}
function CheckFileSize(source, args)
{
    var sFile = document.getElementById(source.controltovalidate).value;
    args.IsValid = GetSize(sFile) <= 10485760; // 10MB
}
function GetSize(file){
    var fso = new ActiveXObject("Scripting.FileSystemObject");
    var f = fso.getFile(file);
    return f.size;
}
// Check File Extension Use With FileUpload
function CheckExcelFileOnly(source, args)
{
    var filename = document.getElementById(source.controltovalidate).value;
    var s = filename.lastIndexOf(".");
    var extension = filename.substring(s + 1).toUpperCase();
    if (extension == "XLS" || extension == "XLSX")
    {
        //do the function which you want in OnClientClick
        args.IsValid = true;
    }
    else
    {
        args.IsValid = false;
    }
}
function CheckTextFileFileOnly(source, args)
{
    var filename = document.getElementById(source.controltovalidate).value;
    var s = filename.lastIndexOf(".");
    var extension = filename.substring(s + 1).toUpperCase();
    if (extension == "TXT")
    {
        //do the function which you want in OnClientClick
        args.IsValid = true;
    }
    else
    {
        args.IsValid = false;
    }
}
//
// --! Ajax Function
// Check ID
function CallBack_CheckID(res)
{
    var arctmsg = res.value.split('|');
	document.getElementById(arctmsg[0]).innerHTML = arctmsg[1];
}
function CallBack_CheckIDAjax(res)
{
    eval(res.value);
}
function CheckIDTStructure(id, scode, _msg)
{
	fajax.CheckIDTStructure(id, document.getElementById(scode).value.trim(), _msg, CallBack_CheckID);
}
function CheckIDTDirectory(structid, id, scode, _msg)
{
	fajax.CheckIDTDirectory(structid, id, document.getElementById(scode).value.trim(), _msg, CallBack_CheckID);
}
function CheckIDTDocument(structid, sdirid, id, scode, _msg)
{
	fajax.CheckIDTDocument(structid, sdirid, id, document.getElementById(scode).value.trim(), _msg, CallBack_CheckID);
}
function CallBack(res)
{
    eval(res.value);
}
function CheckGroupID(groupID, scode, dispID, msg)
{
	fajax.CheckGroupID(groupID, scode, dispID, msg, CallBack);
}
function CheckUserName(userID, suserName, dispID, msg)
{
	fajax.CheckUserName(userID, suserName, dispID, msg, CallBack);
}

// Update
function CallBack_Update(res)
{
    alert(res.value);
}
function UcTopTStructure(_structid, _ctop, _session, _tmsg, _fmsg)
{
	fajax.UcTopTStructure(_structid, _ctop, _session, _tmsg, _fmsg, CallBack_Update);
}
// Ajax Function --! 
// Common Function
function doCheckUncheckAll(tblID, isChecked)
{
	var table = document.getElementById(tblID);
	var rows = table.getElementsByTagName('tr');
	for(i = 0; i < rows.length; i++){
		var cols = rows[i].getElementsByTagName('td');
		for(j = 0; j < cols.length; j++){
			var inputs = cols[j].getElementsByTagName('input');
			for(k = 0; k < inputs.length; k++){
				switch (inputs[k].type) {
					case 'checkbox': 
						inputs[k].checked = isChecked;
					break;
					case 'text': 
						//sumscore += parseInt(inputs[k].value == '' ? '0' : inputs[k].value);
					break;
				}
			}
		}
	}
}
// เลือกทั้งหมด ใน CheckBox ใน DataGrid
function doFindCheckAll(tblID, chkAllID)
{
	var isCheckAll = true;
	var table = document.getElementById(tblID);
	var rows = table.getElementsByTagName('tr');
	for(i = 1; i < rows.length; i++){
		var cols = rows[i].getElementsByTagName('td');
		for(j = 0; j < cols.length; j++){
			var inputs = cols[j].getElementsByTagName('input');
			for(k = 0; k < inputs.length; k++){
				switch (inputs[k].type) {
					case 'checkbox': 
						if(!inputs[k].checked) {isCheckAll = false; break;}
					break;
					case 'text': 
						//sumscore += parseInt(inputs[k].value == '' ? '0' : inputs[k].value);
					break;
				}
			}
		}
	}
	// check all
	document.getElementById(chkAllID).checked = isCheckAll;
}
function doFindCheckBoxListAll(tblID, chkAllID)
{
	var isCheckAll = true;
	var table = document.getElementById(tblID);
	var rows = table.getElementsByTagName('tr');
	for(i = 0; i < rows.length; i++){
		var cols = rows[i].getElementsByTagName('td');
		for(j = 0; j < cols.length; j++){
			var inputs = cols[j].getElementsByTagName('input');
			for(k = 0; k < inputs.length; k++){
				switch (inputs[k].type) {
					case 'checkbox': 
						if(!inputs[k].checked) {isCheckAll = false; break;}
					break;
					case 'text': 
						//sumscore += parseInt(inputs[k].value == '' ? '0' : inputs[k].value);
					break;
				}
			}
		}
	}
	// check all
	document.getElementById(chkAllID).checked = isCheckAll;
}
// เช็คว่ามีการเลือกเมื่อต้องการลบมะ และ ถ้าเลือกให้ยืนยันการลบ
function ConfirmDelete(cf, sl, tblID) 
{ 
	var isOneChecked = false;
	var table = document.getElementById(tblID);
	var rows = table.getElementsByTagName('tr');
	for(i = 1; i < rows.length; i++){
		var cols = rows[i].getElementsByTagName('td');
		for(j = 0; j < cols.length; j++){
			var inputs = cols[j].getElementsByTagName('input');
			for(k = 0; k < inputs.length; k++){
				switch (inputs[k].type) {
					case 'checkbox': 
						if(inputs[k].checked) {isOneChecked = true; break;}
					break;
					case 'text': 
						//sumscore += parseInt(inputs[k].value == '' ? '0' : inputs[k].value);
					break;
				}
			}
		}
	}
    if(isOneChecked) 
    {
        return confirm(cf);
    } 
    else 
    {
        alert(sl);
        return false;
    }
}
// Validate with CustomValidator & Javascript
function ValidateDate(y, mo, d, h, mi, s)
{
  var date = new Date(y, mo - 1, d, h, mi, s, 0);
  var ny = date.getFullYear();
  var nmo = date.getMonth() + 1;
  var nd = date.getDate();
  var nh = date.getHours();
  var nmi = date.getMinutes();
  var ns = date.getSeconds();
  return ny == y && nmo == mo && nd == d && nh == h && nmi == mi && ns == s;
}
function CustomValidatorValidateDate_enUS(source, args)
{
    var _date = document.getElementById(source.controltovalidate).value;
    var _dmy = _date.split('/');
    args.IsValid = ValidateDate(_dmy[2], _dmy[1], _dmy[0], 0, 0, 0);
}
function CustomValidatorValidateDate_thTH(source, args)
{
    var _date = document.getElementById(source.controltovalidate).value;
    var _dmy = _date.split('/');
    args.IsValid = ValidateDate(_dmy[2]-543, _dmy[1], _dmy[0], 0, 0, 0);
}
//
// Clear FileUpload
function RemoveFileUpload(control)
{
    var who = document.getElementsByName(control)[0];
    who.value = "";
    var who2 = who.cloneNode(false);
    who2.onchange = who.onchange;
    who.parentNode.replaceChild(who2, who);
}
function get(id, element) {
    //  validation code that was removed
    if (!element) return document.getElementById(id);
    if (element.getElementById) return element.getElementById(id);
    //  manual DOM walk that was removed ...
} 
//แพนเพิ่ม 27/04/2553
function sselect_deselectAll (chkVal, idVal, idstr, idstr2) 
{ 
    var frm = document.forms[0];
    // Loop through all elements
    for (i=0; i<frm.length; i++) 
    {
        // Look for our Header Template's Checkbox
        if (idVal.indexOf(idstr) != -1) 
        {
            //if elements is them RadioButtonList not access scope if
            if(frm.elements[i].name.indexOf (idstr2) != -1 && frm.elements[i].disabled == false)
            {
                // Check if main checkbox is checked, then select or deselect datagrid checkboxes 
                if(chkVal == true) 
                {
                    frm.elements[i].checked = true;
                } 
                else 
                {
                    frm.elements[i].checked = false;
                }
                // Work here with the Item Template's multiple checkboxes
            }
        } 
        else if (idVal.indexOf ('DeleteThis') != -1) 
        {
            // Check if any of the checkboxes are not checked, and then uncheck top select all checkbox
            if(frm.elements[i].checked == false) 
            {
                frm.elements[1].checked = false; //Uncheck main select all checkbox
            }
        }
    }
}
//แพนเพิ่ม 23/06/53
function Checkmemcode(spono, ctrID, ctr_sdID,_txt)// ตรวจสอบ กรอกเลขที่ซ้ำ
{
    if(spono != '')
    {
	    fajax.Checkmemcode(spono, ctrID, ctr_sdID,_txt, CallBack_CheckIDAjax);
	}
	else
	{
	    document.getElementById(ctrID).innerHTML = 'test';
	    document.getElementById(ctr_sdID).innerHTML = '55+';
	}
}
function CheckmemcodeEn(spono, ctrID, ctr_sdID,_txt)// ตรวจสอบ กรอกเลขที่ซ้ำ
{
    if(spono != '')
    {
	    fajax.CheckmemcodeEn(spono, ctrID, ctr_sdID,_txt, CallBack_CheckIDAjax);
	}
	else
	{
	    document.getElementById(ctrID).innerHTML = '';
	    document.getElementById(ctr_sdID).innerHTML = '';
	}
}