var web_req;
var msgbox_default = "กรุณาใส่ข้อมูลให้ครบถ้วน";

function Inint_AJAX()
{
    try {return new ActiveXObject("Msxml2.XMLHTTP");} catch(e) {} //IE
    try {return new ActiveXObject("Microsoft.XMLHTTP");} catch(e) {} //IE
    try {return new XMLHttpRequest();} catch(e) {} //Native Javascript
    alert("XMLHttpRequest not supported");
    return null;
}

function setfocus(object,combo)
{
    document.getElementById(object).focus();
    if(combo == false)
        document.getElementById(object).select()
}

function trim(obj_value)
{
    if(obj_value.length > 0)
    {
        i = 0;
	for(;;)
	{	
            ch = obj_value.substring(i,i+1);
            if((i == obj_value.length) || (ch != " "))
                break;
            else
                i++;
	}
	if((i != 0) && (i != obj_value.length))
	{
            obj_value = obj_value.substring(i,obj_value.length);
	}
        else
            {
                if(i == obj_value.length)
                    obj_value = "";
            }
		
	if(obj_value.length > 0)		
	{
            i = obj_value.length;
            for(;;)
            {
                ch = obj_value.substring(i-1,i);
		if((i == 0) || (ch != " "))
                    break;
		else
                    i--;
            }
            if(i != obj_value.length)
            {
                obj_value = obj_value.substring(0,i);
            }
	}					
    }
    return obj_value;
}

function textToEntities(text)
{
    var entities = "";
    for (var i = 0; i < text.length; i++)
    {
        if (text.charAt(i) == "&"){entities += "%26";}
        else
            {
                if (text.charAt(i) == "+"){entities += "%2b";}
		else
                    entities += text.charAt(i);
            }
    }

    return entities;
}

function IsNumeric(strString)
//check for valid numeric strings	
{
    var strValidChars = "0123456789";
    var strChar;
    var blnResult = true;
	
    if (strString.length == 0) return false;

    //  test strString consists of valid characters listed above
    for (i = 0; i < strString.length && blnResult == true; i++)
    {
        strChar = strString.charAt(i);
      	if (strValidChars.indexOf(strChar) == -1)
	{
            blnResult = false;
    	}
    }
    return blnResult;
}

function emailCheck(emailStr) 
{
/*  The following pattern is used to check if the entered e-mail address
    fits the user@domain format.  It also is used to separate the username
    from the domain. */
    var emailPat = /^(.+)@(.+)$/;
/*  The following string represents the pattern for matching all special
    characters.  We don't want to allow special characters in the address.
    These characters include ( ) < > @ , ; : \ " . [ ]    */
    var specialChars = "\\(\\)<>@,;:\\\\\\\"\\.\\[\\]";
/*  The following string represents the range of characters allowed in a
    username or domainname.  It really states which chars aren't allowed. */
    var validChars = "\[^\\s" + specialChars + "\]";
/*  The following pattern applies if the "user" is a quoted string (in
    which case, there are no rules about which characters are allowed
    and which aren't; anything goes).  E.g. "jiminy cricket"@disney.com
    is a legal e-mail address. */
    var quotedUser = "(\"[^\"]*\")";
/*  The following pattern applies for domains that are IP addresses,
    rather than symbolic names.  E.g. joe@[123.124.233.4] is a legal
    e-mail address. NOTE: The square brackets are required. */
    var ipDomainPat = /^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;
/*  The following string represents an atom (basically a series of
    non-special characters.) */
    var atom = validChars + '+';
/*  The following string represents one word in the typical username.
    For example, in john.doe@somewhere.com, john and doe are words.
    Basically, a word is either an atom or quoted string. */
    var word = "(" + atom + "|" + quotedUser + ")";
//  The following pattern describes the structure of the user
    var userPat = new RegExp("^" + word + "(\\." + word + ")*$");
/* The following pattern describes the structure of a normal symbolic
   domain, as opposed to ipDomainPat, shown above. */
    var domainPat = new RegExp("^" + atom + "(\\." + atom +")*$");


/*  Finally, let's start trying to figure out if the supplied address is
    valid. */

/*  Begin with the coarse pattern to simply break up user@domain into
    different pieces that are easy to analyze. */
    var matchArray = emailStr.match(emailPat);
    if (matchArray == null)
    {
/*  Too many/few @'s or something; basically, this address doesn't
    even fit the general mould of a valid e-mail address. */
//  alert("Email address seems incorrect (check @ and .'s)");
        return false;
    }

    var user = matchArray[1];
    var domain = matchArray[2];

//  See if "user" is valid
    if (user.match(userPat) == null)
    {
//  user is not valid
//  alert("The username doesn't seem to be valid.");
        return false;
    }

/*  if the e-mail address is at an IP address (as opposed to a symbolic
    host name) make sure the IP address is valid. */
    var IPArray = domain.match(ipDomainPat);
    if (IPArray!=null)
    {
//  this is an IP address
        for (var i=1;i<=4;i++)
        {
            if (IPArray[i]>255)
            {
//  alert("Destination IP address is invalid!");
                return false;
            }
        }
        return true;
    }

//  Domain is symbolic name
    var domainArray = domain.match(domainPat);
    if (domainArray == null)
    {
//  alert("The domain name doesn't seem to be valid.");
      return false;
    }

/*  domain name seems valid, but now make sure that it ends in a
    three-letter word (like com, edu, gov) or a two-letter word,
    representing country (uk, nl), and that there's a hostname preceding
    the domain or country. */

/*  Now we need to break up the domain to get a count of how many atoms
    it consists of. */
    var atomPat = new RegExp(atom,"g");
    var domArr = domain.match(atomPat);
    var len = domArr.length;
    if (domArr[domArr.length-1].length<2 || domArr[domArr.length-1].length>3)
    {
//  the address must end in a two letter or three letter word.
//  alert("The address must end in a three-letter domain, or two letter country.");
        return false;
    }

//  Make sure there's a host name preceding the domain.
    if (len < 2)
    {
//  var errStr="This address is missing a hostname!";
//  alert(errStr);
        return false
    }

// If we've gotten this far, everything's valid!
    return true;
}

function daysInFebruary (year)
{
    //February has 29 days in any year evenly divisible by four,
    //EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}

function DaysArray(n) 
{
    for (var i = 1;i <= n;i++)
    {
        this[i] = 31;
	if (i == 4 || i == 6 || i == 9 || i == 11) {this[i] = 30;}
	if (i == 2) {this[i] = 29;}
    }
   return this;
}

function isDate(day,month,year)
{
    var daysInMonth = DaysArray(12);
    var date = day + "-" + month + "-" + year;

    if (date != "00-00-0000")
    {
        if (day == "00") return false;
    	if (month == "00") return false;
	if (year == "0000") return false;
	if (((parseInt(month) == 2) && (day > daysInFebruary(year))) || (day > daysInMonth[parseInt(month)]))
	{
            return false;
	}
    }
    return true;
}

function checkKeycode(e)
{    
    return e.keyCode;
}

function frm_reset(frm,msg,display,obj,txt)
{
    if (msg == true)
    {
        if (display == false) {if (document.getElementById(obj).style.display  != "none") document.getElementById(obj).style.display  = "none";}
	if (display == true) {document.getElementById(obj).innerHTML = txt;}
    }
    document.getElementById(frm).reset();
}

function storeCaret(text)
{
    //Only bother if it will be useful.
    if (typeof(text.createTextRange) != "undefined")
        text.caretPos = document.selection.createRange().duplicate();
} 

function replace_text(text,textarea)
{
    //Attempt to create a text range (IE).
    if (typeof(textarea.caretPos) != "undefined" && textarea.createTextRange)
    {
        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 scrollPos = textarea.scrollTop;

		textarea.value = begin + text + end;

		if (textarea.setSelectionRange)
		{
                    textarea.focus();
                    textarea.setSelectionRange(begin.length + text.length, begin.length + text.length);
		}
		textarea.scrollTop = scrollPos;
            }
            //Just put it on the end.
            else
		{
                    textarea.value += text;
                    textarea.focus(textarea.value.length - 1);
		}
        }
}

function surround_text(text1,text2,textarea)
{
    //Can a text range be created?
    if (typeof(textarea.caretPos) != "undefined" && textarea.createTextRange)
    {
        var caretPos = textarea.caretPos, temp_length = caretPos.text.length;

	caretPos.text = caretPos.text.charAt(caretPos.text.length - 1) == ' ' ? text1 + caretPos.text + text2 + ' ' : text1 + caretPos.text + text2;
		
	if (temp_length == 0)
	{
            caretPos.moveStart("character", -text2.length);
            caretPos.moveEnd("character", -text2.length);
            caretPos.select();
	}
	else
            textarea.focus(caretPos);
    }
    //Mozilla text range wrap.
    else
        {
            if (typeof(textarea.selectionStart) != "undefined")
            {
                var begin = textarea.value.substr(0, textarea.selectionStart);
		var selection = textarea.value.substr(textarea.selectionStart, textarea.selectionEnd - textarea.selectionStart);
		var end = textarea.value.substr(textarea.selectionEnd);
		var newCursorPos = textarea.selectionStart;
		var scrollPos = textarea.scrollTop;

		textarea.value = begin + text1 + selection + text2 + end;
	
		if (textarea.setSelectionRange)
		{
                    if (selection.length == 0)
                        textarea.setSelectionRange(newCursorPos + text1.length, newCursorPos + text1.length);
                    else
                        textarea.setSelectionRange(newCursorPos, newCursorPos + text1.length + selection.length + text2.length);
                    textarea.focus();
		}
		textarea.scrollTop = scrollPos;
            }
            //Just put them on the end, then.
            else
                {
                    textarea.value += text1 + text2;
                    textarea.focus(textarea.value.length - 1);
		}
        }
}

function select_to_list(obj_choose,obj_list)
{
    var choose = document.all[obj_choose].value;

    if (choose.length > 0)
    {
        var obj = document.all[obj_list];
	var i;

	if (obj.length > 0)
	{
            for(i = 0;i < obj.length;i++)
            {
		if (choose == obj.options[i].value) return;
            }
	}

        var opt = document.createElement("OPTION");
	obj.options.add(opt);
	opt.innerHTML = choose;
	opt.value = choose;
    }
}

function clear_list(obj,mode)
{
    var obj_combo = document.all[obj];

    if (mode == 1)
    {
        if (obj_combo.options.selectedIndex >= 0) obj_combo.options[obj_combo.options.selectedIndex] = null;
    }

    if (mode == 2)
    {
        for(i = obj_combo.length - 1;i >= 0;i--)
	{
            obj_combo.options[i] = null;
	}
    }
}

function delete_list(obj)
{
    var obj_combo = document.all[obj];

    if (obj_combo.options.selectedIndex >= 0) obj_combo.options[obj_combo.options.selectedIndex] = null;
}

function groupvalue_list(obj)
{
    var result = "";

    for (var i = 0;i < obj.length;i++)
    {
        if (result.length > 0) {result = result + ";" + obj.options[i].value;} else {result = obj.options[i].value;}
    }

    return result;
}

function copy_list(obj_source,obj_destination)
{
    clear_list(obj_destination,2);

    obj_combo = document.all[obj_source];
    for(i = 0;i < obj_combo.length;i++)
    {
        var tmp = obj_combo.options[i].value;
	var data = tmp.split(";")
	var obj = document.all[obj_destination];
	var opt = document.createElement("OPTION");
	obj.options.add(opt);
	opt.innerHTML = data[1];
	opt.value = data[0];
    }
}

function getPageSize()
{
    var xPage,yPage;

    if (self.innerHeight )
    {
        xPage = self.innerWidth;
    	yPage = self.innerHeight;
    }
    else
        {
            if (document.documentElement && document.documentElement.clientHeight )
            {
                xPage = document.documentElement.clientWidth;
		yPage = document.documentElement.clientHeight;
            }
            else
		{
                    if (document.body )
                    {
                        xPage = document.body.clientWidth;
    			yPage = document.body.clientHeight;
                    }
		}
	}

    return new Array(xPage,yPage);
}

function getPageScroll()
{
    var yScroll;

    if (self.pageYOffset)
    {
        yScroll = self.pageYOffset;
    }
    else
        {
            if (document.documentElement && document.documentElement.scrollTop)
            {
                // Explorer 6 Strict
                yScroll = document.documentElement.scrollTop;
            }
            else
                {
                    if (document.body)
                    {
                        // all other Explorers
                        yScroll = document.body.scrollTop;
                    }
                }
        }

	return new Array('',yScroll);
}

function show_popup(mode,order)
{
    var xyPage = getPageSize();
    var xyScroll = getPageScroll();
    document.getElementById("popup").style.display = "";

    switch (mode)
    {
        case "form" : {
                        document.getElementById("close_popup_" + order + "_content").style.display = "";
                        frm = document.getElementById(order + "_content").style;
                        document.getElementById("show_form").style.left = ((xyPage[0] - 20 - parseInt(frm.width)) / 2) + "px";
                        document.getElementById("show_form").style.top = ((xyPage[1] - parseInt(frm.height)) / 2) - parseInt(50) + "px";
                        document.getElementById("show_form").style.display = "";
                        document.getElementById(order + "_content").style.display = "";
                        break;
                      }
    }
}

function close_popup(mode,order,close)
{
    switch (mode)
    {
        case "form"  : {
                         document.getElementById("close_popup_" + order + "_content").style.display = "none";
                         document.getElementById(order + "_content").style.display = "none";
                         document.getElementById("show_form").style.display = "none";
                         break;
                       }
    }

    if (close != false){ document.getElementById("popup").style.display = "none"; }
}

function load_security_code(show)
{
    var url = "Securitycode.php";

    if (web_req == null){web_req = Inint_AJAX();}
    web_req.abort();

    web_req.open("GET", url, true);
    web_req.onreadystatechange = function(){
        if (web_req.readyState == 4)
	{
            if (web_req.status == 200)
            {
                var data = web_req.responseText;

                document.getElementById(show).innerHTML = data;
            }
	}
    };
    web_req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
    web_req.send(null);
}


function search_array(array,keyword)
{
    var i;
    
    for(i = 0;i < array.length;i++)
    {
        if(keyword == array[i]) return true;
    }
    return false;
}

function limit_string(e,obj,len)
{
    var mykeycode_unblock = [8,9,33,34,35,36,37,38,39,40,13];
    var mykeycode_block = [59];
    var charCode = (e.which) ? e.which : e.keyCode

    if(((obj.value.length < len) || (search_array(mykeycode_unblock,charCode) == true)) && (search_array(mykeycode_block,charCode) == false)) return true;
    
    return false;
}

function count_string(e,obj,len,show)
{
    var mykeycode = [33,34,35,36,37,38,39,40,59];
    var charCode = (e.which) ? e.which : e.keyCode

    if((obj.value.length <= len) && (search_array(mykeycode,charCode) == false))
    {
        show_len(obj,len,show);
    }
}

function show_len(obj,len,show)
{
    document.getElementById(show).innerHTML = len - obj.value.length
}

function key_number(keycode)
{
    var myarray = [8,9,33,34,35,36,37,38,39,40,48,49,50,51,52,53,54,55,56,57];

    if(search_array(myarray,keycode) == true) return true;
    return false;
}

function IsIdCard(id_card)
{
    var total = 0;
    var mul = 13;

    if(id_card.length != 13) return false;

    for(i = 0;i < id_card.length - 1;i++)
    {
        total = total + id_card[i] * mul;
        mul = mul - 1;
    }
    mod = total % 11;
    nsub = 11 - mod;
    mod2 = nsub % 10;
    if(mod2 != id_card[12])
        return false;
    else
        return true;
}

function checkall(order,obj)
{
    var i;
    var count_order;
    
    count_order = document.getElementById(order).value;

    if(count_order > 0)
    {
        for(i = 1;i <= count_order;i++)
        {
            document.getElementById(obj + i).checked = true;
        }
    }
}

function uncheckall(order,obj)
{
    var i;
    var count_order;

    count_order = document.getElementById(order).value;

    if(count_order > 0)
    {
        for(i = 1;i <= count_order;i++)
        {
            document.getElementById(obj + i).checked = false;
        }
    }
}

function iif(condition,result_true,result_false)
{
    var result;
    
    if(condition){result = result_true;}else{result = result_false;}
    return result;
}

function showselecttitle(id,title)
{
    document.getElementById(id).innerHTML = title;
}
