var currobj;

String.prototype.trim = function(){
	return this.replace(/^\s+|\s+$/g,'');
}

String.prototype.ltrim = function(){
	return this.replace(/^\s+/,'');
}

String.prototype.rtrim = function(){
	return this.replace(/\s+$/,'');
}

function centralize(w,h){
	l = Math.floor((screen.width-w)/2);
	t = Math.floor((screen.height-h)/2-30);
	s = 'left='+l+',top='+t+',height='+h+',width='+w;
	return s;
}

function trim(s){
	rtn_value = s;
	if (rtn_value!=null) rtn_value = s.replace(/^\s*|\s*$/g,'');
	return rtn_value;
}

function isValidPK(s) {
  	return (s.search(/^[a-zA-Z0-9-_+]+$/)!=-1);
}

function isPositiveInt(s) {
  	i = parseInt(s,10);

	if (isNaN(i)){
		return false;
	}else if (i<=0){
		return false;
	}else{
		if (i.toString().length!=s.length) return false;
	}
	return true;
}

function isAlphaNumeric(s) {
  	return (s.search(/^[a-zA-Z0-9]+$/)!=-1);
}

function isNumeric(s) {
  	return (s.search(/^[0-9]+$/)!=-1);
}

function isShortTime(t){
	if (t){
		if (t.length==4) t = '0'+t;

		if (t.length==5){
			var tmp = t.match(/^(\d{1,2})(:)?(\d{1,2})$/);
			
			if (tmp!=null){
				if (tmp[1]>23||tmp[3]>59) return false;
			}else{
				return false;
			}
		}else{
			return false;
		}
	}else{
		return false;
	}

	return true;
}

function isEmail(email){ 
 	var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
 	return email.match(re);
}

function isUrl(s){
	var regexp = /(http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/
	return regexp.test(s);
}

function isValidPriceRemarks(obj,maxChar,maxLine){
	if (obj.value.length>maxChar){
		alert('備註內容只限'+maxChar+'字');
		obj.focus();
		return false;
	}
	if (countLines(obj.value)>maxLine){
		alert('備註內容只限'+maxLine+'行');
		obj.focus();
		return false;
	}
	if (countBlankLines(obj.value)>3){
		alert('請勿濫用分隔行');
		obj.focus();
		return false;
	}
	if (countRestrictedChars(obj.value)>12){
		alert('為避免濫用報價版面，內容不可含有過多的限制字詞或符號');
		obj.focus();
		return false;
	}
	var bw = hasBannedWords(obj.value);
	if (bw){
		alert('內容含有禁止使用的字詞或符號 "'+bw+'"');
		obj.focus();
		return false;
	}
	return true;
}

function countRestrictedChars(s){
	var len = s.length;
	return len > 0 ? len - s.replace(/[#*~=\<\>]/g,'').length : 0;
}

function hasBannedWords(s){
	var words = new Array('♥','★','☆','◇','◆','♦','█','▓','□','■','●','○','◤','◥','◎','㊣','　','╓','╟','╙','※','＊','～','《','》','＃','＜','＞','登入','登記','會員','member','login','register','註冊','用戶','破解');
	var len = s.length;
	if (len>0){
		s = s.replace(/ /g,'').toLowerCase(); // remove all space
		for(var i in words){
			if (s.indexOf(words[i])>-1) return words[i];
		}
	}
	return false;
}

function countLines(s){
	if (s=='') return 0;
	var text = s.trim();
	var split = text.split("\n");
	return split.length;
}

function countBlankLines(s){
	if (s=='') return 0;
	var cnt = 0;
	var text = s.trim();
	var split = text.split("\n");
	for(var i in split){
		if (split[i].trim()=='') cnt++;
	}
	return cnt;
}

function isIP(s) {
	var rtn = true;
	var filter = /^([1-9][0-9]{0,2})+\.([1-9][0-9]{0,2})+\.([1-9][0-9]{0,2})+\.([1-9][0-9]{0,2})+$/;
	if (!filter.test(s)) rtn = false;
	return rtn;	
}

function isPhone(s){
	var valid = true;
	var lastChar = "";
	var repeat = 1;
		
	if (s.length != 8) return false;
	if (!isPositiveInt(s)) return false;

	for (i = 0 ; i < s.length ; i++) {
			chr = s.charAt(i);
			if (i == 0 && chr != 2 && chr != 3 && chr != 5 && chr != 6 && chr != 8 && chr != 9) {
					valid = false;
			}
			// check repeat phone number eg:11111111, 22222222
			repeat = (chr == lastChar) ? repeat + 1 : 1
			lastChar = chr;
	}
	if (repeat == s.length) valid = false;
	return valid;
}

function trimPhone(obj){
	obj.value = obj.value.replace(/[\+\-\s]/g,'');
}
/*
function isPhone(s) {
	ValidChars = "0123456789";
	rtn = true;

	if (s.length==8){
		for (i=0;i<s.length;i++){
			c = s.charAt(i); 
		    if (ValidChars.indexOf(c)==-1){
		    	rtn = false;
				break;
		    }
		}
	}else{
		if (s.length!='') rtn = false;
	}
	
	return rtn;
}
*/

function selectAllRows(){
	obj = document.getElementsByName('key_list[]');
	if (obj.length){
		for (i=0; i<obj.length; i++){
			if (!obj[i].disabled) obj[i].checked = true;
		}
	}else{
		if (!obj.disabled) obj.checked = true; 
	}
}

function isRowSelected(){
	rtn = false;
	obj = document.getElementsByName('key_list[]');

	if (obj.length){
		for (i=0; i<obj.length; i++){ 
			if (obj[i].checked) {
				rtn = true;
				break;
			}
		}
	}else{
		if (obj.checked) rtn = true;
	}
	return rtn;
}

function replaceQueryString(url, param, value){
	var preUrl = '';
	var postUrl = '';
	var newUrl = '';

	start = url.indexOf(param+'=');
	if(start>-1){
   	if (value==''){
   		preUrl = url.substring(0,start-1);
   	}else{
			end = url.indexOf('=', start);
			preUrl = url.substring(0,end)+'='+value;
		}

		startRest = url.indexOf('&',start);
		postUrl = '';
		if(startRest>-1){
			postUrl = url.substring(startRest);
		}
	}else{
		if (value=='') return url;

		preUrl = url;
		if (url.indexOf('?')>-1) postUrl = '&'+param+'='+value;
		else postUrl = '?'+param+'='+value;
	}
	newUrl = preUrl+postUrl;

	return newUrl;
}

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

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 MM_findObj(n, d) { //v4.0
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && document.getElementById) x=document.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

function MM_showHideLayers() { //v3.0
  var i,p,v,obj,args=MM_showHideLayers.arguments;
  for (i=0; i<(args.length-2); i+=3) if ((obj=MM_findObj(args[i]))!=null) { v=args[i+2];
    if (obj.style) { obj=obj.style; v=(v=='show')?'visible':(v='hide')?'hidden':v; }
    obj.visibility=v; }
}

function buildReqString(f){
	var s = '';
	for (i=0;i<f.elements.length;i++){
		if (f.elements[i].type=='text'||f.elements[i].type=='select-one'){
			if (f.elements[i].value!=''){
				if (s!='') s+='&';
				s+=f.elements[i].name+'='+URLEncode(f.elements[i].value);
			}
		}
	}
	return s;
}

function URLEncode(plaintext) {
	plaintext = plaintext.replace(/\r\n/g,"\n");
	var utftext = "";
	
	for (var n = 0; n < plaintext.length; n++) {
		var c = plaintext.charCodeAt(n);

		if (c < 128) {
		    utftext += String.fromCharCode(c);
		} else if((c > 127) && (c < 2048)) {
		    utftext += String.fromCharCode((c >> 6) | 192);
		    utftext += String.fromCharCode((c & 63) | 128);
		} else {
		    utftext += String.fromCharCode((c >> 12) | 224);
		    utftext += String.fromCharCode(((c >> 6) & 63) | 128);
		    utftext += String.fromCharCode((c & 63) | 128);
		}
	}
	
	return escape(utftext);
}

function switchUserMsg(state){
	var frm = document.getElementById('msg_frame');
	var ctr = document.getElementById('msg_container');
	var menu = document.getElementById('menu1');
	var menu_h = 0;

	if (menu) menu_h = getObjectPos(menu).y+18;

	if (frm){
		if (state){
			wsz = getClientSize();
			w = wsz.width;
			h = wsz.height-menu_h;
			t = menu_h;
			frm.style.top = t+'px';
			frm.style.width = w+'px';
			frm.style.height = h+'px';
			ctr.style.top = t+'px';
			ctr.style.width = w+'px';
			ctr.style.height = h+'px';
			frm.style.display = 'block';
			ctr.style.display = 'block';

			// Fix IE animation issue
			setTimeout('reloadImage("img_pbar")',100);
		}else{
			frm.style.display = 'none';
			ctr.style.display = 'none';
		}
	}
}

function reloadImage(id){
	var obj = document.getElementById(id);
	if (obj) obj.src = obj.src;
}

function switchButton(f,state){
	for (i=0;i<f.length;i++){
		obj = f.elements[i];
		if (obj.type=='submit'||obj.type=='reset'||obj.type=='button') obj.disabled = state;
	}
}

function disableForm(f){
	switchButton(f,true);
	switchUserMsg(true);
}

function enableForm(f){
	switchButton(f,false);
	switchUserMsg(false);
}

function preSubmitForm(f){
	window.scrollTo(0,0);
	disableForm(f);
	f.action = f.action+'?f='+Math.random();
}

function resetForm(){
	if (!confirm('確定重設所輸入的內容？')) return false;
}

function addEvent(evt,func){
	if (window.attachEvent){
		window.attachEvent('on'+evt,func);
	}else{
		// Fixed for firefox
		// onload only runs once if the page is cached
		// pageshow can run every time even history.back is called
		if (navigator.userAgent.indexOf('Firefox')>-1&&evt=='load') evt = 'pageshow';

		window.addEventListener(evt,func,false);
	}
}

function openWindow(link,name,w,h,features){
	w = window.open(link,name,centralize(w,h)+',menubar=0,resizable=0,scrollbars=yes,status=yes,'+features);
	w.focus();
}

function refreshWindow(){
	if (opener&&!opener.closed){ 
		opener.location.href=opener.location.href; 
		opener.focus();
	}
	window.close();
}

function viewURL(obj,desc){
	if (obj.value==''){
		alert('請輸入'+desc);
		obj.focus();
	}else if (!isUrl(obj.value)){
		alert('請輸入有效的'+desc);
		obj.focus();
	}else{
		w = window.open(obj.value);
		w.focus();		
	}
}

function showEditor(module,name,desc){
	openWindow('editor.php?module='+module+'&source='+name+'&desc='+URLEncode(desc),'editor',790,600);
}

function getBodySize(){
	var w,h;
	if (document.body.scrollWidth){
		w = document.body.scrollWidth;
		h = document.body.scrollHeight;
	}else{
		w = document.body.offsetWidth;
		h = document.body.offsetHeight;
	}
	return {width:w,height:h};
}

function getClientSize(){
	var w,h;
	if (document.documentElement.clientWidth){
		w = document.documentElement.clientWidth;
		h = document.documentElement.clientHeight;
	}else{
		w = document.body.clientWidth;
		h = document.body.clientHeight;
	}
	return {width:w,height:h};
}

function getObjectPos(obj){
	var curleft = curtop = 0;
	if (obj.offsetParent){
		do {
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop;
		} while (obj = obj.offsetParent);
	}
	return {x:curleft,y:curtop};
}

// Fix firefox history.back issue
window.onunload = function(){};
