var usingIE = document.all ? true:false;

// var str = str.trim();
// alert(str.trim());
String.prototype.trim = function () {
	return this.replace(/^\s*|\s*$/g, "");
}

function charDebug(str)
{
	var ret = new String();
	for(var i=0; i<str.length; i++)
		ret += i + ' [' + str.substring(i, i+1) + ']\n';
	alert(ret);
}

function debug()
{
	var ret = new String();
	for(var i=0; i<arguments.length; i++)
		ret += '[' + arguments[i] + ']\n';
    alert(ret);
}

function getObject(id){

	if(document.getElementById){
		return document.getElementById(id);
	}
	else if(document.all){
		return document.all[id];
	}
	return null;
}

function getElement(formObj, name)
{
	if(formObj==null)
		return;
	for(i=0; i<formObj.elements.length; i++) {
		e = formObj.elements[i];
		if(e.name==name)
			return e;
	}
}

function getQueryString(p){p=p.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]").toLowerCase();var r="[\\?&]"+p+"=([^&#]*)";var rx=new RegExp(r);var rr=rx.exec(window.location.href.toLowerCase());if(rr==null)return "";else return rr[1];} 

function setCookie(cookieName, cookieValue, nDays) { 
	var today = new Date(); 
	var expire = new Date(); 
	if (nDays==null || nDays==0) 
		nDays=1; 
	expire.setTime(today.getTime() + 3600000*24*nDays); 
	document.cookie = cookieName+ "=" + escape(cookieValue) + ";expires=" + expire.toGMTString(); 
} 

function getCookie(c_name)
{
	if(document.cookie.length>0)
	{
		c_start=document.cookie.indexOf(c_name + "=");
		if (c_start!=-1)
		{
			c_start=c_start + c_name.length+1;
			c_end=document.cookie.indexOf(";",c_start);
			if (c_end==-1) c_end=document.cookie.length;
			return unescape(document.cookie.substring(c_start,c_end));
		}
	}
	return "";
}

function getposOffset(overlay, offsettype){
	var totaloffset=(offsettype=="left")? overlay.offsetLeft : overlay.offsetTop;
	var parentEl=overlay.offsetParent;
	while (parentEl!=null){
		totaloffset=(offsettype=="left")? totaloffset+parentEl.offsetLeft : totaloffset+parentEl.offsetTop;
		parentEl=parentEl.offsetParent;
	}
	return totaloffset;
}

function validateEmail(elementValue){   
   var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;   
   return emailPattern.test(elementValue);   
}  

function MM_preloadImages() { //v3.0
	var d=document; 
	if(d.images){ 
		if(!d.MM_p) 
			d.MM_p=new Array();

		var i,j = d.MM_p.length, a = MM_preloadImages.arguments; 
		for(i=0; i<a.length; i++)
			if (a[i].indexOf("#")!=0) { 
				d.MM_p[j]=new Image; 
				d.MM_p[j++].src=a[i];
			}
	}
}

function reloadImg(id) {
   var obj = document.getElementById(id);
   var src = obj.src;
   var pos = src.indexOf('?');
   if (pos >= 0) {
      src = src.substr(0, pos);
   }
   var date = new Date();
   obj.src = src + '?v=' + date.getTime();
   return false;
}

function showHideLayer(obj, status, coordRefID, topOffSet, leftOffSet) 
{
	var subobj = getObject(obj);
	if(subobj==null)	return;

	if(coordRefID!=null) {
		var cf = getObject(coordRefID);
		var xpos = getposOffset(cf, "left")
		var ypos = getposOffset(cf, "top")
		if(leftOffSet!=null)	xpos += leftOffSet;
		if(topOffSet!=null)		ypos += topOffSet;
		subobj.style.left = xpos + "px";
		subobj.style.top = ypos + "px";
	}

	if(status!=null) {
		if(status=='block' || status=='none') {
			subobj.style.display = status;
			return;
		}
	}

	if( subobj.style.display == "block") {
		subobj.style.display = "none";
	} else {
		subobj.style.display = "block";
	}
}

function EncodeParm(str)
{
	var ret = encodeURI(str);
	ret = ret.replace(/&amp;/g, "%26");
	ret = ret.replace(/&/g, "%26");
	ret = ret.replace("%EF%BB%BF", "");		//Remove BOM mark in UTF8 + BOM files
	return ret.replace(/[+]/g, "%2B");
}

function submitForm(formObj)
{
	if(formObj==null)
		return "";

	var postString = "";
	for(i=0; i<formObj.elements.length; i++) {
		e = formObj.elements[i];
		if((e.type=='radio' || e.type=='checkbox') && !e.checked)
			continue;
		if(e.name.length>0 && e.value.length>0)
			postString = postString + e.name + '=' + EncodeParm(e.value) + '&';
	}
	return postString.slice(0, -1);	//remove the last '&';
}

function clearForm(formObj)
{
	for(i=0; i<formObj.elements.length; i++) {
		e = formObj.elements[i];
		if(e.type=='hidden' || e.type=='button' || e.type=='submit')
			continue;
		if(e.type=='select-one')
			e.selectedIndex = 0;
		else if(e.type=='checkbox' || e.type=='radio')
			e.checked = false
		else {
			e.value = '';
		}
	}
}

function openWin(url, w, h, name)
{
	if(!w)                  w = screen.width - 50;
	else if(w>screen.width)	w = screen.width;

	if(!h)                    h = screen.height - 100;
	else if(h>screen.height)  h = screen.height;

	if(!name)
		name = 'newwin';

	win = window.open(url, name, "width=" + w + ",height=" + h + ",resizable=1,scrollbars=1,status=1");
	if(win==null) {
		alert('Sorry, please allow Pop-up on your Browser or hold Ctrl and click again');
	} else
		win.focus()
}

function isDigit(element, min, max)
{
	if(element==null)
		return false;
	if(min!=null && element.value.length<min)
		return false;
	if(max!=null && element.value.length>max)
		return false;

	var reg = new RegExp("^[0-9]+$"); 
	return reg.test(element.value);
}

function validDate(element)
{
    try{
        var d = element.value.split(/\D+/);
        d[0]*=1;
        d[1]-=1;
        d[2]*=1;
        
        var D=new Date(d[0],d[1],d[2]);
        
        if(D.getFullYear()== d[0] && D.getMonth()== d[1] && D.getDate()== d[2]) 
			return D;
        else {
			throw new Error('The date ('+element.value+') does not exist');
			element.value = '';
		}
    }
    catch(er){
        alert(er.message +'\n\nThe date must be in this format: YYYY-MM-DD');
        element.value='';
        return false;
    }
}

function setCheckedValue(radioObj, newValue) {
	if(!radioObj)
		return;
	var radioLength = radioObj.length;
	if(radioLength == undefined) {
		radioObj.checked = (radioObj.value == newValue.toString());
		return;
	}
	for(var i = 0; i < radioLength; i++) {
		radioObj[i].checked = false;
		if(radioObj[i].value == newValue.toString()) {
			radioObj[i].checked = true;
		}
	}
}

function setCheckedValueCheck(formObj, checkObjName, checkedValues) {
	if(formObj==null || checkObjName==null || checkedValues==null)
		return;

	for(i=0; i<formObj.elements.length; i++) {
		e = formObj.elements[i];
		if(e.name==checkObjName)
			if(e.value & checkedValues)
				e.checked = true;
			else
				e.checked = false;
	}
}

var ajax_request = false;
function AJAXconnect(url, parameters, handlerFunction, handlerFunctionParam) {
	ajax_request = false;
	if (window.XMLHttpRequest) { // Mozilla, Safari,...
		ajax_request = new XMLHttpRequest();
		if (ajax_request.overrideMimeType) {
			ajax_request.overrideMimeType('text/html');
		}
	} else if (window.ActiveXObject) { // IE
		try {
			ajax_request = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
			ajax_request = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {}
		}
	}
	if(!ajax_request) {
		alert('錯誤, 請立刻聯繫系統管理員! AJAXconnect');
		return false;
	}
	ajax_request.onreadystatechange = function() {
		if (ajax_request.readyState == 4) {
			if (ajax_request.status == 200) {
				handlerFunction(handlerFunctionParam);
			} else {
				alert('錯誤, 請立刻聯繫系統管理員! AJAXconnect2');
			}
		}
	}
	ajax_request.open('POST', url, true);
	ajax_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	ajax_request.setRequestHeader("Content-length", parameters.length);
	ajax_request.setRequestHeader("Connection", "close");
	ajax_request.send(parameters);
}

/******** general function for fetching dynamic result by HTTP *********/
function httpConnect(url, objInnerHTML, objValue, alertString)
{
	var xmlhttp = null;
	if (window.XMLHttpRequest)
		xmlhttp = new XMLHttpRequest();
	else if (window.ActiveXObject)
		xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
 
	//does not support XMLHTTP, use popup instead
	if (xmlhttp == null)
	{
		alert("請使用 IE 6.0 或更高版本 (1)");
	}
	else {
		xmlhttp.open("GET", url, true);
		xmlhttp.onreadystatechange = function(){ 

			if (xmlhttp.readyState != 4)
				return; 
			if (xmlhttp.status == 200)
			{
				if(objInnerHTML!=null)
					objInnerHTML.innerHTML = xmlhttp.responseText;
				else if(objValue!=null) 
					objValue.value = xmlhttp.responseText;
				else if(alertString!=null) 
					alert(alertString + xmlhttp.responseText);
			} 
			else
			{
				alert("請使用 IE 6.0 或更高版本 (2)");
			}
		}
		xmlhttp.send(null);
	}
}


// If NS -- that is, !IE -- then set up for mouse capture
if(!usingIE) document.captureEvents(Event.MOUSEMOVE)
// Global variables to remember current mouse x-y pos.s
//to use or activate, add  "document.onmousemove = getMouseXY;" into javascript and access mouseX, mouseY for current mouse position
var mouseX = 0;
var mouseY = 0;

function getMouseXY(e) {
	if(usingIE==null || !usingIE) {
		mouseX = e.pageX;
		mouseY = e.pageY;
	} else {
		mouseX = event.clientX + document.body.scrollLeft;
		mouseY = event.clientY + document.body.scrollTop;
	} 	  
	// catch possible negative values in NS4
	if (mouseX < 0){mouseX = 0;}
	if (mouseY < 0){mouseY = 0;}  
	return true;
}

/*
function showWaiting(mode)
{
	var obj = getObject('waitingDIV');
	if(obj==null)	{
		alert("showWaiting cannot find \'waitingDIV\'");
		return;
	}
	if(mode==null || mode==0)
		obj.style.display = 'none';
	else {
		if(mouseY>0) {
			var y = mouseY + 25;
			obj.style.top = y + 'px';
		}
		obj.style.display = 'block';
	}
}
*/
if(typeof jQuery != 'undefined') {
	jQuery.fn.center = function () {     
		this.css("position", "absolute");     
		this.css("top", (jQuery(window).height() - this.height() ) / 2 + jQuery(window).scrollTop() + "px");     
		this.css("left", (jQuery(window).width() - this.width() ) / 2 + jQuery(window).scrollLeft() + "px");     
		return this; 
	} 
}

function showWaiting(mode)
{
	var obj = getObject('waitingDIV');
	if(obj==null)	{
		if(typeof jQuery=='undefined') { 
			alert("showWaiting cannot find \'waitingDIV\'");
			return;
		} else {
			jQuery("<div id='waitingDIV' style='position:absolute; display:none; top: 0px; left: 0px;'><table width=1024><TR bgcolor=#eeeeee><TD align=center><img src=_image/loading.gif></td></table></div>").appendTo("body")
			obj = getObject('waitingDIV');		
		}
	}
	if(mode==null || mode==0)
		obj.style.display = 'none';
	else {
		if(typeof jQuery!='undefined') { 
			jQuery("#waitingDIV").children().css('width', jQuery(window).width());
			jQuery("#waitingDIV").center();
		} else if(mouseY!=null && mouseY>0) {
			var y = mouseY + 25;
			obj.style.top = y + 'px';
		}
		obj.style.display = 'block';
	}
}

