// post("index.jsp", {refervariable:variable,paramstring:"string",number:10});
if($context == null) {
	var $context='';
}
function setParentPlace(datas) {
	document.getElementById('parentplaceforinnerHTML').innerHTML = datas; 
}
function setToCurrentPlace(datas, xadd, yadd) {
	var ix = getPosX()+xadd; 
	var iy = getPosY()+yadd; 
	datas = "<span style='position:absolute;left:"+(ix==null?0:ix)+";top:"+(iy==null?0:iy)+";'>"+datas+"</span>";
	setParentPlace(datas);
}

//allvals is new Array('1',2,'3',4) Or ['1','22',333,'44']
function sum(allvals) {
	var data = 0;
	for(var d=0; d<allvals.length; d++) {
		try {
			if(allvals[d]*1) data+=(allvals[d]*1);
		} catch(e) {
		}
	}
	return data;
}


	function topage(topg) {
		try {
			var tmppage;
			var tmptxt = topg;
			var params = findTextByRegEx("(\\?|&)[^=?&]+=[^=?&]+",tmptxt);
			if(params == null) {
				tmppage = topg;
			} else {
				tmppage = topg.substring(0, topg.indexOf("?"));
			}
			var URL = tmppage;
			var allparam = new Array();
			while(params != null) {
				tmptxt = tmptxt.substring(tmptxt.indexOf(params)+params.length);
				allparam[findTextByRegEx("[^=?&]+", params)] = iescapeback(findTextByRegEx("=[^=?&]+", params).substring(1));
				params = findTextByRegEx("(\\?|&)[^=?&]+=[^=?&]+",tmptxt);
			}
			post(URL, allparam);
		} catch(e) {
			location.href = topg;
		}
	}
// remove data from array config by index
function remove(datas,index) {
	if(index<0 || index>=datas.length) return datas;
	if(index==datas.length-1) {
		datas = datas.slice(0,index);
	} else {
		datas = datas.slice(0,index).concat(datas.slice((datas.length-index-1)*-1));
	}
	return datas;
}

function post(URL, PARAMS) {
	var objload = "<table width='750' border=0><tr><td height='250' align=center><table width='0' height='0'>"
		+"<tr><td><font color='#A3A3A3' size='2' face='Times New Roman'><b>Loading</b></font></td></tr>"
		+"<tr><td align=center><img src='"+$context+"/images/default/loading.gif'></td></tr></table>";
	objload = "<table><tr><td>"+objload+"</td></tr></table></td></tr></table>";
	document.getElementById("mainrefresh").innerHTML=objload;
	var fct = function(){toPageByPost(URL, PARAMS);};
	var time = setTimeout(fct,300);
}
//call by function post after display effect
function toPageByPost(URL, PARAMS) {
	var temp=document.createElement("form");
	temp.action=URL;
	temp.method="POST";
	temp.style.display="none";
	for(var x in PARAMS) {
		var opt=document.createElement("textarea");
		opt.name=x;
		opt.value=PARAMS[x];
		temp.appendChild(opt);
	}
	document.body.appendChild(temp);
	temp.submit();
	return temp;
}
function disableAlliSearch() {
	try{
		var iall=document.all("isearch");
		if(iall.length==null) {
			document.getElementById("isearch").style.display="none";
		} else {
			for( var i=0;i<iall.length;i++ ) {
				iall[i].style.display="none";
			}
		}
	} catch(e){
	}
}

// all focus image path
//var $picpath = $context+"/images/";
var $picpath = "../images/";
// iduserpath : Store path of file in user machine
// idserverpath : Store path of file user upload in Server machine
function getFilePath(caption, iduserpath, idserverpath, fixfilename, iuploadpath) {
	var url = $context+"/tools/upload/browse.jsp?caption="+caption+"&userpath="+iduserpath
	+"&serverpath="+idserverpath+"&fixfilename="+fixfilename+"&iuploadpath="+iuploadpath;
	open(url,'None','left=200,right=200,menubar=no,status=no,titlebar=no,toolbar=no,alwaysRaised=yes,resizable=no,width=300,height=100');
}

// use with web.jsp
function setLoading(displayobj, dataafterload) {
	var objload = "<table width='0' height='0'>"
		+"<tr height=0><td align=center><font color='#A3A3A3' size='2' face='Times New Roman'><b>Loading</b></font></td></tr>"
		+"<tr><td align=center><img src='"+$context+"/images/default/loading.gif'></td></tr></table>";
	objload = "<table width='100%' height='100%'><tr><td align=center valign=middle>"+objload+"</td></tr></table>";
	displayobj.innerHTML=objload;
	var fct = function(){displayobj.innerHTML=dataafterload;};
	var time = setTimeout(fct,500);
}
function setFctAfterLoad(actareaobj,fct) {
	var objload = "<table width='0' height='0'>"
		+"<tr height=0><td align=center><font color='#A3A3A3' size='2' face='Times New Roman'><b>Loading</b></font></td></tr>"
		+"<tr><td align=center><img src='"+$context+"/images/default/loading.gif'></td></tr></table>";
	objload = "<table width='100%' height='100%'><tr><td align=center valign=middle>"+objload+"</td></tr></table>";
	actareaobj.innerHTML=objload;
	var time = setTimeout(fct,500);
}

function setStatusFlagText(id, usepasstext) {
	document.getElementById(id).innerHTML = "<span class="+(usepasstext?"passtext":"errortext")+">*</span>";
}

	// <tr onclick="swaprow(this);" old="rowactive" class="bwrow0">
	// for swap style class between old property and class property
	function swaprow(obj) {
		var classdefault = "rowover";
		var tmp = obj.className;
		obj.className = obj.old==null?classdefault:obj.old;
		obj.old = tmp;
	}
	
	function getValue(id) {
		try {
			return document.getElementById(id).value;
		} catch(e){
			return null;
		}
	}
	
function setAllDisabled(id) {
	var allobj = document.all[id];
	try {
		if(allobj.length == null) {
			allobj.disabled=true;
		} else {
			for(var i=0; i<allobj.length; i++) {
				allobj.item(i).disabled=true;
			}
		}
	} catch(e){}
}
function replaceAll(text, oldText, replaceWith) {
	if(text==null) return text;
	if(oldText != null && replaceWith != null) {
		if(oldText==replaceWith){
			return text;
		}
	} else {
	  return text;
	}
	var index = text.indexOf(oldText);
	var remainText = text;
	var result = "";
	while (index > -1) {
	  result += remainText.substring(0,index) + replaceWith;
	  remainText = remainText.substring(index + oldText.length, remainText.length);
	  index = remainText.indexOf(oldText);
	}
	result += remainText;
	return result;
}


function iescape(data) {
	data = replaceAll(data,"&","%26");
	data = replaceAll(data,"=","%3D");
	data = replaceAll(data,"?","%3F");
	return data;
}
function iescapeback(data) {
	data = replaceAll(data,"%26","&");
	data = replaceAll(data,"%3D","=");
	data = replaceAll(data,"%3F","?");
	return data;
}

////////////////////////////// For get Position of Obj ///////////////////////////
/**
	Ex. 
		// obj is  obj u need to find position
		var obj;
		var pos = new Position(obj);
		alert("X : "+pos.getX()+"\nY : " + pos.getY());
		//////// original
    try {
        var targetElement = this.obj;
        if(targetElement.x && targetElement.y) {
            this.coords.x = targetElement.x;
            this.coords.y = targetElement.y;
        } else {
            if(targetElement.offsetParent) {
                this.coords.x += targetElement.offsetLeft;
                this.coords.y += targetElement.offsetTop;
                while(targetElement = targetElement.offsetParent) {
                    this.coords.x += targetElement.offsetLeft;
                    this.coords.y += targetElement.offsetTop;
                }
            } else {
                //alert(\"Could not find any reference for coordinate positioning.\");
            }
        }
    } catch(error) {
        //alert(error.msg);
    }
*/
function getBrowserType() {
    var isNS4 = (document.layers) ? true : false;
    var isIE4 = (document.all && !document.getElementById) ? true : false;
    var isIE5 = (document.all && document.getElementById) ? true : false;
    var isNS6 = (!document.all && document.getElementById) ? true : false;
    var isNS = (isNS4||isNS6) ? true : false;
    var isIE = (isIE4||isIE5) ? true : false;
    var browser = "";
    if(isNS4) {
    	browser = "Netscape 4";
    } else if(isIE4) {
    	browser = "IE 4";
    } else if(isIE5) {
    	browser = "IE 5";
    } else if(isNS6) {
    	browser = "Netscape 6";
    } else if(isNS) {
    	browser = "Netscape";
    } else if(isIE) {
    	browser = "IE";
    }
    return browser;
}

function getEvent(e) {
	if (window.Event) {
		return window.Event;
	} else if(document.documentElement.event) {
		return document.documentElement.event;
	} else if (event) {
		return event;
	} else {
		alert("Internet Browser not support please try to use IE or Firefox or another IE before visit our website");
		return null;
	}
}
var Position = function (objname){
	this.obj = objname;
	this.coords = new Object();
    this.coords.x = 0;
	this.coords.y = 0;
}
Position.prototype.getX = function() {
    try {
        var targetElement = this.obj;
        if(targetElement.x) {
            this.coords.x = targetElement.x;
        } else {
            if(targetElement.offsetParent) {
                this.coords.x += targetElement.offsetLeft;
                while(targetElement = targetElement.offsetParent) {
                    this.coords.x += targetElement.offsetLeft;
                }
            } else {
                //alert(\"Could not find any reference for coordinate positioning.\");
            }
        }
    } catch(error) {
        //alert(error.msg);
    }
	return this.coords.x;
}
Position.prototype.getY = function() {
    try {
        var targetElement = this.obj;
        if(targetElement.y) {
            this.coords.y = targetElement.y;
        } else {
            if(targetElement.offsetParent) {
            	alert("in offsetParent y");
                this.coords.y += targetElement.offsetTop;
                while(targetElement = targetElement.offsetParent) {
                    this.coords.y += targetElement.offsetTop;
                }
            } else {
                //alert("Could not find any reference for coordinate positioning.");
            }
        }
    } catch(error) {
        //alert(error.msg);
    }
	return this.coords.y;
}
function os(e) {
	var e=(!e)?window.event:e;//IE:Moz
	var x=0,y=0;
	if(e.pageX) {
		x = e.pageX;
		y = e.pageY;
	} else if(e.clientX) {
		if(document.body){//Other IE
			x = e.clientX + document.body.scrollLeft;
			y = e.clientY + document.body.scrollTop;
		} else if(document.documentElement){//IE 6+ strict mode
			x = e.clientX + document.documentElement.scrollLeft;
			y = e.clientY + document.documentElement.scrollTop;
		}
	}
	currentPosX = x;
	currentPosY = y;
}

function getPosX() {
	try {
		return currentPosX;
	} catch(e) {
	}
}
function getPosY() {
	try {
		return currentPosY;
	} catch(e) {
	}
}
//////////////////////////////////// For get Position of Obj /////////////////////
/*
Process: Trim
to trim a string
Parameter:
	- s = (String) source string
Return: (String) string after trim
*/
function trim(str) {
	return str.replace(/^\s*|\s*$/g,"");
/*
	while (s.substring(0,1) == ' ') {
		s = s.substring(1, s.length);
	}
	while (s.substring(s.length-1, s.length) == ' ') {
		s = s.substring(0,s.length-1);
	}
	return s;
*/	
}

/** 
Process: StringBuffer
to create string buffer in javascript
Example.
	var sb = new StringBuffer();
	sb.append("abc");
	sb.append("xyz");
	sb.toString(); ==> "abcxyz"
	sb.toString(" "); ==> "abc xyz"
	sb.toString(","); ==> "abc,xyz"
*/
var StringBuffer = function() {
	this.buffer = new Array();
}
StringBuffer.prototype.append = function(str) {
	this.buffer[this.buffer.length] = str;
}
StringBuffer.prototype.toString = function(str) {
	if (str == undefined) str = '';
	return this.buffer.join(str);
//	var ss = this.buffer.join(str);
//	if (ss.length>0) ss=ss.substring(0, ss.length-str.length);
//	return ss;
}

/**
	var alldata = new Array();
	alldata = getStringArray('123,456,789', ',');
	alldata -> "{123, 456, 789}";
	data is return in Array format
*/
function getStringArray(data, separator) {
     var value = new Array();
     if (data != null){
        data = trim(data);
		 if (data=="") return"";
		 if (separator=="") return data;
		var x = data.length+separator.length;
        var tmpData = new Array((x<1?1:x));
        var count = 0, num = data.indexOf(separator);
        var tempData,temp;
        if (num != -1) {
            tempData = data.substring(0,num);
            var xtempdata=trim(tempData);
            if(xtempData == "" ) {
               tmpData[count] = tempData;
            } else {
               tmpData[count] = xtempdata;
            }
            data = data.substring(num+separator.length, data.length);
            data = trim(data);
            count++;
            while (num != -1) {
               num = data.indexOf(separator);
               if (num == -1) {
                  var xtempData = trim(data);
                  if(xtempData == "" ) {
                     tmpData[count] = data;
                  } else {
                     tmpData[count] = trim(xtempData);
                  }
                  count++;
               } else {
                  tempData = data.substring(0,num);
                  var x=trim(tempData);
                  if(x == "") {
                     tmpData[count] = tempData;
                  } else {
                     tmpData[count] = x;
                  }
                  data = data.substring(num+separator.length, data.length);
                  count++;
               }
            }
      } else {
         tmpData[0] = data;
         count++;
      }
      value = new Array(count);
      for (var y = 0 ; y < count ; y++ ) {
         value[y] = tmpData[y];
      }
   }
   return value;
}

function isEnter(e) {
	var keycode;
	if (window.event) {
		keycode = window.event.keyCode;
	} else if (e) {
		keycode = e.which;
	} else {
		return false;
	}
	if (keycode == 13) {
		flag = true;
		return true;
	} else {
		return false;
	}
}

var txtexception = "character only enable with english type or 0-9 or _ only";
// for only thai text use ¡-ì
// character only enable with english type or 0-9 or _ only
function isEnableCharacter(text) {
	var errortxt=false;
	for (var i=0;i<text.length;i++) {
		if (text.charAt(i).search(/[0-9]/) == -1 && text.charAt(i).search(/[A-Z]/) == -1
			&& text.charAt(i).search(/[a-z]/) == -1 && text.charAt(i) != "_") {
			errortxt = true;
			break;
		}
	}
	return !errortxt;
}

////////////////////////////////////////////// For ListBox Manage /////////////////////////////////////////////////
/*
Process: isIE
Return: true if the browser is Microsoft Internet Explorer
        false if other browser
*/
function isIE() {
	return (document.all==undefined)?false:true;
}

/*
Process: isNescape
Return: true if the browser isn't Microsoft Internet Explorer
        false if the browser is Microsoft Internet Explorer
*/
function isNescape() {
	return (document.all==undefined)?true:false;
}

/*
Process: window_height
Return: the height of window
*/
function window_height() {
	return isIE()?document.body.clientHeight:window.innerHeight;
}

/*
Process: window_width
Return: the width of window
*/
function window_width() {
	return isIE()?document.body.clientWidth:window.innerWidth;
}
/*
Process: toSelMove[Side]2[Side]
	to move a option from sel1 to sel2 
	insert at index the selected (sel2) in select-input-type 
	- L = Left
	- R = Right
Parameter:
	- sel1 = (Object - InputSelect - from)
	- sel2 = (Object - InputSelect - to)
	- index = (int - index of selectedIndex on sel2)
Return: (String) string list of selected option on InputSelect
*/
function toSelMoveL2R(sel1, sel2, index) {
    toSelMove(sel1, sel2, index);
}
function toSelMoveR2L(sel1, sel2, index) {
    toSelMove(sel2, sel1, index);
}
function toSelMoveL2RAll(sel1, sel2, index) {
    toSelMoves(sel1, sel2, index);
}
function toSelMoveR2LAll(sel1, sel2, index) {
    toSelMoves(sel2, sel1, index);
}
/*
Process: toSelMoves
to move all option from sel1 to sel2 
insert at index the selected (sel2) in select-input-type 
Parameter:
	- sel1 = (Object - InputSelect - from)
	- sel2 = (Object - InputSelect - to)
	- index = (int - index of selectedIndex on sel2)
Return: (String) string list of selected option on InputSelect
*/
function toSelMoves(sel1, sel2, index) {
    try {
        var max1 = sel1.length, max2 = sel2.length;
        if (index==undefined) index = sel2.length; else index++;
        if (max1>0) {
            sel1.selectedIndex = 0;
            for (var i=0; i<max1; ++i) {
                var optNew = document.createElement('option');
                optNew.text = sel1.options[0].text;
                optNew.value = sel1.options[0].value;
                try {
                    sel2.add(optNew, index++); // standards compliant
                } catch (ex) {
                    sel2.add(optNew); // IE only
                }
                sel1.remove(0);
            }
        }
    } catch (e) {
        alert("Can not move all item from '"+sel1.name+"' to '"+sel2.name+"'.\n"+e.message);
    }
}
document.onclick = os;

/*
Process: toSelMove
to move a option from sel1 to sel2 
insert at index the selected (sel2) in select-input-type 
Parameter:
	- sel1 = (Object - InputSelect - from)
	- sel2 = (Object - InputSelect - to)
	- index = (int - index of selectedIndex on sel2)
Return: (String) string list of selected option on InputSelect
*/
function toSelMove(sel1, sel2, index) {
    try {
        var max1 = sel1.length, max2 = sel2.length;
        var idx1 = sel1.selectedIndex, idx2 = sel2.selectedIndex;
        if (index==undefined) index = sel2.length; else index++;
        if (idx1 >= 0 && idx1 < max1) {
            var optNew = document.createElement('option');
            optNew.text = sel1.options[idx1].text;
            optNew.value = sel1.options[idx1].value;
            try {
                sel2.add(optNew, index); // standards compliant
            } catch (ex) {
                sel2.add(optNew); // IE only
            }
            sel1.remove(idx1);
            if (idx1 >= sel1.length) idx1--;
            if (idx1 >= 0) sel1.selectedIndex = idx1;
        }
    } catch (e) {
        alert("Can not move item from '"+sel1.name+"' to '"+sel2.name+"'.\n"+e.message);
    }
}

/*
Process: makeOptionsList
to concat the options in select-input-type 
Parameter:
	- obj = (Object - InputSelect)
Return: (String) string list of selected option on InputSelect
*/
function getOptionsList(obj) {
	var sb = new StringBuffer();
	for (var i=0; i<obj.length; ++i) {
		sb.append(obj.options[i].value);
	}
	return sb.toString(", ");
}

/*
Process: makeSelectedList
to concat the selected option in select-input-type 
Parameter:
	- obj = (Object - InputSelect)
Return: (String) string list of selected option on InputSelect
*/
function getSelectedList(obj) {
	var sb = new StringBuffer();
	for (var i=0; i<obj.length; ++i) {
		if (obj.options[i].selected) {
			sb.append(obj.options[i].value);
		}
	}
	return sb.toString(",");
}
var data  = "";
var i = 0;
for(temp in document) {
	i++;
	data+=temp+","+(i%10==0?"\n":"");
}

/*  Use Ajax for get context use in javascript  */
// this function will blur your pic and restore basic pic
// picture name support by this function
//  is basic pic with [^_]+
//  and Blur pic with [_][^_]+
function blurPic(objectname, ctx) {
	var obj = objectname;
	var path = obj.src;
	var oldimg=obj.img;
	var picname = path.substring(path.lastIndexOf("/")+1);
	if(trim(ctx) == "") {
		// In context with ROOT case 
		path = path.substring(0,path.lastIndexOf("/")+1);
	} else {
		// In context not equals ROOT
		path = path.substring(path.lastIndexOf(ctx+"/")+ctx.length, path.lastIndexOf("/")+1);
	}
	if(picname.substring(0,1) == "_") {
		picname = picname.substring(1);
	} else {
		picname = "_"+picname;
	}
	obj.src = ctx+path+picname;
}
	// use by <span id="change_image" onclick=alert('edit'); img='fullpath' ctx='<%=ctx%>' hint='Edit record'></span>
	function getBlurImage(doc) {
		var its = doc.all["change_image"];
		try {
			if(its.length == null) {
				its.value=(its.value==null?its.innerHTML:its.value);
				setImage(its);
			} else {
				for(var i=0; i<its.length; i++) {
					its.item(i).value=(its.item(i).value==null?its.item(i).innerHTML:its.item(i).value);
					setImage(its.item(i));
				}
			}
		} catch(e){}
	}
	function setImage(obj) {
		var pic = "<img src='"+obj.img+"' img='"+obj.img+"' onmouseover=this.style.cursor='hand';blurPic(this,'"+obj.ctx+"'); onmouseout=blurPic(this,'"+obj.ctx+"');>";
		obj.innerHTML = pic;
	}
///////////////////////////////////// Set Property Of  object ///////////////////////////////
var XProperty = function(dataobj){
	this.obj = dataobj;
}

XProperty.prototype.setNone = function() {
	try{
		this.obj.style.display="none";
	}catch(e){alert(e);}
}

XProperty.prototype.setShow= function() {
	try{
		this.obj.style.display="block";
	}catch(e){}
}

/**
Global Search
	g The global search flag makes the RegExp search for a pattern throughout the string, creating an array of all	occurrences it can find matching the given pattern.
Ignore Case
	i The ignore case flag makes a regular expression case insensitive. For international coders, note that this might not work on extended characters.
Multiline Input
	m This flag makes the beginning of input (^) and end of input ($) codes also catch beginning and end of line respectively.
Ex.
	var re = new RegExp(window.prompt('Please input a regex.','yes|yeah'),'g');
*/
function findTextByRegEx(regex, text) {
	var re = new RegExp(regex);
	var datas = re.exec(text);
	if(datas==null) {
		return null;
	}
	return datas[0];
}

/////////////////////////////// Use Button path //////////////////////////////////////
//<span id="change_button" onclick="confirm('Logout?')?topage('/WebUserSwitcher.do?action=logout'):'';" context="<%=ctx%>"><span class=buttontext>LOGOUT</span></span>
	function setButton(doc) {
		var its = doc.all["change_button"];
		try {
			if(its.length == null) {
				its.value=(its.value==null?its.innerHTML:its.value);
				swapButton(its);
			} else {
				for(var i=0; i<its.length; i++) {
					its.item(i).value=(its.item(i).value==null?its.item(i).innerHTML:its.item(i).value);
					swapButton(its.item(i));
				}
			}
		} catch(e){}
	}

	/**
	 *		obj.idisabled only set with true or false with boolean type
	 */
	 var btnpath = "/images/main/";
	function swapButton(obj) {
		var p1 = "bt1.gif";
		var p2 = "bt2.gif";
		var p3 = "bt3.gif";
		if((""+obj.idisabled) == "true") {
			obj.oldclick=obj.onclick;
			obj.onclick="";
			p1 = "_bt1.gif";
			p2 = "_bt2.gif";
			p3 = "_bt3.gif";
		} else {
			if(obj.oldclick != null) {
				obj.onclick = obj.oldclick;
			}
		}
		var path = (obj.context != null?obj.context:"")+btnpath;
		var h = 30;
		var bt = "<table border=0 cellpadding=0 cellspacing=0 height="+h+" width=0 onmouseover=this.style.cursor='hand'><tr>";
		bt += "<td>";
		bt += "	<IMG height="+h+" width=9 src='"+path+p1+"' border=0>";
		bt += "</td>";
		bt += "<td width='0' background='"+path+p2+"'>";
		bt += obj.value;
		bt += "</td>";
		bt += "<td>";
		bt += "	<IMG height="+h+" width=9 src='"+path+p3+"' border=0>"
		bt += "</td>";
		bt += "</tr></table>";
		obj.innerHTML = bt;
	}
	
/////////////////////////////// End use Button path //////////////////////////////////////

